From 3c538613bf585a10b3f6050d1c9c777b0bea8aca Mon Sep 17 00:00:00 2001 From: benym Date: Sun, 16 Aug 2026 16:20:24 +0800 Subject: [PATCH 1/4] fix(native): respect Git ignore during Archive finish --- CHANGELOG.md | 1 + .../scripts/comet-native-archive.mjs | 122 +++++----- .../scripts/comet-native-doctor.mjs | 158 ++++++------- .../scripts/comet-native-next.mjs | 112 ++++----- .../scripts/comet-native-runtime.mjs | 214 +++++++++--------- .../scripts/comet-native-spec.mjs | 114 +++++----- .../native-portable-migration-runtime.ts | 14 +- .../comet-native/native-workspace-finish.ts | 40 +++- .../comet-native/native-doctor-v4.test.ts | 21 ++ .../native-portable-migration-runtime.test.ts | 27 ++- ...native-workspace-finish-git-ignore.test.ts | 126 +++++++++++ 11 files changed, 580 insertions(+), 369 deletions(-) create mode 100644 test/domains/comet-native/native-workspace-finish-git-ignore.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 14d87954e..1cc1fb03e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ All notable changes to @rpamis/comet will be documented in this file. - **Fork pull request greetings**: First-time contributors now receive the repository guidance comment when opening a pull request from a fork, without weakening the read-only permissions of workflows that execute contributor code. - **Pull request template checks**: Pull requests now receive an actionable comment and a failing check when items from the repository template are missing or its checklist is incomplete. +- **Native Archive**: Archive now respects Git ignore rules when staging workspace artifacts and keeps valid portable verification reports from being treated as incomplete migrations. ## What's Changed [0.4.0-beta.18] - 2026-08-13 diff --git a/assets/skills/comet-native/scripts/comet-native-archive.mjs b/assets/skills/comet-native/scripts/comet-native-archive.mjs index 85b481191..07300f32b 100644 --- a/assets/skills/comet-native/scripts/comet-native-archive.mjs +++ b/assets/skills/comet-native/scripts/comet-native-archive.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Qf=Object.create;var oc=Object.defineProperty;var Zf=Object.getOwnPropertyDescriptor;var eh=Object.getOwnPropertyNames;var th=Object.getPrototypeOf,ih=Object.prototype.hasOwnProperty;var fr=(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 rh=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of eh(t))!ih.call(e,n)&&n!==i&&oc(e,n,{get:()=>t[n],enumerable:!(r=Zf(t,n))||r.enumerable});return e};var ti=(e,t,i)=>(i=e!=null?Qf(th(e)):{},rh(t||!e||!e.__esModule?oc(i,"default",{value:e,enumerable:!0}):i,e));var P=y(M=>{"use strict";var fa=Symbol.for("yaml.alias"),dc=Symbol.for("yaml.document"),mr=Symbol.for("yaml.map"),fc=Symbol.for("yaml.pair"),ha=Symbol.for("yaml.scalar"),vr=Symbol.for("yaml.seq"),Ie=Symbol.for("yaml.node.type"),Nh=e=>!!e&&typeof e=="object"&&e[Ie]===fa,bh=e=>!!e&&typeof e=="object"&&e[Ie]===dc,kh=e=>!!e&&typeof e=="object"&&e[Ie]===mr,Sh=e=>!!e&&typeof e=="object"&&e[Ie]===fc,hc=e=>!!e&&typeof e=="object"&&e[Ie]===ha,Eh=e=>!!e&&typeof e=="object"&&e[Ie]===vr;function pc(e){if(e&&typeof e=="object")switch(e[Ie]){case mr:case vr:return!0}return!1}function Ph(e){if(e&&typeof e=="object")switch(e[Ie]){case fa:case mr:case ha:case vr:return!0}return!1}var xh=e=>(hc(e)||pc(e))&&!!e.anchor;M.ALIAS=fa;M.DOC=dc;M.MAP=mr;M.NODE_TYPE=Ie;M.PAIR=fc;M.SCALAR=ha;M.SEQ=vr;M.hasAnchor=xh;M.isAlias=Nh;M.isCollection=pc;M.isDocument=bh;M.isMap=kh;M.isNode=Ph;M.isPair=Sh;M.isScalar=hc;M.isSeq=Eh});var oi=y(pa=>{"use strict";var D=P(),X=Symbol("break visit"),mc=Symbol("skip children"),Se=Symbol("remove node");function gr(e,t){let i=vc(t);D.isDocument(e)?xt(null,e.contents,i,Object.freeze([e]))===Se&&(e.contents=null):xt(null,e,i,Object.freeze([]))}gr.BREAK=X;gr.SKIP=mc;gr.REMOVE=Se;function xt(e,t,i,r){let n=gc(e,t,i,r);if(D.isNode(n)||D.isPair(n))return wc(e,r,n),xt(e,n,i,r);if(typeof n!="symbol"){if(D.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var yc=P(),Rh=oi(),Ch={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ah=e=>e.replace(/[!,[\]{}]/g,t=>Ch[t]),si=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+Ah(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&&yc.isNode(t.contents)){let a={};Rh.visit(t.contents,(o,s)=>{yc.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(` -`)}};si.defaultYaml={explicit:!1,version:"1.2"};si.defaultTags={"!!":"tag:yaml.org,2002:"};Nc.Directives=si});var yr=y(ci=>{"use strict";var bc=P(),_h=oi();function Th(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 kc(e){let t=new Set;return _h.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Sc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function Ih(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=kc(e));let o=Sc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(bc.isScalar(o.node)||bc.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}}ci.anchorIsValid=Th;ci.anchorNames=kc;ci.createNodeAnchors=Ih;ci.findNewAnchor=Sc});var va=y(Ec=>{"use strict";function li(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var jh=P();function Pc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Pc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!jh.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}xc.toJS=Pc});var Nr=y(Cc=>{"use strict";var $h=va(),Rc=P(),Oh=qe(),ga=class{constructor(t){Object.defineProperty(this,Rc.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(!Rc.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=Oh.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?$h.applyReviver(a,{"":s},"",s):s}};Cc.NodeBase=ga});var ui=y(Ac=>{"use strict";var Hh=yr(),Dh=oi(),Ct=P(),Bh=Nr(),Lh=qe(),wa=class extends Bh.NodeBase{constructor(t){super(Ct.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=[],Dh.visit(t,{Node:(a,o)=>{(Ct.isAlias(o)||Ct.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||(Lh.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=br(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(Hh.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 br(e,t,i){if(Ct.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Ct.isCollection(t)){let r=0;for(let n of t.items){let a=br(e,n,i);a>r&&(r=a)}return r}else if(Ct.isPair(t)){let r=br(e,t.key,i),n=br(e,t.value,i);return Math.max(r,n)}return 1}Ac.Alias=wa});var j=y(ya=>{"use strict";var Fh=P(),Mh=Nr(),Vh=qe(),qh=e=>!e||typeof e!="function"&&typeof e!="object",We=class extends Mh.NodeBase{constructor(t){super(Fh.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Vh.toJS(this.value,t,i)}toString(){return String(this.value)}};We.BLOCK_FOLDED="BLOCK_FOLDED";We.BLOCK_LITERAL="BLOCK_LITERAL";We.PLAIN="PLAIN";We.QUOTE_DOUBLE="QUOTE_DOUBLE";We.QUOTE_SINGLE="QUOTE_SINGLE";ya.Scalar=We;ya.isScalarValue=qh});var di=y(Tc=>{"use strict";var Wh=ui(),st=P(),_c=j(),zh="tag:yaml.org,2002:";function Jh(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 Gh(e,t,i){if(st.isDocument(e)&&(e=e.contents),st.isNode(e))return e;if(st.isPair(e)){let f=i.schema[st.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 Wh.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=zh+t.slice(2));let l=Jh(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new _c.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?o[st.MAP]:Symbol.iterator in Object(e)?o[st.SEQ]:o[st.MAP]}a&&(a(l),delete i.onTagObj);let d=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new _c.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}Tc.createNode=Gh});var Sr=y(kr=>{"use strict";var Uh=di(),Ee=P(),Kh=Nr();function Na(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 Uh.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 Ic=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ba=class extends Kh.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=>Ee.isNode(r)||Ee.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Ic(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Ee.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Na(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(Ee.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&&Ee.isScalar(a)?a.value:a:Ee.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Ee.isPair(i))return!1;let r=i.value;return r==null||t&&Ee.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 Ee.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(Ee.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Na(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};kr.Collection=ba;kr.collectionFromPath=Na;kr.isEmptyPath=Ic});var fi=y(Er=>{"use strict";var Yh=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ka(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Xh=(e,t,i)=>e.endsWith(` +var eh=Object.create;var oc=Object.defineProperty;var th=Object.getOwnPropertyDescriptor;var ih=Object.getOwnPropertyNames;var rh=Object.getPrototypeOf,nh=Object.prototype.hasOwnProperty;var fr=(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 ah=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ih(t))!nh.call(e,n)&&n!==i&&oc(e,n,{get:()=>t[n],enumerable:!(r=th(t,n))||r.enumerable});return e};var ti=(e,t,i)=>(i=e!=null?eh(rh(e)):{},ah(t||!e||!e.__esModule?oc(i,"default",{value:e,enumerable:!0}):i,e));var P=y(M=>{"use strict";var fa=Symbol.for("yaml.alias"),dc=Symbol.for("yaml.document"),mr=Symbol.for("yaml.map"),fc=Symbol.for("yaml.pair"),ha=Symbol.for("yaml.scalar"),vr=Symbol.for("yaml.seq"),Ie=Symbol.for("yaml.node.type"),kh=e=>!!e&&typeof e=="object"&&e[Ie]===fa,Sh=e=>!!e&&typeof e=="object"&&e[Ie]===dc,Eh=e=>!!e&&typeof e=="object"&&e[Ie]===mr,Ph=e=>!!e&&typeof e=="object"&&e[Ie]===fc,hc=e=>!!e&&typeof e=="object"&&e[Ie]===ha,xh=e=>!!e&&typeof e=="object"&&e[Ie]===vr;function pc(e){if(e&&typeof e=="object")switch(e[Ie]){case mr:case vr:return!0}return!1}function Rh(e){if(e&&typeof e=="object")switch(e[Ie]){case fa:case mr:case ha:case vr:return!0}return!1}var Ch=e=>(hc(e)||pc(e))&&!!e.anchor;M.ALIAS=fa;M.DOC=dc;M.MAP=mr;M.NODE_TYPE=Ie;M.PAIR=fc;M.SCALAR=ha;M.SEQ=vr;M.hasAnchor=Ch;M.isAlias=kh;M.isCollection=pc;M.isDocument=Sh;M.isMap=Eh;M.isNode=Rh;M.isPair=Ph;M.isScalar=hc;M.isSeq=xh});var oi=y(pa=>{"use strict";var B=P(),X=Symbol("break visit"),mc=Symbol("skip children"),Se=Symbol("remove node");function gr(e,t){let i=vc(t);B.isDocument(e)?xt(null,e.contents,i,Object.freeze([e]))===Se&&(e.contents=null):xt(null,e,i,Object.freeze([]))}gr.BREAK=X;gr.SKIP=mc;gr.REMOVE=Se;function xt(e,t,i,r){let n=gc(e,t,i,r);if(B.isNode(n)||B.isPair(n))return wc(e,r,n),xt(e,n,i,r);if(typeof n!="symbol"){if(B.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var yc=P(),Ah=oi(),_h={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Th=e=>e.replace(/[!,[\]{}]/g,t=>_h[t]),si=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+Th(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&&yc.isNode(t.contents)){let a={};Ah.visit(t.contents,(o,s)=>{yc.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(` +`)}};si.defaultYaml={explicit:!1,version:"1.2"};si.defaultTags={"!!":"tag:yaml.org,2002:"};Nc.Directives=si});var yr=y(ci=>{"use strict";var bc=P(),Ih=oi();function jh(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 kc(e){let t=new Set;return Ih.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Sc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function $h(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=kc(e));let o=Sc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(bc.isScalar(o.node)||bc.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}}ci.anchorIsValid=jh;ci.anchorNames=kc;ci.createNodeAnchors=$h;ci.findNewAnchor=Sc});var va=y(Ec=>{"use strict";function li(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var Oh=P();function Pc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Pc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!Oh.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}xc.toJS=Pc});var Nr=y(Cc=>{"use strict";var Hh=va(),Rc=P(),Dh=qe(),ga=class{constructor(t){Object.defineProperty(this,Rc.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(!Rc.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=Dh.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Hh.applyReviver(a,{"":s},"",s):s}};Cc.NodeBase=ga});var ui=y(Ac=>{"use strict";var Bh=yr(),Lh=oi(),Ct=P(),Fh=Nr(),Mh=qe(),wa=class extends Fh.NodeBase{constructor(t){super(Ct.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=[],Lh.visit(t,{Node:(a,o)=>{(Ct.isAlias(o)||Ct.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||(Mh.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=br(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(Bh.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 br(e,t,i){if(Ct.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Ct.isCollection(t)){let r=0;for(let n of t.items){let a=br(e,n,i);a>r&&(r=a)}return r}else if(Ct.isPair(t)){let r=br(e,t.key,i),n=br(e,t.value,i);return Math.max(r,n)}return 1}Ac.Alias=wa});var $=y(ya=>{"use strict";var Vh=P(),qh=Nr(),Wh=qe(),zh=e=>!e||typeof e!="function"&&typeof e!="object",We=class extends qh.NodeBase{constructor(t){super(Vh.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Wh.toJS(this.value,t,i)}toString(){return String(this.value)}};We.BLOCK_FOLDED="BLOCK_FOLDED";We.BLOCK_LITERAL="BLOCK_LITERAL";We.PLAIN="PLAIN";We.QUOTE_DOUBLE="QUOTE_DOUBLE";We.QUOTE_SINGLE="QUOTE_SINGLE";ya.Scalar=We;ya.isScalarValue=zh});var di=y(Tc=>{"use strict";var Jh=ui(),st=P(),_c=$(),Gh="tag:yaml.org,2002:";function Uh(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 Kh(e,t,i){if(st.isDocument(e)&&(e=e.contents),st.isNode(e))return e;if(st.isPair(e)){let f=i.schema[st.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 Jh.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Gh+t.slice(2));let l=Uh(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new _c.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?o[st.MAP]:Symbol.iterator in Object(e)?o[st.SEQ]:o[st.MAP]}a&&(a(l),delete i.onTagObj);let d=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new _c.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}Tc.createNode=Kh});var Sr=y(kr=>{"use strict";var Yh=di(),Ee=P(),Xh=Nr();function Na(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 Yh.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 Ic=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ba=class extends Xh.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=>Ee.isNode(r)||Ee.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Ic(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Ee.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Na(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(Ee.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&&Ee.isScalar(a)?a.value:a:Ee.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Ee.isPair(i))return!1;let r=i.value;return r==null||t&&Ee.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 Ee.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(Ee.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Na(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};kr.Collection=ba;kr.collectionFromPath=Na;kr.isEmptyPath=Ic});var fi=y(Er=>{"use strict";var Qh=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ka(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Zh=(e,t,i)=>e.endsWith(` `)?ka(i,t):i.includes(` `)?` -`+ka(i,t):(e.endsWith(" ")?"":" ")+i;Er.indentComment=ka;Er.lineComment=Xh;Er.stringifyComment=Yh});var $c=y(hi=>{"use strict";var Qh="flow",Sa="block",Pr="quoted";function Zh(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):f=n-r);let u,p,v=!1,h=-1,m=-1,g=-1;i===Sa&&(h=jc(e,h,t.length),h!==-1&&(f=h+c));for(let w;w=e[h+=1];){if(i===Pr&&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===` +`+ka(i,t):(e.endsWith(" ")?"":" ")+i;Er.indentComment=ka;Er.lineComment=Zh;Er.stringifyComment=Qh});var $c=y(hi=>{"use strict";var ep="flow",Sa="block",Pr="quoted";function tp(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):f=n-r);let u,p,v=!1,h=-1,m=-1,g=-1;i===Sa&&(h=jc(e,h,t.length),h!==-1&&(f=h+c));for(let w;w=e[h+=1];){if(i===Pr&&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===` `)i===Sa&&(h=jc(e,h,t.length)),f=h+t.length+c,u=void 0;else{if(w===" "&&p&&p!==" "&&p!==` `&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==` `&&k!==" "&&(u=h)}if(h>=f)if(u)l.push(u),f=u+c,u=void 0;else if(i===Pr){for(;p===" "||p===" ";)p=w,w=e[h+=1],v=!0;let k=h>g+1?h-2:m-1;if(d[k])return e;l.push(k),d[k]=!0,f=k+c,u=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{"use strict";var me=j(),ze=$c(),Rr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Cr=e=>/^(%|---|\.\.\.)/m.test(e);function ep(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{"use strict";var me=$(),ze=$c(),Rr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Cr=e=>/^(%|---|\.\.\.)/m.test(e);function ip(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;ar)return!0;if(o=a+1,n-o<=r)return!1}return!0}function pi(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Cr(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 d=i.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length `;let f,u;for(u=i.length;u>0;--u){let S=i[u-1];if(S!==` `&&S!==" "&&S!==" ")break}let p=i.substring(u),v=p.indexOf(` @@ -29,12 +29,12 @@ ${i}`)+"'";return t.implicitKey?r:ze.foldFlowLines(r,i,ze.FOLD_FLOW,Rr(t,!1))}fu `)g=m;else break}let N=i.substring(0,g{E=!0});let b=ze.foldFlowLines(`${N}${S}${p}`,l,ze.FOLD_BLOCK,C);if(!E)return`>${k} ${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k} -${l}${N}${i}${p}`}function tp(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:d}=t;if(s&&a.includes(` +${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:d}=t;if(s&&a.includes(` `)||d&&/[[\]{},]/.test(a))return At(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||d||!a.includes(` `)?At(a,t):xr(e,t,i,r);if(!s&&!d&&n!==me.Scalar.PLAIN&&a.includes(` `))return xr(e,t,i,r);if(Cr(a)){if(c==="")return t.forceBlockIndent=!0,xr(e,t,i,r);if(s&&c===l)return At(a,t)}let f=a.replace(/\n+/g,`$& -${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:v}=t.doc.schema;if(v.some(u)||p?.some(u))return At(a,t)}return s?f:ze.foldFlowLines(f,c,ze.FOLD_FLOW,Rr(t,!1))}function ip(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=d=>{switch(d){case me.Scalar.BLOCK_FOLDED:case me.Scalar.BLOCK_LITERAL:return n||a?At(o.value,t):xr(o,t,i,r);case me.Scalar.QUOTE_DOUBLE:return pi(o.value,t);case me.Scalar.QUOTE_SINGLE:return Ea(o.value,t);case me.Scalar.PLAIN:return tp(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:f}=t.options,u=n&&d||f;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Oc.stringifyString=ip});var vi=y(xa=>{"use strict";var rp=yr(),Je=P(),np=fi(),ap=mi();function op(e,t){let i=Object.assign({blockQuote:!0,commentString:np.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 sp(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(Je.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 cp(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Je.isScalar(e)||Je.isCollection(e))&&e.anchor;a&&rp.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 lp(e,t,i,r){if(Je.isPair(e))return e.toString(t,i,r);if(Je.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=Je.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=sp(t.doc.schema.tags,a));let o=cp(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):Je.isScalar(a)?ap.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Je.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} -${t.indent}${s}`:s}xa.createStringifyContext=op;xa.stringify=lp});var Lc=y(Bc=>{"use strict";var je=P(),Hc=j(),Dc=vi(),gi=fi();function up({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:f}}=i,u=je.isNode(e)&&e.comment||null;if(f){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(je.isCollection(e)||!je.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||u&&t==null&&!i.inFlow||je.isCollection(e)||(je.isScalar(e)?e.type===Hc.Scalar.BLOCK_FOLDED||e.type===Hc.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=Dc.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}`,u&&!v?m+=gi.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=gi.lineComment(m,i.indent,l(u))),m=`? ${m} +${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:v}=t.doc.schema;if(v.some(u)||p?.some(u))return At(a,t)}return s?f:ze.foldFlowLines(f,c,ze.FOLD_FLOW,Rr(t,!1))}function np(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=d=>{switch(d){case me.Scalar.BLOCK_FOLDED:case me.Scalar.BLOCK_LITERAL:return n||a?At(o.value,t):xr(o,t,i,r);case me.Scalar.QUOTE_DOUBLE:return pi(o.value,t);case me.Scalar.QUOTE_SINGLE:return Ea(o.value,t);case me.Scalar.PLAIN:return rp(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:f}=t.options,u=n&&d||f;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Oc.stringifyString=np});var vi=y(xa=>{"use strict";var ap=yr(),Je=P(),op=fi(),sp=mi();function cp(e,t){let i=Object.assign({blockQuote:!0,commentString:op.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 lp(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(Je.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 up(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Je.isScalar(e)||Je.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 dp(e,t,i,r){if(Je.isPair(e))return e.toString(t,i,r);if(Je.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=Je.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=lp(t.doc.schema.tags,a));let o=up(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):Je.isScalar(a)?sp.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Je.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} +${t.indent}${s}`:s}xa.createStringifyContext=cp;xa.stringify=dp});var Lc=y(Bc=>{"use strict";var je=P(),Hc=$(),Dc=vi(),gi=fi();function fp({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:f}}=i,u=je.isNode(e)&&e.comment||null;if(f){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(je.isCollection(e)||!je.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||u&&t==null&&!i.inFlow||je.isCollection(e)||(je.isScalar(e)?e.type===Hc.Scalar.BLOCK_FOLDED||e.type===Hc.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=Dc.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}`,u&&!v?m+=gi.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=gi.lineComment(m,i.indent,l(u))),m=`? ${m} ${s}:`):(m=`${m}:`,u&&(m+=gi.lineComment(m,i.indent,l(u))));let g,N,w;je.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&&!u&&je.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!i.inFlow&&!p&&je.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,S=Dc.stringify(t,i,()=>k=!0,()=>h=!0),E=" ";if(u||g||N){if(E=g?` `:"",N){let C=l(N);E+=` ${gi.indentComment(C,i.indent)}`}S===""&&!i.inFlow?E===` @@ -42,34 +42,34 @@ ${gi.indentComment(C,i.indent)}`}S===""&&!i.inFlow?E===` `):E+=` ${i.indent}`}else if(!p&&je.isCollection(t)){let C=S[0],b=S.indexOf(` -`),O=b!==-1,Me=i.inFlow??t.flow??t.items.length===0;if(O||!Me){let Pt=!1;if(O&&(C==="&"||C==="!")){let H=S.indexOf(" ");C==="&"&&H!==-1&&H{"use strict";var Fc=fr("process");function dp(e,...t){e==="debug"&&console.log(...t)}function fp(e,t){(e==="debug"||e==="warn")&&(typeof Fc.emitWarning=="function"?Fc.emitWarning(t):console.warn(t))}Ra.debug=dp;Ra.warn=fp});var jr=y(Ir=>{"use strict";var Tr=P(),Mc=j(),Ar="<<",_r={identify:e=>e===Ar||typeof e=="symbol"&&e.description===Ar,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Mc.Scalar(Symbol(Ar)),{addToJSMap:Vc}),stringify:()=>Ar},hp=(e,t)=>(_r.identify(t)||Tr.isScalar(t)&&(!t.type||t.type===Mc.Scalar.PLAIN)&&_r.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===_r.tag&&i.default);function Vc(e,t,i){let r=qc(e,i);if(Tr.isSeq(r))for(let n of r.items)Aa(e,t,n);else if(Array.isArray(r))for(let n of r)Aa(e,t,n);else Aa(e,t,r)}function Aa(e,t,i){let r=qc(e,i);if(!Tr.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 qc(e,t){return e&&Tr.isAlias(t)?t.resolve(e.doc,e):t}Ir.addMergeToJSMap=Vc;Ir.isMergeKey=hp;Ir.merge=_r});var Ta=y(Jc=>{"use strict";var pp=Ca(),Wc=jr(),mp=vi(),zc=P(),_a=qe();function vp(e,t,{key:i,value:r}){if(zc.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Wc.isMergeKey(e,i))Wc.addMergeToJSMap(e,t,r);else{let n=_a.toJS(i,"",e);if(t instanceof Map)t.set(n,_a.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=gp(i,n,e),o=_a.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 gp(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(zc.isNode(e)&&i?.doc){let r=mp.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)+'..."'),pp.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)}Jc.addPairToJSMap=vp});var Ge=y(Ia=>{"use strict";var Gc=di(),wp=Lc(),yp=Ta(),$r=P();function Np(e,t,i){let r=Gc.createNode(e,void 0,i),n=Gc.createNode(t,void 0,i);return new Or(r,n)}var Or=class e{constructor(t,i=null){Object.defineProperty(this,$r.NODE_TYPE,{value:$r.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return $r.isNode(i)&&(i=i.clone(t)),$r.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return yp.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?wp.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ia.Pair=Or;Ia.createPair=Np});var ja=y(Kc=>{"use strict";var ct=P(),Uc=vi(),Hr=fi();function bp(e,t,i){return(t.inFlow??e.flow?Sp:kp)(e,t,i)}function kp({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,d=Object.assign({},i,{indent:a,type:null}),f=!1,u=[];for(let v=0;vm=null,()=>f=!0);m&&(g+=Hr.lineComment(g,a,l(m))),f&&m&&(f=!1),u.push(r+g)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v{"use strict";var Fc=fr("process");function hp(e,...t){e==="debug"&&console.log(...t)}function pp(e,t){(e==="debug"||e==="warn")&&(typeof Fc.emitWarning=="function"?Fc.emitWarning(t):console.warn(t))}Ra.debug=hp;Ra.warn=pp});var jr=y(Ir=>{"use strict";var Tr=P(),Mc=$(),Ar="<<",_r={identify:e=>e===Ar||typeof e=="symbol"&&e.description===Ar,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Mc.Scalar(Symbol(Ar)),{addToJSMap:Vc}),stringify:()=>Ar},mp=(e,t)=>(_r.identify(t)||Tr.isScalar(t)&&(!t.type||t.type===Mc.Scalar.PLAIN)&&_r.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===_r.tag&&i.default);function Vc(e,t,i){let r=qc(e,i);if(Tr.isSeq(r))for(let n of r.items)Aa(e,t,n);else if(Array.isArray(r))for(let n of r)Aa(e,t,n);else Aa(e,t,r)}function Aa(e,t,i){let r=qc(e,i);if(!Tr.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 qc(e,t){return e&&Tr.isAlias(t)?t.resolve(e.doc,e):t}Ir.addMergeToJSMap=Vc;Ir.isMergeKey=mp;Ir.merge=_r});var Ta=y(Jc=>{"use strict";var vp=Ca(),Wc=jr(),gp=vi(),zc=P(),_a=qe();function wp(e,t,{key:i,value:r}){if(zc.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Wc.isMergeKey(e,i))Wc.addMergeToJSMap(e,t,r);else{let n=_a.toJS(i,"",e);if(t instanceof Map)t.set(n,_a.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=yp(i,n,e),o=_a.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 yp(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(zc.isNode(e)&&i?.doc){let r=gp.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)+'..."'),vp.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)}Jc.addPairToJSMap=wp});var Ge=y(Ia=>{"use strict";var Gc=di(),Np=Lc(),bp=Ta(),$r=P();function kp(e,t,i){let r=Gc.createNode(e,void 0,i),n=Gc.createNode(t,void 0,i);return new Or(r,n)}var Or=class e{constructor(t,i=null){Object.defineProperty(this,$r.NODE_TYPE,{value:$r.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return $r.isNode(i)&&(i=i.clone(t)),$r.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return bp.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?Np.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ia.Pair=Or;Ia.createPair=kp});var ja=y(Kc=>{"use strict";var ct=P(),Uc=vi(),Hr=fi();function Sp(e,t,i){return(t.inFlow??e.flow?Pp:Ep)(e,t,i)}function Ep({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,d=Object.assign({},i,{indent:a,type:null}),f=!1,u=[];for(let v=0;vm=null,()=>f=!0);m&&(g+=Hr.lineComment(g,a,l(m))),f&&m&&(f=!1),u.push(r+g)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;vm=null);l||(l=f.length>d||g.includes(` +`+Hr.indentComment(l(e),c),s&&s()):f&&o&&o(),p}function Pp({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,d=0,f=[];for(let v=0;vm=null);l||(l=f.length>d||g.includes(` `)),v0&&(l||(l=f.reduce((N,w)=>N+w.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),m&&(g+=Hr.lineComment(g,r,s(m))),f.push(g),d=f.length}let{start:u,end:p}=i;if(f.length===0)return u+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=u;for(let h of f)v+=h?` ${a}${n}${h}`:` `;return`${v} -${n}${p}`}else return`${u}${o}${f.join(" ")}${o}${p}`}function Dr({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Hr.indentComment(t(r),e);i.push(a.trimStart())}}Kc.stringifyCollection=bp});var Ke=y(Oa=>{"use strict";var Ep=ja(),Pp=Ta(),xp=Sr(),Ue=P(),Br=Ge(),Rp=j();function wi(e,t){let i=Ue.isScalar(t)?t.value:t;for(let r of e)if(Ue.isPair(r)&&(r.key===t||r.key===i||Ue.isScalar(r.key)&&r.key.value===i))return r}var $a=class extends xp.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ue.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(Br.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;Ue.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Br.Pair(t,t?.value):r=new Br.Pair(t.key,t.value);let n=wi(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Ue.isScalar(n.value)&&Rp.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=wi(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=wi(this.items,t)?.value;return(!i&&Ue.isScalar(n)?n.value:n)??void 0}has(t){return!!wi(this.items,t)}set(t,i){this.add(new Br.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)Pp.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Ue.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})),Ep.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Oa.YAMLMap=$a;Oa.findPair=wi});var _t=y(Xc=>{"use strict";var Cp=P(),Yc=Ke(),Ap={collection:"map",default:!0,nodeClass:Yc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Cp.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Yc.YAMLMap.from(e,t,i)};Xc.map=Ap});var Ye=y(Qc=>{"use strict";var _p=di(),Tp=ja(),Ip=Sr(),Fr=P(),jp=j(),$p=qe(),Ha=class extends Ip.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Fr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Lr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Lr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Fr.isScalar(n)?n.value:n}has(t){let i=Lr(t);return typeof i=="number"&&i=0?t:null}Qc.YAMLSeq=Ha});var Tt=y(el=>{"use strict";var Op=P(),Zc=Ye(),Hp={collection:"seq",default:!0,nodeClass:Zc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Op.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Zc.YAMLSeq.from(e,t,i)};el.seq=Hp});var yi=y(tl=>{"use strict";var Dp=mi(),Bp={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),Dp.stringifyString(e,t,i,r)}};tl.string=Bp});var Mr=y(nl=>{"use strict";var il=j(),rl={identify:e=>e==null,createNode:()=>new il.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new il.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&rl.test.test(e)?e:t.options.nullStr};nl.nullTag=rl});var Da=y(ol=>{"use strict";var Lp=j(),al={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Lp.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&al.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};ol.boolTag=al});var It=y(sl=>{"use strict";function Fp({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=Fp});var La=y(Vr=>{"use strict";var Mp=j(),Ba=It(),Vp={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:Ba.stringifyNumber},qp={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():Ba.stringifyNumber(e)}},Wp={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 Mp.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ba.stringifyNumber};Vr.float=Wp;Vr.floatExp=qp;Vr.floatNaN=Vp});var Ma=y(Wr=>{"use strict";var cl=It(),qr=e=>typeof e=="bigint"||Number.isInteger(e),Fa=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function ll(e,t,i){let{value:r}=e;return qr(r)&&r>=0?i+r.toString(t):cl.stringifyNumber(e)}var zp={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Fa(e,2,8,i),stringify:e=>ll(e,8,"0o")},Jp={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Fa(e,0,10,i),stringify:cl.stringifyNumber},Gp={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Fa(e,2,16,i),stringify:e=>ll(e,16,"0x")};Wr.int=Jp;Wr.intHex=Gp;Wr.intOct=zp});var dl=y(ul=>{"use strict";var Up=_t(),Kp=Mr(),Yp=Tt(),Xp=yi(),Qp=Da(),Va=La(),qa=Ma(),Zp=[Up.map,Yp.seq,Xp.string,Kp.nullTag,Qp.boolTag,qa.intOct,qa.int,qa.intHex,Va.floatNaN,Va.floatExp,Va.float];ul.schema=Zp});var pl=y(hl=>{"use strict";var em=j(),tm=_t(),im=Tt();function fl(e){return typeof e=="bigint"||Number.isInteger(e)}var zr=({value:e})=>JSON.stringify(e),rm=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:zr},{identify:e=>e==null,createNode:()=>new em.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:zr},{identify:fl,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})=>fl(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:zr}],nm={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},am=[tm.map,im.seq].concat(rm,nm);hl.schema=am});var za=y(ml=>{"use strict";var Ni=fr("buffer"),Wa=j(),om=mi(),sm={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ni.Buffer=="function")return Ni.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{"use strict";var Jr=P(),Ja=Ge(),cm=j(),lm=Ye();function vl(e,t){if(Jr.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Ja.Pair(new cm.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} +${n}${p}`}else return`${u}${o}${f.join(" ")}${o}${p}`}function Dr({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Hr.indentComment(t(r),e);i.push(a.trimStart())}}Kc.stringifyCollection=Sp});var Ke=y(Oa=>{"use strict";var xp=ja(),Rp=Ta(),Cp=Sr(),Ue=P(),Br=Ge(),Ap=$();function wi(e,t){let i=Ue.isScalar(t)?t.value:t;for(let r of e)if(Ue.isPair(r)&&(r.key===t||r.key===i||Ue.isScalar(r.key)&&r.key.value===i))return r}var $a=class extends Cp.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ue.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(Br.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;Ue.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Br.Pair(t,t?.value):r=new Br.Pair(t.key,t.value);let n=wi(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Ue.isScalar(n.value)&&Ap.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=wi(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=wi(this.items,t)?.value;return(!i&&Ue.isScalar(n)?n.value:n)??void 0}has(t){return!!wi(this.items,t)}set(t,i){this.add(new Br.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)Rp.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Ue.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})),xp.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Oa.YAMLMap=$a;Oa.findPair=wi});var _t=y(Xc=>{"use strict";var _p=P(),Yc=Ke(),Tp={collection:"map",default:!0,nodeClass:Yc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return _p.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Yc.YAMLMap.from(e,t,i)};Xc.map=Tp});var Ye=y(Qc=>{"use strict";var Ip=di(),jp=ja(),$p=Sr(),Fr=P(),Op=$(),Hp=qe(),Ha=class extends $p.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Fr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Lr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Lr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Fr.isScalar(n)?n.value:n}has(t){let i=Lr(t);return typeof i=="number"&&i=0?t:null}Qc.YAMLSeq=Ha});var Tt=y(el=>{"use strict";var Dp=P(),Zc=Ye(),Bp={collection:"seq",default:!0,nodeClass:Zc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Dp.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Zc.YAMLSeq.from(e,t,i)};el.seq=Bp});var yi=y(tl=>{"use strict";var Lp=mi(),Fp={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),Lp.stringifyString(e,t,i,r)}};tl.string=Fp});var Mr=y(nl=>{"use strict";var il=$(),rl={identify:e=>e==null,createNode:()=>new il.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new il.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&rl.test.test(e)?e:t.options.nullStr};nl.nullTag=rl});var Da=y(ol=>{"use strict";var Mp=$(),al={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Mp.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&al.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};ol.boolTag=al});var It=y(sl=>{"use strict";function Vp({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=Vp});var La=y(Vr=>{"use strict";var qp=$(),Ba=It(),Wp={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:Ba.stringifyNumber},zp={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():Ba.stringifyNumber(e)}},Jp={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 qp.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ba.stringifyNumber};Vr.float=Jp;Vr.floatExp=zp;Vr.floatNaN=Wp});var Ma=y(Wr=>{"use strict";var cl=It(),qr=e=>typeof e=="bigint"||Number.isInteger(e),Fa=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function ll(e,t,i){let{value:r}=e;return qr(r)&&r>=0?i+r.toString(t):cl.stringifyNumber(e)}var Gp={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Fa(e,2,8,i),stringify:e=>ll(e,8,"0o")},Up={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Fa(e,0,10,i),stringify:cl.stringifyNumber},Kp={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Fa(e,2,16,i),stringify:e=>ll(e,16,"0x")};Wr.int=Up;Wr.intHex=Kp;Wr.intOct=Gp});var dl=y(ul=>{"use strict";var Yp=_t(),Xp=Mr(),Qp=Tt(),Zp=yi(),em=Da(),Va=La(),qa=Ma(),tm=[Yp.map,Qp.seq,Zp.string,Xp.nullTag,em.boolTag,qa.intOct,qa.int,qa.intHex,Va.floatNaN,Va.floatExp,Va.float];ul.schema=tm});var pl=y(hl=>{"use strict";var im=$(),rm=_t(),nm=Tt();function fl(e){return typeof e=="bigint"||Number.isInteger(e)}var zr=({value:e})=>JSON.stringify(e),am=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:zr},{identify:e=>e==null,createNode:()=>new im.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:zr},{identify:fl,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})=>fl(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:zr}],om={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},sm=[rm.map,nm.seq].concat(am,om);hl.schema=sm});var za=y(ml=>{"use strict";var Ni=fr("buffer"),Wa=$(),cm=mi(),lm={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ni.Buffer=="function")return Ni.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{"use strict";var Jr=P(),Ja=Ge(),um=$(),dm=Ye();function vl(e,t){if(Jr.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Ja.Pair(new um.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment} -${a.comment}`:r.comment}r=n}e.items[i]=Jr.isPair(r)?r:new Ja.Pair(r)}}else t("Expected a sequence for this tag");return e}function gl(e,t,i){let{replacer:r}=i,n=new lm.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(Ja.createPair(s,c,i))}return n}var um={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vl,createNode:gl};Gr.createPairs=gl;Gr.pairs=um;Gr.resolvePairs=vl});var Ka=y(Ua=>{"use strict";var wl=P(),Ga=qe(),bi=Ke(),dm=Ye(),yl=Ur(),lt=class e extends dm.YAMLSeq{constructor(){super(),this.add=bi.YAMLMap.prototype.add.bind(this),this.delete=bi.YAMLMap.prototype.delete.bind(this),this.get=bi.YAMLMap.prototype.get.bind(this),this.has=bi.YAMLMap.prototype.has.bind(this),this.set=bi.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(wl.isPair(n)?(a=Ga.toJS(n.key,"",i),o=Ga.toJS(n.value,a,i)):a=Ga.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=yl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};lt.tag="tag:yaml.org,2002:omap";var fm={collection:"seq",identify:e=>e instanceof Map,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=yl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)wl.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new lt,i)},createNode:(e,t,i)=>lt.from(e,t,i)};Ua.YAMLOMap=lt;Ua.omap=fm});var El=y(Ya=>{"use strict";var Nl=j();function bl({value:e,source:t},i){return t&&(e?kl:Sl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var kl={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 Nl.Scalar(!0),stringify:bl},Sl={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 Nl.Scalar(!1),stringify:bl};Ya.falseTag=Sl;Ya.trueTag=kl});var Pl=y(Kr=>{"use strict";var hm=j(),Xa=It(),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:Xa.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.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Xa.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.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:Xa.stringifyNumber};Kr.float=vm;Kr.floatExp=mm;Kr.floatNaN=pm});var Rl=y(Si=>{"use strict";var xl=It(),ki=e=>typeof e=="bigint"||Number.isInteger(e);function Yr(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 Qa(e,t,i){let{value:r}=e;if(ki(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return xl.stringifyNumber(e)}var gm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Yr(e,2,2,i),stringify:e=>Qa(e,2,"0b")},wm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Yr(e,1,8,i),stringify:e=>Qa(e,8,"0")},ym={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Yr(e,0,10,i),stringify:xl.stringifyNumber},Nm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Yr(e,2,16,i),stringify:e=>Qa(e,16,"0x")};Si.int=ym;Si.intBin=gm;Si.intHex=Nm;Si.intOct=wm});var eo=y(Za=>{"use strict";var Zr=P(),Xr=Ge(),Qr=Ke(),ut=class e extends Qr.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Zr.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Xr.Pair(t.key,null):i=new Xr.Pair(t,null),Qr.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Qr.findPair(this.items,t);return!i&&Zr.isPair(r)?Zr.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=Qr.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Xr.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(Xr.createPair(o,null,r));return a}};ut.tag="tag:yaml.org,2002:set";var bm={collection:"map",identify:e=>e instanceof Set,nodeClass:ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>ut.from(e,t,i),resolve(e,t){if(Zr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ut,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Za.YAMLSet=ut;Za.set=bm});var io=y(en=>{"use strict";var km=It();function to(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 Cl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return km.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 Sm={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})=>to(e,i),stringify:Cl},Em={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=>to(e,!1),stringify:Cl},Al={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(Al.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),d=t[8];if(d&&d!=="Z"){let f=to(d,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};en.floatTime=Em;en.intTime=Sm;en.timestamp=Al});var Il=y(Tl=>{"use strict";var Pm=_t(),xm=Mr(),Rm=Tt(),Cm=yi(),Am=za(),_l=El(),ro=Pl(),tn=Rl(),_m=jr(),Tm=Ka(),Im=Ur(),jm=eo(),no=io(),$m=[Pm.map,Rm.seq,Cm.string,xm.nullTag,_l.trueTag,_l.falseTag,tn.intBin,tn.intOct,tn.int,tn.intHex,ro.floatNaN,ro.floatExp,ro.float,Am.binary,_m.merge,Tm.omap,Im.pairs,jm.set,no.intTime,no.floatTime,no.timestamp];Tl.schema=$m});var Vl=y(so=>{"use strict";var Hl=_t(),Om=Mr(),Dl=Tt(),Hm=yi(),Dm=Da(),ao=La(),oo=Ma(),Bm=dl(),Lm=pl(),Bl=za(),Ei=jr(),Ll=Ka(),Fl=Ur(),jl=Il(),Ml=eo(),rn=io(),$l=new Map([["core",Bm.schema],["failsafe",[Hl.map,Dl.seq,Hm.string]],["json",Lm.schema],["yaml11",jl.schema],["yaml-1.1",jl.schema]]),Ol={binary:Bl.binary,bool:Dm.boolTag,float:ao.float,floatExp:ao.floatExp,floatNaN:ao.floatNaN,floatTime:rn.floatTime,int:oo.int,intHex:oo.intHex,intOct:oo.intOct,intTime:rn.intTime,map:Hl.map,merge:Ei.merge,null:Om.nullTag,omap:Ll.omap,pairs:Fl.pairs,seq:Dl.seq,set:Ml.set,timestamp:rn.timestamp},Fm={"tag:yaml.org,2002:binary":Bl.binary,"tag:yaml.org,2002:merge":Ei.merge,"tag:yaml.org,2002:omap":Ll.omap,"tag:yaml.org,2002:pairs":Fl.pairs,"tag:yaml.org,2002:set":Ml.set,"tag:yaml.org,2002:timestamp":rn.timestamp};function Mm(e,t,i){let r=$l.get(t);if(r&&!e)return i&&!r.includes(Ei.merge)?r.concat(Ei.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from($l.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(Ei.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ol[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ol).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}so.coreKnownTags=Fm;so.getTags=Mm});var uo=y(ql=>{"use strict";var co=P(),Vm=_t(),qm=Tt(),Wm=yi(),nn=Vl(),zm=(e,t)=>e.keyt.key?1:0,lo=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?nn.getTags(t,"compat"):t?nn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?nn.coreKnownTags:{},this.tags=nn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,co.MAP,{value:Vm.map}),Object.defineProperty(this,co.SCALAR,{value:Wm.string}),Object.defineProperty(this,co.SEQ,{value:qm.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?zm:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};ql.Schema=lo});var zl=y(Wl=>{"use strict";var Jm=P(),fo=vi(),Pi=fi();function Gm(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=fo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Pi.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Jm.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);i.push(Pi.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=fo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Pi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(fo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` +${a.comment}`:r.comment}r=n}e.items[i]=Jr.isPair(r)?r:new Ja.Pair(r)}}else t("Expected a sequence for this tag");return e}function gl(e,t,i){let{replacer:r}=i,n=new dm.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(Ja.createPair(s,c,i))}return n}var fm={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vl,createNode:gl};Gr.createPairs=gl;Gr.pairs=fm;Gr.resolvePairs=vl});var Ka=y(Ua=>{"use strict";var wl=P(),Ga=qe(),bi=Ke(),hm=Ye(),yl=Ur(),lt=class e extends hm.YAMLSeq{constructor(){super(),this.add=bi.YAMLMap.prototype.add.bind(this),this.delete=bi.YAMLMap.prototype.delete.bind(this),this.get=bi.YAMLMap.prototype.get.bind(this),this.has=bi.YAMLMap.prototype.has.bind(this),this.set=bi.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(wl.isPair(n)?(a=Ga.toJS(n.key,"",i),o=Ga.toJS(n.value,a,i)):a=Ga.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=yl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};lt.tag="tag:yaml.org,2002:omap";var pm={collection:"seq",identify:e=>e instanceof Map,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=yl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)wl.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new lt,i)},createNode:(e,t,i)=>lt.from(e,t,i)};Ua.YAMLOMap=lt;Ua.omap=pm});var El=y(Ya=>{"use strict";var Nl=$();function bl({value:e,source:t},i){return t&&(e?kl:Sl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var kl={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 Nl.Scalar(!0),stringify:bl},Sl={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 Nl.Scalar(!1),stringify:bl};Ya.falseTag=Sl;Ya.trueTag=kl});var Pl=y(Kr=>{"use strict";var mm=$(),Xa=It(),vm={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:Xa.stringifyNumber},gm={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():Xa.stringifyNumber(e)}},wm={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 mm.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:Xa.stringifyNumber};Kr.float=wm;Kr.floatExp=gm;Kr.floatNaN=vm});var Rl=y(Si=>{"use strict";var xl=It(),ki=e=>typeof e=="bigint"||Number.isInteger(e);function Yr(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 Qa(e,t,i){let{value:r}=e;if(ki(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return xl.stringifyNumber(e)}var ym={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Yr(e,2,2,i),stringify:e=>Qa(e,2,"0b")},Nm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Yr(e,1,8,i),stringify:e=>Qa(e,8,"0")},bm={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Yr(e,0,10,i),stringify:xl.stringifyNumber},km={identify:ki,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Yr(e,2,16,i),stringify:e=>Qa(e,16,"0x")};Si.int=bm;Si.intBin=ym;Si.intHex=km;Si.intOct=Nm});var eo=y(Za=>{"use strict";var Zr=P(),Xr=Ge(),Qr=Ke(),ut=class e extends Qr.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Zr.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Xr.Pair(t.key,null):i=new Xr.Pair(t,null),Qr.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Qr.findPair(this.items,t);return!i&&Zr.isPair(r)?Zr.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=Qr.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Xr.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(Xr.createPair(o,null,r));return a}};ut.tag="tag:yaml.org,2002:set";var Sm={collection:"map",identify:e=>e instanceof Set,nodeClass:ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>ut.from(e,t,i),resolve(e,t){if(Zr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ut,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Za.YAMLSet=ut;Za.set=Sm});var io=y(en=>{"use strict";var Em=It();function to(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 Cl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Em.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 Pm={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})=>to(e,i),stringify:Cl},xm={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=>to(e,!1),stringify:Cl},Al={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(Al.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),d=t[8];if(d&&d!=="Z"){let f=to(d,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};en.floatTime=xm;en.intTime=Pm;en.timestamp=Al});var Il=y(Tl=>{"use strict";var Rm=_t(),Cm=Mr(),Am=Tt(),_m=yi(),Tm=za(),_l=El(),ro=Pl(),tn=Rl(),Im=jr(),jm=Ka(),$m=Ur(),Om=eo(),no=io(),Hm=[Rm.map,Am.seq,_m.string,Cm.nullTag,_l.trueTag,_l.falseTag,tn.intBin,tn.intOct,tn.int,tn.intHex,ro.floatNaN,ro.floatExp,ro.float,Tm.binary,Im.merge,jm.omap,$m.pairs,Om.set,no.intTime,no.floatTime,no.timestamp];Tl.schema=Hm});var Vl=y(so=>{"use strict";var Hl=_t(),Dm=Mr(),Dl=Tt(),Bm=yi(),Lm=Da(),ao=La(),oo=Ma(),Fm=dl(),Mm=pl(),Bl=za(),Ei=jr(),Ll=Ka(),Fl=Ur(),jl=Il(),Ml=eo(),rn=io(),$l=new Map([["core",Fm.schema],["failsafe",[Hl.map,Dl.seq,Bm.string]],["json",Mm.schema],["yaml11",jl.schema],["yaml-1.1",jl.schema]]),Ol={binary:Bl.binary,bool:Lm.boolTag,float:ao.float,floatExp:ao.floatExp,floatNaN:ao.floatNaN,floatTime:rn.floatTime,int:oo.int,intHex:oo.intHex,intOct:oo.intOct,intTime:rn.intTime,map:Hl.map,merge:Ei.merge,null:Dm.nullTag,omap:Ll.omap,pairs:Fl.pairs,seq:Dl.seq,set:Ml.set,timestamp:rn.timestamp},Vm={"tag:yaml.org,2002:binary":Bl.binary,"tag:yaml.org,2002:merge":Ei.merge,"tag:yaml.org,2002:omap":Ll.omap,"tag:yaml.org,2002:pairs":Fl.pairs,"tag:yaml.org,2002:set":Ml.set,"tag:yaml.org,2002:timestamp":rn.timestamp};function qm(e,t,i){let r=$l.get(t);if(r&&!e)return i&&!r.includes(Ei.merge)?r.concat(Ei.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from($l.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(Ei.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ol[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ol).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}so.coreKnownTags=Vm;so.getTags=qm});var uo=y(ql=>{"use strict";var co=P(),Wm=_t(),zm=Tt(),Jm=yi(),nn=Vl(),Gm=(e,t)=>e.keyt.key?1:0,lo=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?nn.getTags(t,"compat"):t?nn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?nn.coreKnownTags:{},this.tags=nn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,co.MAP,{value:Wm.map}),Object.defineProperty(this,co.SCALAR,{value:Jm.string}),Object.defineProperty(this,co.SEQ,{value:zm.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Gm:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};ql.Schema=lo});var zl=y(Wl=>{"use strict";var Um=P(),fo=vi(),Pi=fi();function Km(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=fo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Pi.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Um.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);i.push(Pi.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=fo.stringify(e.contents,n,()=>s=null,c);s&&(l+=Pi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(fo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` `)?(i.push("..."),i.push(Pi.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(Pi.indentComment(a(c),"")))}return i.join(` `)+` -`}Wl.stringifyDocument=Gm});var xi=y(Jl=>{"use strict";var Um=ui(),jt=Sr(),le=P(),Km=Ge(),Ym=qe(),Xm=uo(),Qm=zl(),ho=yr(),Zm=va(),ev=di(),po=ma(),mo=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 po.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){$t(this.contents)&&this.contents.add(t)}addIn(t,i){$t(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=ho.anchorNames(this);t.anchor=!i||r.has(i)?ho.findNewAnchor(i||"a",r):i}return new Um.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:d}=r??{},{onAnchor:f,setAnchors:u,sourceObjects:p}=ho.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=ev.createNode(t,d,v);return s&&le.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new Km.Pair(n,a)}delete(t){return $t(this.contents)?this.contents.delete(t):!1}deleteIn(t){return jt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):$t(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 jt.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 jt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=jt.collectionFromPath(this.schema,[t],i):$t(this.contents)&&this.contents.set(t,i)}setIn(t,i){jt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=jt.collectionFromPath(this.schema,Array.from(t),i):$t(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 po.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 po.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 Xm.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=Ym.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?Zm.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 Qm.stringifyDocument(this,t)}};function $t(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Jl.Document=mo});var Ai=y(Ci=>{"use strict";var Ri=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},vo=class extends Ri{constructor(t,i,r){super("YAMLParseError",t,i,r)}},go=class extends Ri{constructor(t,i,r){super("YAMLWarning",t,i,r)}},tv=(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)+`… +`}Wl.stringifyDocument=Km});var xi=y(Jl=>{"use strict";var Ym=ui(),jt=Sr(),le=P(),Xm=Ge(),Qm=qe(),Zm=uo(),ev=zl(),ho=yr(),tv=va(),iv=di(),po=ma(),mo=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 po.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){$t(this.contents)&&this.contents.add(t)}addIn(t,i){$t(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=ho.anchorNames(this);t.anchor=!i||r.has(i)?ho.findNewAnchor(i||"a",r):i}return new Ym.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:d}=r??{},{onAnchor:f,setAnchors:u,sourceObjects:p}=ho.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=iv.createNode(t,d,v);return s&&le.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new Xm.Pair(n,a)}delete(t){return $t(this.contents)?this.contents.delete(t):!1}deleteIn(t){return jt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):$t(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 jt.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 jt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=jt.collectionFromPath(this.schema,[t],i):$t(this.contents)&&this.contents.set(t,i)}setIn(t,i){jt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=jt.collectionFromPath(this.schema,Array.from(t),i):$t(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 po.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 po.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 Zm.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=Qm.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?tv.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 $t(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Jl.Document=mo});var Ai=y(Ci=>{"use strict";var Ri=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},vo=class extends Ri{constructor(t,i,r){super("YAMLParseError",t,i,r)}},go=class extends Ri{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)+`… `),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+=`: ${o} ${l} -`}};Ci.YAMLError=Ri;Ci.YAMLParseError=vo;Ci.YAMLWarning=go;Ci.prettifyError=tv});var _i=y(Gl=>{"use strict";function iv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,f="",u="",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),d=!0;break;case"comment":{d||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=b.source.substring(1)||" ";f?f+=u+O:f=O,u="",l=!1;break}case"newline":l?f?f+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=b.source,l=!0,p=!0,(m||g)&&(N=b),d=!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,d=!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,d=!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",d=!1;break;case"comma":if(t){w&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=b,l=!1,d=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!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}}Gl.resolveProps=iv});var an=y(Ul=>{"use strict";function wo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` -`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(wo(t.key)||wo(t.value))return!0}return!1;default:return!0}}Ul.containsNewline=wo});var yo=y(Kl=>{"use strict";var rv=an();function nv(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&rv.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Kl.flowIndentCheck=nv});var No=y(Xl=>{"use strict";var Yl=P();function av(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Yl.isScalar(a)&&Yl.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Xl.mapIncludes=av});var ru=y(iu=>{"use strict";var Ql=Ge(),ov=Ke(),Zl=_i(),sv=an(),eu=yo(),cv=No(),tu="All mapping items must start at the same column";function lv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??ov.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let d of r.items){let{start:f,key:u,sep:p,value:v}=d,h=Zl.resolveProps(f,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",tu)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` -`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||sv.containsNewline(u))&&n(u??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",tu);i.atKey=!0;let g=h.end,N=u?e(i,u,h,n):t(i,g,f,null,h,n);i.schema.compat&&eu.flowIndentCheck(r.indent,u,n),i.atKey=!1,cv.mapIncludes(i,s.items,N)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let w=Zl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.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{"use strict";var uv=Ye(),dv=_i(),fv=yo();function hv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??uv.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:d,value:f}of r.items){let u=dv.resolveProps(d,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||f)f?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=f?e(i,f,u,n):t(i,u.end,d,null,u,n);i.schema.compat&&fv.flowIndentCheck(r.indent,f,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}nu.resolveBlockSeq=hv});var Ot=y(ou=>{"use strict";function pv(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 d=c.substring(1)||" ";n?n+=o+d:n=d,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}}ou.resolveEnd=pv});var uu=y(lu=>{"use strict";var mv=P(),vv=Ge(),su=Ke(),gv=Ye(),wv=Ot(),cu=_i(),yv=an(),Nv=No(),bo="Block collections are not allowed within flow collections",ko=e=>e&&(e.type==="block-map"||e.type==="block-seq");function bv({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:gv.YAMLSeq),l=new c(i.schema);l.flow=!0;let d=i.atRoot;d&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let f=r.offset+r.start.source.length;for(let m=0;m0){let m=wv.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=` -`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}lu.resolveFlowCollection=bv});var fu=y(du=>{"use strict";var kv=P(),Sv=j(),Ev=Ke(),Pv=Ye(),xv=ru(),Rv=au(),Cv=uu();function So(e,t,i,r,n,a){let o=i.type==="block-map"?xv.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Rv.resolveBlockSeq(e,t,i,r,a):Cv.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Av(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offsetu.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),So(e,t,i,n,o)}let l=So(e,t,i,n,o,c),d=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,f=kv.isNode(d)?d:new Sv.Scalar(d);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}du.composeCollection=Av});var Po=y(hu=>{"use strict";var Eo=j();function _v(e,t,i){let r=t.offset,n=Tv(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Eo.Scalar.BLOCK_FOLDED:Eo.Scalar.BLOCK_LITERAL,o=t.source?Iv(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` +`}};Ci.YAMLError=Ri;Ci.YAMLParseError=vo;Ci.YAMLWarning=go;Ci.prettifyError=rv});var _i=y(Gl=>{"use strict";function nv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,f="",u="",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),d=!0;break;case"comment":{d||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let H=b.source.substring(1)||" ";f?f+=u+H:f=H,u="",l=!1;break}case"newline":l?f?f+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=b.source,l=!0,p=!0,(m||g)&&(N=b),d=!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,d=!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,d=!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",d=!1;break;case"comma":if(t){w&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=b,l=!1,d=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!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}}Gl.resolveProps=nv});var an=y(Ul=>{"use strict";function wo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` +`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(wo(t.key)||wo(t.value))return!0}return!1;default:return!0}}Ul.containsNewline=wo});var yo=y(Kl=>{"use strict";var av=an();function ov(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)}}Kl.flowIndentCheck=ov});var No=y(Xl=>{"use strict";var Yl=P();function sv(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Yl.isScalar(a)&&Yl.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Xl.mapIncludes=sv});var ru=y(iu=>{"use strict";var Ql=Ge(),cv=Ke(),Zl=_i(),lv=an(),eu=yo(),uv=No(),tu="All mapping items must start at the same column";function dv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??cv.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let d of r.items){let{start:f,key:u,sep:p,value:v}=d,h=Zl.resolveProps(f,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",tu)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` +`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||lv.containsNewline(u))&&n(u??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",tu);i.atKey=!0;let g=h.end,N=u?e(i,u,h,n):t(i,g,f,null,h,n);i.schema.compat&&eu.flowIndentCheck(r.indent,u,n),i.atKey=!1,uv.mapIncludes(i,s.items,N)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let w=Zl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.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{"use strict";var fv=Ye(),hv=_i(),pv=yo();function mv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??fv.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:d,value:f}of r.items){let u=hv.resolveProps(d,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||f)f?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=f?e(i,f,u,n):t(i,u.end,d,null,u,n);i.schema.compat&&pv.flowIndentCheck(r.indent,f,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}nu.resolveBlockSeq=mv});var Ot=y(ou=>{"use strict";function vv(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 d=c.substring(1)||" ";n?n+=o+d:n=d,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}}ou.resolveEnd=vv});var uu=y(lu=>{"use strict";var gv=P(),wv=Ge(),su=Ke(),yv=Ye(),Nv=Ot(),cu=_i(),bv=an(),kv=No(),bo="Block collections are not allowed within flow collections",ko=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Sv({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:yv.YAMLSeq),l=new c(i.schema);l.flow=!0;let d=i.atRoot;d&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let f=r.offset+r.start.source.length;for(let m=0;m0){let m=Nv.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=` +`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}lu.resolveFlowCollection=Sv});var fu=y(du=>{"use strict";var Ev=P(),Pv=$(),xv=Ke(),Rv=Ye(),Cv=ru(),Av=au(),_v=uu();function So(e,t,i,r,n,a){let o=i.type==="block-map"?Cv.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Av.resolveBlockSeq(e,t,i,r,a):_v.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Tv(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offsetu.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),So(e,t,i,n,o)}let l=So(e,t,i,n,o,c),d=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,f=Ev.isNode(d)?d:new Pv.Scalar(d);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}du.composeCollection=Tv});var Po=y(hu=>{"use strict";var Eo=$();function Iv(e,t,i){let r=t.offset,n=jv(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Eo.Scalar.BLOCK_FOLDED:Eo.Scalar.BLOCK_LITERAL,o=t.source?$v(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,d=0;for(let h=0;hc&&(c=m.length);else{m.length=s;--h)o[h][0].length>c&&(s=h+1);let f="",u="",p=!1;for(let h=0;hc||g[0]===" "?(u===" "?u=` @@ -84,41 +84,41 @@ ${l} `+o[h][0].slice(c);f[f.length-1]!==` `&&(f+=` `);break;default:f+=` -`}let v=r+n.length+t.source.length;return{value:f,type:a,comment:n.comment,range:[r,v,v]}}function Tv({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let u=1;u{"use strict";var xo=j(),jv=Ot();function $v(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(u,p,v)=>i(r+u,p,v);switch(n){case"scalar":s=xo.Scalar.PLAIN,c=Ov(a,l);break;case"single-quoted-scalar":s=xo.Scalar.QUOTE_SINGLE,c=Hv(a,l);break;case"double-quoted-scalar":s=xo.Scalar.QUOTE_DOUBLE,c=Dv(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let d=r+a.length,f=jv.resolveEnd(o,d,t,i);return{value:c,type:s,comment:f.comment,range:[r,d,f.offset]}}function Ov(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),pu(e)}function Hv(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),pu(e.slice(1,-1)).replace(/''/g,"'")}function pu(e){let t,i;try{t=new RegExp(`(.*?)(?{"use strict";var xo=$(),Ov=Ot();function Hv(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(u,p,v)=>i(r+u,p,v);switch(n){case"scalar":s=xo.Scalar.PLAIN,c=Dv(a,l);break;case"single-quoted-scalar":s=xo.Scalar.QUOTE_SINGLE,c=Bv(a,l);break;case"double-quoted-scalar":s=xo.Scalar.QUOTE_DOUBLE,c=Lv(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let d=r+a.length,f=Ov.resolveEnd(o,d,t,i);return{value:c,type:s,comment:f.comment,range:[r,d,f.offset]}}function Dv(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),pu(e)}function Bv(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),pu(e.slice(1,-1)).replace(/''/g,"'")}function pu(e){let t,i;try{t=new RegExp(`(.*?)(?a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Bv(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===` +`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Fv(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===` `||r==="\r")&&!(r==="\r"&&e[t+2]!==` `);)r===` `&&(i+=` -`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Lv={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Fv(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}}mu.resolveFlowScalar=$v});var wu=y(gu=>{"use strict";var dt=P(),vu=j(),Mv=Po(),Vv=Ro();function qv(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Mv.resolveBlockScalar(e,t,r):Vv.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[dt.SCALAR]:c?l=Wv(e.schema,n,c,i,r):t.type==="scalar"?l=zv(e,n,t,r):l=e.schema[dt.SCALAR];let d;try{let f=l.resolve(n,u=>r(i??t,"TAG_RESOLVE_FAILED",u),e.options);d=dt.isScalar(f)?f:new vu.Scalar(f)}catch(f){let u=f instanceof Error?f.message:String(f);r(i??t,"TAG_RESOLVE_FAILED",u),d=new vu.Scalar(n)}return d.range=s,d.source=n,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Wv(e,t,i,r,n){if(i==="!")return e[dt.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[dt.SCALAR])}function zv({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[dt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[dt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}gu.composeScalar=qv});var Nu=y(yu=>{"use strict";function Jv(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}yu.emptyScalarPosition=Jv});var Su=y(Ao=>{"use strict";var Gv=ui(),Uv=P(),Kv=fu(),bu=wu(),Yv=Ot(),Xv=Nu(),Qv={composeNode:ku,composeEmptyNode:Co};function ku(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,d=!0;switch(t.type){case"alias":l=Zv(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=bu.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Kv.composeCollection(Qv,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(f){let u=f instanceof Error?f.message:String(f);r(t,"RESOURCE_EXHAUSTION",u)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",f),d=!1}}return l??(l=Co(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&&(!Uv.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&&d&&(l.srcToken=t),l}function Co(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:Xv.emptyScalarPosition(t,i,r),indent:-1,source:""},f=bu.composeScalar(e,d,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 Zv({options:e},{offset:t,source:i,end:r},n){let a=new Gv.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=Yv.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ao.composeEmptyNode=Co;Ao.composeNode=ku});var xu=y(Pu=>{"use strict";var eg=xi(),Eu=Su(),tg=Ot(),ig=_i();function rg(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new eg.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=ig.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Eu.composeNode(l,n,d,o):Eu.composeEmptyNode(l,d.end,r,null,d,o);let f=c.contents.range[2],u=tg.resolveEnd(a,f,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,f,u.offset],c}Pu.composeDoc=rg});var To=y(Au=>{"use strict";var ng=fr("process"),ag=ma(),og=xi(),Ti=Ai(),Ru=P(),sg=xu(),cg=Ot();function Ii(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 Cu(e){let t="",i=!1,r=!1;for(let n=0;n{"use strict";var dt=P(),vu=$(),qv=Po(),Wv=Ro();function zv(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?qv.resolveBlockScalar(e,t,r):Wv.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[dt.SCALAR]:c?l=Jv(e.schema,n,c,i,r):t.type==="scalar"?l=Gv(e,n,t,r):l=e.schema[dt.SCALAR];let d;try{let f=l.resolve(n,u=>r(i??t,"TAG_RESOLVE_FAILED",u),e.options);d=dt.isScalar(f)?f:new vu.Scalar(f)}catch(f){let u=f instanceof Error?f.message:String(f);r(i??t,"TAG_RESOLVE_FAILED",u),d=new vu.Scalar(n)}return d.range=s,d.source=n,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Jv(e,t,i,r,n){if(i==="!")return e[dt.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[dt.SCALAR])}function Gv({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[dt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[dt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}gu.composeScalar=zv});var Nu=y(yu=>{"use strict";function Uv(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}yu.emptyScalarPosition=Uv});var Su=y(Ao=>{"use strict";var Kv=ui(),Yv=P(),Xv=fu(),bu=wu(),Qv=Ot(),Zv=Nu(),eg={composeNode:ku,composeEmptyNode:Co};function ku(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,d=!0;switch(t.type){case"alias":l=tg(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=bu.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Xv.composeCollection(eg,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(f){let u=f instanceof Error?f.message:String(f);r(t,"RESOURCE_EXHAUSTION",u)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",f),d=!1}}return l??(l=Co(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&&(!Yv.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&&d&&(l.srcToken=t),l}function Co(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:Zv.emptyScalarPosition(t,i,r),indent:-1,source:""},f=bu.composeScalar(e,d,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 tg({options:e},{offset:t,source:i,end:r},n){let a=new Kv.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=Qv.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ao.composeEmptyNode=Co;Ao.composeNode=ku});var xu=y(Pu=>{"use strict";var ig=xi(),Eu=Su(),rg=Ot(),ng=_i();function ag(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new ig.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=ng.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Eu.composeNode(l,n,d,o):Eu.composeEmptyNode(l,d.end,r,null,d,o);let f=c.contents.range[2],u=rg.resolveEnd(a,f,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,f,u.offset],c}Pu.composeDoc=ag});var To=y(Au=>{"use strict";var og=fr("process"),sg=ma(),cg=xi(),Ti=Ai(),Ru=P(),lg=xu(),ug=Ot();function Ii(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 Cu(e){let t="",i=!1,r=!1;for(let n=0;n{let o=Ii(i);a?this.warnings.push(new Ti.YAMLWarning(o,r,n)):this.errors.push(new Ti.YAMLParseError(o,r,n))},this.directives=new ag.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Cu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} +`)+(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 _o=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Ii(i);a?this.warnings.push(new Ti.YAMLWarning(o,r,n)):this.errors.push(new Ti.YAMLParseError(o,r,n))},this.directives=new sg.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Cu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ru.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ru.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r} ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r} -${o}`:r}}if(i){for(let a=0;a{let a=Ii(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=sg.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 Ti.YAMLParseError(Ii(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 Ti.YAMLParseError(Ii(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=cg.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} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Ti.YAMLParseError(Ii(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 og.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}}};Au.Composer=_o});var Iu=y(on=>{"use strict";var lg=Po(),ug=Ro(),dg=Ai(),_u=mi();function fg(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 ug.resolveFlowScalar(e,t,r);case"block-scalar":return lg.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function hg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=_u.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:` +${o}`:r}}if(i){for(let a=0;a{let a=Ii(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=lg.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 Ti.YAMLParseError(Ii(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 Ti.YAMLParseError(Ii(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=ug.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} +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Ti.YAMLParseError(Ii(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 cg.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}}};Au.Composer=_o});var Iu=y(on=>{"use strict";var dg=Po(),fg=Ro(),hg=Ai(),_u=mi();function pg(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 hg.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return fg.resolveFlowScalar(e,t,r);case"block-scalar":return dg.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function mg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=_u.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:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),d=s.substring(0,l),f=s.substring(l+1)+` `,u=[{type:"block-scalar-header",offset:a,indent:r,source:d}];return Tu(u,c)||u.push({type:"newline",offset:-1,indent:r,source:` -`}),{type:"block-scalar",offset:a,indent:r,props:u,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function pg(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=_u.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":mg(e,c);break;case'"':Io(e,c,"double-quoted-scalar");break;case"'":Io(e,c,"single-quoted-scalar");break;default:Io(e,c,"scalar")}}function mg(e,t){let i=t.indexOf(` +`}),{type:"block-scalar",offset:a,indent:r,props:u,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function vg(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=_u.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":gg(e,c);break;case'"':Io(e,c,"double-quoted-scalar");break;case"'":Io(e,c,"single-quoted-scalar");break;default:Io(e,c,"scalar")}}function gg(e,t){let i=t.indexOf(` `),r=t.substring(0,i),n=t.substring(i+1)+` `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];Tu(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Tu(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 Io(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:` -`};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})}}}on.createScalarToken=hg;on.resolveAsScalar=fg;on.setScalarValue=pg});var $u=y(ju=>{"use strict";var vg=e=>"type"in e?cn(e):sn(e);function cn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=cn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=sn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=sn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=sn(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 sn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=cn(t)),i)for(let a of i)n+=a.source;return r&&(n+=cn(r)),n}ju.stringify=vg});var Bu=y(Du=>{"use strict";var jo=Symbol("break visit"),gg=Symbol("skip children"),Ou=Symbol("remove item");function ft(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Hu(Object.freeze([]),e,t)}ft.BREAK=jo;ft.SKIP=gg;ft.REMOVE=Ou;ft.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};ft.parentCollection=(e,t)=>{let i=ft.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 Hu(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{"use strict";var $o=Iu(),wg=$u(),yg=Bu(),Oo="\uFEFF",Ho="",Do="",Bo="",Ng=e=>!!e&&"items"in e,bg=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function kg(e){switch(e){case Oo:return"";case Ho:return"";case Do:return"";case Bo:return"";default:return JSON.stringify(e)}}function Sg(e){switch(e){case Oo:return"byte-order-mark";case Ho:return"doc-mode";case Do:return"flow-error-end";case Bo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`};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})}}}on.createScalarToken=mg;on.resolveAsScalar=pg;on.setScalarValue=vg});var $u=y(ju=>{"use strict";var wg=e=>"type"in e?cn(e):sn(e);function cn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=cn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=sn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=sn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=sn(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 sn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=cn(t)),i)for(let a of i)n+=a.source;return r&&(n+=cn(r)),n}ju.stringify=wg});var Bu=y(Du=>{"use strict";var jo=Symbol("break visit"),yg=Symbol("skip children"),Ou=Symbol("remove item");function ft(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Hu(Object.freeze([]),e,t)}ft.BREAK=jo;ft.SKIP=yg;ft.REMOVE=Ou;ft.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};ft.parentCollection=(e,t)=>{let i=ft.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 Hu(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{"use strict";var $o=Iu(),Ng=$u(),bg=Bu(),Oo="\uFEFF",Ho="",Do="",Bo="",kg=e=>!!e&&"items"in e,Sg=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Eg(e){switch(e){case Oo:return"";case Ho:return"";case Do:return"";case Bo:return"";default:return JSON.stringify(e)}}function Pg(e){switch(e){case Oo:return"byte-order-mark";case Ho:return"doc-mode";case Do:return"flow-error-end";case Bo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Q.createScalarToken=$o.createScalarToken;Q.resolveAsScalar=$o.resolveAsScalar;Q.setScalarValue=$o.setScalarValue;Q.stringify=wg.stringify;Q.visit=yg.visit;Q.BOM=Oo;Q.DOCUMENT=Ho;Q.FLOW_END=Do;Q.SCALAR=Bo;Q.isCollection=Ng;Q.isScalar=bg;Q.prettyToken=kg;Q.tokenType=Sg});var Mo=y(Fu=>{"use strict";var ji=ln();function ve(e){switch(e){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var Lu=new Set("0123456789ABCDEFabcdef"),Eg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),un=new Set(",[]{}"),Pg=new Set(` ,[]{} -\r `),Lo=e=>!e||Pg.has(e),Fo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(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===` +`: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}Q.createScalarToken=$o.createScalarToken;Q.resolveAsScalar=$o.resolveAsScalar;Q.setScalarValue=$o.setScalarValue;Q.stringify=Ng.stringify;Q.visit=bg.visit;Q.BOM=Oo;Q.DOCUMENT=Ho;Q.FLOW_END=Do;Q.SCALAR=Bo;Q.isCollection=kg;Q.isScalar=Sg;Q.prettyToken=Eg;Q.tokenType=Pg});var Mo=y(Fu=>{"use strict";var ji=ln();function ve(e){switch(e){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var Lu=new Set("0123456789ABCDEFabcdef"),xg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),un=new Set(",[]{}"),Rg=new Set(` ,[]{} +\r `),Lo=e=>!e||Rg.has(e),Fo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(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===` `?!0:i==="\r"?this.buffer[t+1]===` `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===` `||!n&&!this.atEnd)return t+r+1}return i===` @@ -133,22 +133,22 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield ji.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&&un.has(a))break;i=r}else if(ve(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===` `?(r+=1,n=` `,a=this.buffer[r+1]):i=r),a==="#"||t&&un.has(a))break;if(n===` -`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&un.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ji.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(Lo),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ve(r)||i&&un.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(Eg.has(i))i=this.buffer[++t];else if(i==="%"&&Lu.has(this.buffer[t+1])&&Lu.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` +`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&un.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ji.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(Lo),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ve(r)||i&&un.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(xg.has(i))i=this.buffer[++t];else if(i==="%"&&Lu.has(this.buffer[t+1])&&Lu.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,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)}};Fu.Lexer=Fo});var qo=y(Mu=>{"use strict";var Vo=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var xg=fr("process"),Vu=ln(),Rg=Mo();function Xe(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function fn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&Wu(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&&qu(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent0&&(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)}};Fu.Lexer=Fo});var qo=y(Mu=>{"use strict";var Vo=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var Cg=fr("process"),Vu=ln(),Ag=Mo();function Xe(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function fn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&Wu(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&&qu(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.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;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":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(Xe(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(zu(i.key)&&!Xe(i.sep,"newline")){let o=Ht(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Xe(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ht(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]}):Xe(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&&!Xe(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)){fn(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||Xe(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=dn(r),a=Ht(n);Wu(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=dn(t),r=Ht(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=dn(t),r=Ht(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())}}};Ju.Parser=Wo});var Xu=y(Oi=>{"use strict";var Gu=To(),Cg=xi(),$i=Ai(),Ag=Ca(),_g=P(),Tg=qo(),Uu=zo();function Ku(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Tg.LineCounter||null,prettyErrors:t}}function Ig(e,t={}){let{lineCounter:i,prettyErrors:r}=Ku(t),n=new Uu.Parser(i?.addNewLine),a=new Gu.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach($i.prettifyError(e,i)),s.warnings.forEach($i.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Yu(e,t={}){let{lineCounter:i,prettyErrors:r}=Ku(t),n=new Uu.Parser(i?.addNewLine),a=new Gu.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 $i.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach($i.prettifyError(e,i)),o.warnings.forEach($i.prettifyError(e,i))),o}function jg(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Yu(e,i);if(!n)return null;if(n.warnings.forEach(a=>Ag.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 $g(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 _g.isDocument(e)&&!r?e.toString(i):new Cg.Document(e,r,i).toString(i)}Oi.parse=jg;Oi.parseAllDocuments=Ig;Oi.parseDocument=Yu;Oi.stringify=$g});var Dt=y(x=>{"use strict";var Og=To(),Hg=xi(),Dg=uo(),Jo=Ai(),Bg=ui(),Qe=P(),Lg=Ge(),Fg=j(),Mg=Ke(),Vg=Ye(),qg=ln(),Wg=Mo(),zg=qo(),Jg=zo(),hn=Xu(),Qu=oi();x.Composer=Og.Composer;x.Document=Hg.Document;x.Schema=Dg.Schema;x.YAMLError=Jo.YAMLError;x.YAMLParseError=Jo.YAMLParseError;x.YAMLWarning=Jo.YAMLWarning;x.Alias=Bg.Alias;x.isAlias=Qe.isAlias;x.isCollection=Qe.isCollection;x.isDocument=Qe.isDocument;x.isMap=Qe.isMap;x.isNode=Qe.isNode;x.isPair=Qe.isPair;x.isScalar=Qe.isScalar;x.isSeq=Qe.isSeq;x.Pair=Lg.Pair;x.Scalar=Fg.Scalar;x.YAMLMap=Mg.YAMLMap;x.YAMLSeq=Vg.YAMLSeq;x.CST=qg;x.Lexer=Wg.Lexer;x.LineCounter=zg.LineCounter;x.Parser=Jg.Parser;x.parse=hn.parse;x.parseAllDocuments=hn.parseAllDocuments;x.parseDocument=hn.parseDocument;x.stringify=hn.stringify;x.visit=Qu.visit;x.visitAsync=Qu.visitAsync});import{randomUUID as vb}from"node:crypto";import{promises as W}from"node:fs";import U from"node:path";import{execFileSync as nh}from"child_process";import ri from"path";function ii(e,t){return nh("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function ah(e,t){let i=ri.normalize(e),r=ri.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function F(e){try{let t=ri.resolve(ii(e,["rev-parse","--show-toplevel"])),r=ii(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?ri.resolve(r.slice(9)):t,a=null;try{a=ii(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!ah(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function sc(e){try{ii(e,["rev-parse","--is-inside-work-tree"]);let t=ii(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:ri.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 ot(e){return sc(e).map(t=>t.root)}import{randomUUID as oh}from"crypto";import{promises as z}from"fs";import he from"path";function Ve(e){return e!==0&&e!==0n&&e!=="0"}function ie(e,t){return Ve(e.dev)&&Ve(t.dev)&&Ve(e.ino)&&Ve(t.ino)}function A(e,t){let i=Ve(e.dev)&&Ve(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ve(e.ino)&&Ve(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ua(e,t){let i=he.relative(e,t);return i===""||!he.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${he.sep}`)}function sh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function la(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ie(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cc(e){let t=await z.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 z.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ni(e){for(let t of e){let i=await z.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!sh(t,i)||await z.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function ch(e,t){let i=he.resolve(e),r=he.resolve(t);if(!ua(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await cc(i)],a=he.relative(i,r).split(he.sep).filter(Boolean),o=i;for(let s of a){await ni(n),o=he.join(o,s);try{await z.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await cc(o);if(!ua(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ni(n),n}async function lh(e){let t;try{t=await z.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 uh(e,t,i={}){let r=he.dirname(e),n=i.containedRoot?await ch(i.containedRoot,r):null;n||await z.mkdir(r,{recursive:!0});let a=he.join(r,`.${he.basename(e)}.${oh()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await z.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([z.lstat(a),z.realpath(a)]);if(await ni(n),!c.isFile()||c.isSymbolicLink()||!la(s,c)||!ua(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!la(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await ni(n);let c=await z.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!la(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await z.link(a,e),await z.unlink(a)):await z.rename(a,e),await lh(r)}catch(c){if(await o?.close(),!n)await z.rm(a,{force:!0});else try{await ni(n),await z.rm(a,{force:!0})}catch{}throw c}}async function K(e,t,i={}){await uh(e,t,i)}async function Y(e,t,i={}){await K(e,JSON.stringify(t,null,2)+` -`,i)}import{createHash as ph}from"node:crypto";import{promises as pe}from"node:fs";import ce from"node:path";import{TextDecoder as mh}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"]),fh=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function hh(e){return e.toLowerCase().startsWith(".env")}function ai(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>hh(r))?"environment-file":i.some(r=>fh.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 pr=1024*1024;function da(e,t){let i=ce.relative(e,t);return i===""||!ce.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ce.sep}`)}function vh(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=ai(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 gh(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 hr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ie(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lc(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 yh(e,t){let i=ce.resolve(e),r=ce.resolve(t);if(!da(i,r))throw new Error("Native artifact path is outside its root");let n=[await lc(i)],a=i;for(let o of ce.relative(i,r).split(ce.sep).filter(Boolean)){a=ce.join(a,o);let s=await lc(a);if(!da(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function uc(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 I(e){let t=vh(e.ref),i=e.maxBytes===null?null:gh(e.maxBytes??pr),r=ce.resolve(e.root,...t.split("/")),n=await yh(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(!da(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,d]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await uc(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!hr(a,c)||!hr(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let w=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,w),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>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 uc(n),!h.isFile()||h.isSymbolicLink()||m!==o||!hr(c,v)||!hr(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(f,u),N;try{N=new mh("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:u,hash:e.includeHash===!1?null:ph("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var js=ti(Dt(),1);import Kt from"path";var Uo=ti(Dt(),1);import pn from"path";var Hi=64*1024,mn=1024,vn=64,Ko=5,Gg=[".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/**",".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/**"],Ug=["**/.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"],Kg=[...Gg,...Ug].sort((e,t)=>e.localeCompare(t,"en"));var re={include:["**/*"],exclude:[...Kg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Yg(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||pn.posix.isAbsolute(i)||pn.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 ht(e){let t=Yg(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ed(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 gn(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||pn.posix.isAbsolute(r)||pn.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 Bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function td(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 Yo(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>mn)throw new Error(`${t} exceeds ${mn} characters`);let i=0;for(let r=0;rvn)throw new Error(`${t} contains more than ${vn} wildcard tokens`);return e}function Zu(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=>Yo(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Go(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 Xg(e){if(e===void 0)return{...re,include:[...re.include],exclude:[...re.exclude]};let t=Bt(e,"native.snapshot");return{include:Zu(t.include,"native.snapshot.include",re.include),exclude:Zu(t.exclude,"native.snapshot.exclude",re.exclude),max_files:Go(t.max_files,re.max_files,"native.snapshot.max_files"),max_total_bytes:Go(t.max_total_bytes,re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Go(t.max_duration_ms,re.max_duration_ms,"native.snapshot.max_duration_ms")}}function Qg(e){if(e===void 0)return;let t=Bt(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=Bt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:ht(r),toArtifactRoot:ht(n),stage:a,...o?{cleanup:o}:{}}}function Zg(e,t={}){let i=Bt(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??Ko;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Qg(i.pending_root_move);return{artifact_root:ht(r),language:td(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Xg(i.snapshot),...s?{pending_root_move:s}:{}}}function ew(e){let t=Bt(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:ed(t.artifact_layout),language:td(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function tw(e){let i=Bt(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)=>gn(r,`hook.allow_paths[${n}]`)))]}}function iw(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function rw(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(d=>d!=="native"&&d!=="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 Di(e,t={}){let i=(0,Uo.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=iw(n.ambient_resume),o=n.hook===void 0?void 0:tw(n.hook),s=n.native===void 0?void 0:Zg(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:ew(n.classic),l=rw(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 wn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:ht(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Ko,snapshot:{...re,include:[...re.include],exclude:[...re.exclude]}}}}import{createHash as aw}from"crypto";import{promises as bn}from"fs";import Ze from"path";import{constants as yn,promises as pt}from"fs";var ge=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Xo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function id(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Bi(e){return{dev:e.dev,ino:e.ino,birthtime:Xo(e)}}function Nn(e,t){let i=Bi(e),r=Bi(t);return ie(i,r)?A(i,r):A(i,r)&&Xo(e)===Xo(t)&&id(e)===id(t)&&e.size===t.size}async function mt(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 pt.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 pt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Bi(a)});let s=process.platform==="win32"?yn.O_RDONLY:yn.O_RDONLY|yn.O_NOFOLLOW|yn.O_NONBLOCK,c;try{c=await pt.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,d,f]=await Promise.all([c.stat({bigint:n}),pt.lstat(e,{bigint:n}),pt.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||f!==o||!Nn(a,l)||!Nn(a,d))throw new ge("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:Bi(l)}),await i.hooks?.afterOpen?.();let u=[],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`);u.push(Buffer.from(v.subarray(0,w)))}await i.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),pt.lstat(e,{bigint:n}),pt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!Nn(a,h)||!Nn(a,m))throw new ge("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Bi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function nw(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Qo(e,t){let i=Ze.relative(e,t);return i===""||!Ze.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ze.sep}`)}async function rd(e,t){let i=Ze.resolve(e),r=await bn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return bn.realpath(i)}async function nd(e,t,i,r){let n=e;for(let a=0;a{if(!Qo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await nd(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Li=".comet/config.yaml";function ow(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function kn(e,t={}){return(await Sn(e,t)).document}async function sw(e){try{return(await et(e,Li,Hi,{label:Li})).bytes}catch(t){if(ow(t))return null;throw t}}function cw(e){return e?{exists:!0,sha256:aw("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Sn(e,t={}){let i=await sw(e);return{document:i?Di(i.toString("utf8"),t):null,identity:cw(i)}}async function Zo(e){return(await kn(e))?.config??null}var _E=16*1024;import{existsSync as od,promises as vt}from"fs";import R from"path";import hw from"os";var En=".comet/config.yaml",pw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function is(e){try{return await vt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mw(e){try{let t=await vt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Mt(e,t){let i=R.relative(e,t);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function Ft(e){let t=[],i=e;for(;!await is(i);){let n=R.dirname(i);if(n===i)break;t.push(R.basename(i)),i=n}let r=await vt.realpath(i);return R.resolve(r,...t.reverse())}async function rs(e){try{return(await vt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Pn(e){let t=R.resolve(e);try{(await vt.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=R.resolve(hw.homedir());for(;;){if(!(t===r&&i!==r)){let o=R.join(t,...En.split("/")),s=t===i||await mw(o);if(await is(o)&&s)return t}if(await is(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return i;t=a}}function xn(e){return ht(e)}async function vw(e,t){let i=xn(t),r=R.resolve(e,...i.split("/")),n=await vt.realpath(e),a=await Ft(r);if(!Mt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function tt(e,t){let i=xn(t),r=await vw(e,i),n=R.join(r,"comet");if(await rs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ft(r),Ft(n)]);if(!Mt(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 rs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([vt.realpath(s),Ft(c)]);if(!Mt(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...En.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 sd(e){if(!pw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Pe(e,t){sd(t);let i=R.join(e.changesRuntimeDir,t);if(!B(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function ns(e,t){sd(t);let i=R.join(e.changesDir,t,"runtime");if(!B(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function xe(e,t){let i=Pe(e,t);if(od(i))return i;let r=ns(e,t);return od(r)?r:i}function Re(e,t){let i=R.resolve(t);if(B(e.runtimeDir,i))return e.runtimeDir;if(B(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function B(e,t){return Mt(R.resolve(e),R.resolve(t))}async function T(e,t){let i=R.resolve(e),r=R.resolve(t);if(!Mt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await rs(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ft(i),Ft(r)]);if(!Mt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function ww(e="docs",t="en"){return wn(e,t)}async function we(e){let t=(await kn(e))?.config??null;return t?.native?t:null}async function Mi(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 cd(e){let t=await Pn(e.startPath),i=await we(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${En} 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?xn(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??ww(r??"docs"),a=await tt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Uy}from"fs";import Ky from"path";import{AsyncLocalStorage as yw}from"async_hooks";import{randomUUID as dd}from"crypto";import{promises as ue}from"fs";import fd from"os";import G from"path";var ld=16*1024,hd=".coordinator",Nw=5e3,ud=new yw,Rn=new Map;function bw(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function kw(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 pd(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 as(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ie(i,r)?A(i,r):A(i,r)&&e.size===t.size}function os(e,t){return as(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function $e(e){let t,i;try{let r=await mt(e,ld,{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 ${ld} 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:kw(JSON.parse(t.toString("utf8")),e),identity:pd(i)}}async function Sw(e){return(await $e(e))?.owner??null}function md(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==fd.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Aw(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Ew(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 ss(e,t){let i=await $e(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!os(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ue.mkdir(t,{recursive:!0});let r=G.join(t,`${G.basename(e.file)}.${e.owner.id}.${dd()}.removed`);try{await ue.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await $e(r);if(!n||n.owner.id!==e.owner.id||!as(n.identity,e.identity))throw await Ew(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ue.rm(r,{force:!0}),"removed"}function vd(e){return{id:dd(),pid:process.pid,hostname:fd.hostname(),createdAt:new Date().toISOString(),operation:e}}async function gd(e,t){let i;try{i=await ue.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await Sw(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)+` -`,"utf8"),await i.sync(),pd(await i.stat({bigint:!0}))}finally{await i.close()}}async function Pw(e,t){let i=await T(e.runtimeDir,e.locksDir);await ue.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,G.join(i,hd));await ue.mkdir(r,{recursive:!0});let n=vd(t),a=G.join(r,`.${n.id}.tmp`),o=G.join(r,`${n.id}.claim`);try{let s=await gd(a,n);await ue.rename(a,o);let c=await $e(o);if(!c||!as(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 xw(e){let t=G.dirname(e.file),i=!1,r=G.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=G.join(t,n.name);if(G.resolve(a)!==G.resolve(e.file))try{let o=await $e(a),s=md(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ss(o,t);continue}n.name=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 Cw(e){let t=Rn.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Rn.set(e,n),await t,()=>{i(),Rn.get(e)===n&&Rn.delete(e)}}async function yd(e,t,i){let r=G.resolve(e.locksDir),n=ud.getStore();if(n?.has(r))return i();let a=await Cw(r);try{let o=await Rw(e,t),s=new Map(n??[]);return s.set(r,o),await ud.run(s,async()=>{try{return await i()}finally{await wd(o)}})}finally{a()}}async function Cn(e,t,i){return yd(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await ue.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,G.join(r,bw(t))),a=vd(i),o=await gd(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function An(e){await $e(e.file)&&await yd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${G.basename(e.file)}`,async()=>{let t=await $e(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!os(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=G.join(e.locksDir,hd);await ss(t,i)})}function Aw(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Nd(e){return md(await $e(e))}import ks from"node:path";import sy from"node:path";import kd from"node:path";import{createHash as _w}from"crypto";function ye(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Tw(e,t){t.has(e)&&ye("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&ye("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ye("symbol properties are not supported"),`[${e.map(r=>cs(r,t)).join(",")}]`}finally{t.delete(e)}}function Iw(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)}:${cs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function cs(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)?Tw(e,t):Iw(e,t);case"bigint":case"function":case"symbol":case"undefined":return ye(`${typeof e} values are not supported`)}return ye("unsupported value type")}function ls(e){return cs(e,new Set)}function Z(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 _w("sha256").update(`${e} -${ls(t)}`).digest("hex")}var jw="comet.native.acceptance.v1";var lP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Wi=Object.freeze({maxCriteria:1024});function ds(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 us(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*Vi(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` +`,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=dn(t),r=Ht(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=dn(t),r=Ht(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())}}};Ju.Parser=Wo});var Xu=y(Oi=>{"use strict";var Gu=To(),_g=xi(),$i=Ai(),Tg=Ca(),Ig=P(),jg=qo(),Uu=zo();function Ku(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new jg.LineCounter||null,prettyErrors:t}}function $g(e,t={}){let{lineCounter:i,prettyErrors:r}=Ku(t),n=new Uu.Parser(i?.addNewLine),a=new Gu.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach($i.prettifyError(e,i)),s.warnings.forEach($i.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Yu(e,t={}){let{lineCounter:i,prettyErrors:r}=Ku(t),n=new Uu.Parser(i?.addNewLine),a=new Gu.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 $i.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach($i.prettifyError(e,i)),o.warnings.forEach($i.prettifyError(e,i))),o}function Og(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Yu(e,i);if(!n)return null;if(n.warnings.forEach(a=>Tg.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 Hg(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 Ig.isDocument(e)&&!r?e.toString(i):new _g.Document(e,r,i).toString(i)}Oi.parse=Og;Oi.parseAllDocuments=$g;Oi.parseDocument=Yu;Oi.stringify=Hg});var Dt=y(x=>{"use strict";var Dg=To(),Bg=xi(),Lg=uo(),Jo=Ai(),Fg=ui(),Qe=P(),Mg=Ge(),Vg=$(),qg=Ke(),Wg=Ye(),zg=ln(),Jg=Mo(),Gg=qo(),Ug=zo(),hn=Xu(),Qu=oi();x.Composer=Dg.Composer;x.Document=Bg.Document;x.Schema=Lg.Schema;x.YAMLError=Jo.YAMLError;x.YAMLParseError=Jo.YAMLParseError;x.YAMLWarning=Jo.YAMLWarning;x.Alias=Fg.Alias;x.isAlias=Qe.isAlias;x.isCollection=Qe.isCollection;x.isDocument=Qe.isDocument;x.isMap=Qe.isMap;x.isNode=Qe.isNode;x.isPair=Qe.isPair;x.isScalar=Qe.isScalar;x.isSeq=Qe.isSeq;x.Pair=Mg.Pair;x.Scalar=Vg.Scalar;x.YAMLMap=qg.YAMLMap;x.YAMLSeq=Wg.YAMLSeq;x.CST=zg;x.Lexer=Jg.Lexer;x.LineCounter=Gg.LineCounter;x.Parser=Ug.Parser;x.parse=hn.parse;x.parseAllDocuments=hn.parseAllDocuments;x.parseDocument=hn.parseDocument;x.stringify=hn.stringify;x.visit=Qu.visit;x.visitAsync=Qu.visitAsync});import{randomUUID as wb}from"node:crypto";import{promises as W}from"node:fs";import U from"node:path";import{execFileSync as oh}from"child_process";import ri from"path";function ii(e,t){return oh("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function sh(e,t){let i=ri.normalize(e),r=ri.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function F(e){try{let t=ri.resolve(ii(e,["rev-parse","--show-toplevel"])),r=ii(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?ri.resolve(r.slice(9)):t,a=null;try{a=ii(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!sh(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function sc(e){try{ii(e,["rev-parse","--is-inside-work-tree"]);let t=ii(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:ri.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 ot(e){return sc(e).map(t=>t.root)}import{randomUUID as ch}from"crypto";import{promises as z}from"fs";import he from"path";function Ve(e){return e!==0&&e!==0n&&e!=="0"}function ie(e,t){return Ve(e.dev)&&Ve(t.dev)&&Ve(e.ino)&&Ve(t.ino)}function A(e,t){let i=Ve(e.dev)&&Ve(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ve(e.ino)&&Ve(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ua(e,t){let i=he.relative(e,t);return i===""||!he.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${he.sep}`)}function lh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function la(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ie(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cc(e){let t=await z.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 z.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ni(e){for(let t of e){let i=await z.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!lh(t,i)||await z.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function uh(e,t){let i=he.resolve(e),r=he.resolve(t);if(!ua(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await cc(i)],a=he.relative(i,r).split(he.sep).filter(Boolean),o=i;for(let s of a){await ni(n),o=he.join(o,s);try{await z.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await cc(o);if(!ua(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ni(n),n}async function dh(e){let t;try{t=await z.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 fh(e,t,i={}){let r=he.dirname(e),n=i.containedRoot?await uh(i.containedRoot,r):null;n||await z.mkdir(r,{recursive:!0});let a=he.join(r,`.${he.basename(e)}.${ch()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await z.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([z.lstat(a),z.realpath(a)]);if(await ni(n),!c.isFile()||c.isSymbolicLink()||!la(s,c)||!ua(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!la(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await ni(n);let c=await z.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!la(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await z.link(a,e),await z.unlink(a)):await z.rename(a,e),await dh(r)}catch(c){if(await o?.close(),!n)await z.rm(a,{force:!0});else try{await ni(n),await z.rm(a,{force:!0})}catch{}throw c}}async function K(e,t,i={}){await fh(e,t,i)}async function Y(e,t,i={}){await K(e,JSON.stringify(t,null,2)+` +`,i)}import{createHash as vh}from"node:crypto";import{promises as pe}from"node:fs";import ce from"node:path";import{TextDecoder as gh}from"node:util";var hh=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ph=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function mh(e){return e.toLowerCase().startsWith(".env")}function ai(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>mh(r))?"environment-file":i.some(r=>ph.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>hh.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var pr=1024*1024;function da(e,t){let i=ce.relative(e,t);return i===""||!ce.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ce.sep}`)}function wh(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=ai(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 yh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Nh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ie(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lc(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 bh(e,t){let i=ce.resolve(e),r=ce.resolve(t);if(!da(i,r))throw new Error("Native artifact path is outside its root");let n=[await lc(i)],a=i;for(let o of ce.relative(i,r).split(ce.sep).filter(Boolean)){a=ce.join(a,o);let s=await lc(a);if(!da(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function uc(e){for(let t of e){let i=await pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Nh(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=wh(e.ref),i=e.maxBytes===null?null:yh(e.maxBytes??pr),r=ce.resolve(e.root,...t.split("/")),n=await bh(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(!da(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,d]=await Promise.all([s.stat(),pe.lstat(r),pe.realpath(r)]);if(await uc(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!hr(a,c)||!hr(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let w=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,w),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>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 uc(n),!h.isFile()||h.isSymbolicLink()||m!==o||!hr(c,v)||!hr(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(f,u),N;try{N=new gh("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:u,hash:e.includeHash===!1?null:vh("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var js=ti(Dt(),1);import Kt from"path";var Uo=ti(Dt(),1);import pn from"path";var Hi=64*1024,mn=1024,vn=64,Ko=5,Kg=[".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/**",".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/**"],Yg=["**/.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"],Xg=[...Kg,...Yg].sort((e,t)=>e.localeCompare(t,"en"));var re={include:["**/*"],exclude:[...Xg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Qg(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||pn.posix.isAbsolute(i)||pn.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 ht(e){let t=Qg(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ed(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 gn(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||pn.posix.isAbsolute(r)||pn.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 Bt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function td(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 Yo(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>mn)throw new Error(`${t} exceeds ${mn} characters`);let i=0;for(let r=0;rvn)throw new Error(`${t} contains more than ${vn} wildcard tokens`);return e}function Zu(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=>Yo(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Go(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 Zg(e){if(e===void 0)return{...re,include:[...re.include],exclude:[...re.exclude]};let t=Bt(e,"native.snapshot");return{include:Zu(t.include,"native.snapshot.include",re.include),exclude:Zu(t.exclude,"native.snapshot.exclude",re.exclude),max_files:Go(t.max_files,re.max_files,"native.snapshot.max_files"),max_total_bytes:Go(t.max_total_bytes,re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Go(t.max_duration_ms,re.max_duration_ms,"native.snapshot.max_duration_ms")}}function ew(e){if(e===void 0)return;let t=Bt(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=Bt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:ht(r),toArtifactRoot:ht(n),stage:a,...o?{cleanup:o}:{}}}function tw(e,t={}){let i=Bt(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??Ko;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ew(i.pending_root_move);return{artifact_root:ht(r),language:td(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Zg(i.snapshot),...s?{pending_root_move:s}:{}}}function iw(e){let t=Bt(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:ed(t.artifact_layout),language:td(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function rw(e){let i=Bt(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)=>gn(r,`hook.allow_paths[${n}]`)))]}}function nw(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function aw(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(d=>d!=="native"&&d!=="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 Di(e,t={}){let i=(0,Uo.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=nw(n.ambient_resume),o=n.hook===void 0?void 0:rw(n.hook),s=n.native===void 0?void 0:tw(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:iw(n.classic),l=aw(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 wn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:ht(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Ko,snapshot:{...re,include:[...re.include],exclude:[...re.exclude]}}}}import{createHash as sw}from"crypto";import{promises as bn}from"fs";import Ze from"path";import{constants as yn,promises as pt}from"fs";var ge=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Xo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function id(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Bi(e){return{dev:e.dev,ino:e.ino,birthtime:Xo(e)}}function Nn(e,t){let i=Bi(e),r=Bi(t);return ie(i,r)?A(i,r):A(i,r)&&Xo(e)===Xo(t)&&id(e)===id(t)&&e.size===t.size}async function mt(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 pt.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 pt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Bi(a)});let s=process.platform==="win32"?yn.O_RDONLY:yn.O_RDONLY|yn.O_NOFOLLOW|yn.O_NONBLOCK,c;try{c=await pt.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,d,f]=await Promise.all([c.stat({bigint:n}),pt.lstat(e,{bigint:n}),pt.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||f!==o||!Nn(a,l)||!Nn(a,d))throw new ge("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:Bi(l)}),await i.hooks?.afterOpen?.();let u=[],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`);u.push(Buffer.from(v.subarray(0,w)))}await i.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),pt.lstat(e,{bigint:n}),pt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!Nn(a,h)||!Nn(a,m))throw new ge("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Bi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function ow(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Qo(e,t){let i=Ze.relative(e,t);return i===""||!Ze.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ze.sep}`)}async function rd(e,t){let i=Ze.resolve(e),r=await bn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return bn.realpath(i)}async function nd(e,t,i,r){let n=e;for(let a=0;a{if(!Qo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await nd(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Li=".comet/config.yaml";function cw(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function kn(e,t={}){return(await Sn(e,t)).document}async function lw(e){try{return(await et(e,Li,Hi,{label:Li})).bytes}catch(t){if(cw(t))return null;throw t}}function uw(e){return e?{exists:!0,sha256:sw("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Sn(e,t={}){let i=await lw(e);return{document:i?Di(i.toString("utf8"),t):null,identity:uw(i)}}async function Zo(e){return(await kn(e))?.config??null}var $E=16*1024;import{existsSync as od,promises as vt}from"fs";import R from"path";import mw from"os";var En=".comet/config.yaml",vw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function is(e){try{return await vt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gw(e){try{let t=await vt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Mt(e,t){let i=R.relative(e,t);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function Ft(e){let t=[],i=e;for(;!await is(i);){let n=R.dirname(i);if(n===i)break;t.push(R.basename(i)),i=n}let r=await vt.realpath(i);return R.resolve(r,...t.reverse())}async function rs(e){try{return(await vt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Pn(e){let t=R.resolve(e);try{(await vt.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=R.resolve(mw.homedir());for(;;){if(!(t===r&&i!==r)){let o=R.join(t,...En.split("/")),s=t===i||await gw(o);if(await is(o)&&s)return t}if(await is(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return i;t=a}}function xn(e){return ht(e)}async function ww(e,t){let i=xn(t),r=R.resolve(e,...i.split("/")),n=await vt.realpath(e),a=await Ft(r);if(!Mt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function tt(e,t){let i=xn(t),r=await ww(e,i),n=R.join(r,"comet");if(await rs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ft(r),Ft(n)]);if(!Mt(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 rs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([vt.realpath(s),Ft(c)]);if(!Mt(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...En.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 sd(e){if(!vw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Pe(e,t){sd(t);let i=R.join(e.changesRuntimeDir,t);if(!L(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function ns(e,t){sd(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 xe(e,t){let i=Pe(e,t);if(od(i))return i;let r=ns(e,t);return od(r)?r:i}function Re(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 Mt(R.resolve(e),R.resolve(t))}async function T(e,t){let i=R.resolve(e),r=R.resolve(t);if(!Mt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await rs(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ft(i),Ft(r)]);if(!Mt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function Nw(e="docs",t="en"){return wn(e,t)}async function we(e){let t=(await kn(e))?.config??null;return t?.native?t:null}async function Mi(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 cd(e){let t=await Pn(e.startPath),i=await we(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${En} 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?xn(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??Nw(r??"docs"),a=await tt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Yy}from"fs";import Xy from"path";import{AsyncLocalStorage as bw}from"async_hooks";import{randomUUID as dd}from"crypto";import{promises as ue}from"fs";import fd from"os";import G from"path";var ld=16*1024,hd=".coordinator",kw=5e3,ud=new bw,Rn=new Map;function Sw(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Ew(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 pd(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 as(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ie(i,r)?A(i,r):A(i,r)&&e.size===t.size}function os(e,t){return as(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function $e(e){let t,i;try{let r=await mt(e,ld,{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 ${ld} 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:Ew(JSON.parse(t.toString("utf8")),e),identity:pd(i)}}async function Pw(e){return(await $e(e))?.owner??null}function md(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==fd.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Tw(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function xw(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 ss(e,t){let i=await $e(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!os(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ue.mkdir(t,{recursive:!0});let r=G.join(t,`${G.basename(e.file)}.${e.owner.id}.${dd()}.removed`);try{await ue.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await $e(r);if(!n||n.owner.id!==e.owner.id||!as(n.identity,e.identity))throw await xw(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ue.rm(r,{force:!0}),"removed"}function vd(e){return{id:dd(),pid:process.pid,hostname:fd.hostname(),createdAt:new Date().toISOString(),operation:e}}async function gd(e,t){let i;try{i=await ue.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await Pw(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)+` +`,"utf8"),await i.sync(),pd(await i.stat({bigint:!0}))}finally{await i.close()}}async function Rw(e,t){let i=await T(e.runtimeDir,e.locksDir);await ue.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,G.join(i,hd));await ue.mkdir(r,{recursive:!0});let n=vd(t),a=G.join(r,`.${n.id}.tmp`),o=G.join(r,`${n.id}.claim`);try{let s=await gd(a,n);await ue.rename(a,o);let c=await $e(o);if(!c||!as(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 Cw(e){let t=G.dirname(e.file),i=!1,r=G.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=G.join(t,n.name);if(G.resolve(a)!==G.resolve(e.file))try{let o=await $e(a),s=md(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ss(o,t);continue}n.name=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 _w(e){let t=Rn.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Rn.set(e,n),await t,()=>{i(),Rn.get(e)===n&&Rn.delete(e)}}async function yd(e,t,i){let r=G.resolve(e.locksDir),n=ud.getStore();if(n?.has(r))return i();let a=await _w(r);try{let o=await Aw(e,t),s=new Map(n??[]);return s.set(r,o),await ud.run(s,async()=>{try{return await i()}finally{await wd(o)}})}finally{a()}}async function Cn(e,t,i){return yd(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await ue.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,G.join(r,Sw(t))),a=vd(i),o=await gd(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function An(e){await $e(e.file)&&await yd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${G.basename(e.file)}`,async()=>{let t=await $e(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!os(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=G.join(e.locksDir,hd);await ss(t,i)})}function Tw(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Nd(e){return md(await $e(e))}import ks from"node:path";import ly from"node:path";import kd from"node:path";import{createHash as Iw}from"crypto";function ye(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function jw(e,t){t.has(e)&&ye("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&ye("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ye("symbol properties are not supported"),`[${e.map(r=>cs(r,t)).join(",")}]`}finally{t.delete(e)}}function $w(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)}:${cs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function cs(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)?jw(e,t):$w(e,t);case"bigint":case"function":case"symbol":case"undefined":return ye(`${typeof e} values are not supported`)}return ye("unsupported value type")}function ls(e){return cs(e,new Set)}function Z(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 Iw("sha256").update(`${e} +${ls(t)}`).digest("hex")}var Ow="comet.native.acceptance.v1";var hP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Wi=Object.freeze({maxCriteria:1024});function ds(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 us(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*Vi(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(` -`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=us(l,t);else if(i)bd(l)&&(i=!1);else if(r!==null)new RegExp(``,"iu").test(l)&&(r=null);else{let f=us(l,null);if(f!==null)t=f;else{let u=l.trimStart();if(u.startsWith(""||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(d);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(),hs(n,"Specification mandatory requirements",r)}var Ow=/^A[1-9]\d*$/u;function Sd(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||kd.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||kd.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Hw(e,t){return e.localeCompare(t,"en")}function _n(e){let t=Sd(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Hw(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=ps(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Sd(a.source,`Native spec source for ${a.capability}`);r.push(...ms(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...vs(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=qi(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 Ed(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}var jn=ti(Dt(),1);import{promises as Dw}from"node:fs";var Vt="comet.native.v4",zi="comet.native.local-execution.v4";function gs(){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 Bw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fw=/^A[1-9][0-9]*$/u,Mw=/^[a-f0-9]{64}$/u,Vw=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"]),In=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 ee(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function te(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 q(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 ys(e,t){return e===null?null:q(e,t)}function qw(e,t){let i=q(e,t);if(!Mw.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function qt(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)||ei(r,n))}function $n(e,t){return Ce(e,t,(i,r)=>q(i,`${t}[${r}]`))}function gt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Wt(e,t){let i=q(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Ns(e,t,i=!1){let r=q(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=ee(e,t);return te(i,new Set(["text","truncated"]),t),{text:q(i.text,`${t}.text`,{empty:!0}),truncated:qt(i.truncated,`${t}.truncated`)}}function zw(e,t){let i=`Native spec_changes[${t}]`,r=ee(e,i);te(r,new Set(["capability","operation","source"]),i);let n=q(r.capability,`${i}.capability`);if(!Lw.test(n))throw new Error(`${i}.capability is invalid`);let a=V(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Ns(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 Jw(e){let t="Native workspace",i=ee(e,t);te(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=V(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=ys(i.change_branch,`${t}.change_branch`),a=ys(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 Gw(e){let t="Native loop",i=ee(e,t);te(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=$n(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return gt(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:ys(i.next_action,`${t}.next_action`)}}function Uw(e,t){let i=`Native acceptance[${t}]`,r=ee(e,i);te(r,new Set(["id","source","text","result","reason"]),i);let n=q(r.id,`${i}.id`);if(!Fw.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Ns(r.source,`${i}.source`),text:q(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 Kw(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ee(e,i);return te(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 Yw(e){let t="Native builder_handoff",i=ee(e,t);te(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=$n(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return gt(r,`${t}.addressed_acceptance_ids`),{candidate_id:q(i.candidate_id,`${t}.candidate_id`),identity_provider:q(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:q(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:Ce(i.checks,`${t}.checks`,Kw),checks_truncated:qt(i.checks_truncated,`${t}.checks_truncated`),known_limits:Ce(i.known_limits,`${t}.known_limits`,(n,a)=>Ne(n,`${t}.known_limits[${a}]`)),known_limits_truncated:qt(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Wt(i.submitted_at,`${t}.submitted_at`)}}function Xw(e,t){let i=`Native blockers[${t}]`,r=ee(e,i);te(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=$n(r.acceptance_ids,`${i}.acceptance_ids`);return gt(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 Qw(e,t){let i=`Native verification.checks[${t}]`,r=ee(e,i);return te(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:q(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),argv_display:Ce(r.argv_display,`${i}.argv_display`,(n,a)=>Ne(n,`${i}.argv_display[${a}]`)),argv_truncated:qt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Ns(r.cwd_ref,`${i}.cwd_ref`,!0),status:V(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Ww(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Zw(e){let t="Native verification",i=ee(e,t);te(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Ce(i.checks,`${t}.checks`,Qw);gt(r.map(a=>a.id),`${t}.checks IDs`);let n=q(i.identity_provider,`${t}.identity_provider`);return{candidate_id:q(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:q(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:Ce(i.risks,`${t}.risks`,(a,o)=>Ne(a,`${t}.risks[${o}]`)),risks_truncated:qt(i.risks_truncated,`${t}.risks_truncated`),completed_at:Wt(i.completed_at,`${t}.completed_at`)}}function xd(e,t){let i=`Native history[${t}]`,r=ee(e,i);te(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=$n(r.unresolved_ids,`${i}.unresolved_ids`);return gt(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:Wt(r.completed_at,`${i}.completed_at`)}}function ey(e){let t="Native history_overflow.outcome_counts",i=ee(e,t),r=["pass","fail","blocked","execution-error","recovery"];return te(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 ty(e){let t="Native history_overflow",i=ee(e,t);te(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:Wt(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Wt(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=ey(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 iy(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 ry(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=ee(e,"Native portable state");if(te(t,Vw,"Native portable state"),t.schema!==Vt)throw new Error(`Native portable state schema must be ${Vt}`);let i=q(t.name,"Native state name");if(!Bw.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=Ce(t.spec_changes,"Native spec_changes",zw);gt(r.map(s=>s.capability),"Native spec change capabilities");let n=Ce(t.acceptance,"Native acceptance",Uw);gt(n.map(s=>s.id),"Native acceptance IDs");let a=Ce(t.history,"Native history",xd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Vt,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:qw(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Jw(t.workspace),loop:Gw(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Yw(t.builder_handoff),blockers:Ce(t.blockers,"Native blockers",Xw),verification:t.verification===null?null:Zw(t.verification),history:a,history_overflow:ty(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:qt(t.archived,"Native archived"),created_at:Wt(t.created_at,"Native created_at")};return iy(o),ry(o),o}function zt(e,t){let i=ne(e),r=xd(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 ny(e,t){let i=(0,jn.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 Dw.readFile(e,"utf8");return ne(ny(t,"Native portable state"))}async function On(e,t,i={}){let r=ne(t);await K(e,(0,jn.stringify)(r),i)}var Tn=new Map;async function ay(e,t){let i=Tn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Tn.set(e,a),await i;try{return await t()}finally{r(),Tn.get(e)===a&&Tn.delete(e)}}async function wt(e){return ay(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 In(t,r.state_version);return await On(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ae(e.file);if(n.state_version!==t)throw new In(t,n.state_version)}}),i})}function oy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function it(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(oy(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 Oe="comet.native.v3",Ae="comet.native.v2",_e="comet.native.v1";var Hn="comet.native.portable-migration.v1",cy=new Set(["schema","id","change","fromSchema","status","createdAt"]),ly=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uy=/^[a-z0-9][a-z0-9-]{7,127}$/u,dy=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fy=new Set([_e,Ae,Oe]);function hy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function py(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 my(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 vy(e){return e.schema===_e?Ji(e):e.schema===Ae?Gi(e):Ui(e)}function gy(e){return sy.posix.normalize(e.replaceAll("\\","/"))}function wy(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:gy(t.source)})}function yy(e){return e==="shape"?"shape":"build"}function Ny(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function by(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 Rd(e){let t=vy(e.state);Ed(e.acceptance);let i=yy(t.phase),r=i==="shape"?0:1,n=py(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:Vt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:wy(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:Ny(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:it(by(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:gs(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function bs(e){let t=hy(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!cy.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Hn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!uy.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!ly.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!fy.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!dy.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Hn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:my(t.createdAt,"Native portable migration transaction createdAt")}}function Cd(e){switch(bs(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 Dn="comet.native.archive-transaction.v4",Ad="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",ky=new RegExp(`^portable-archive-(${Ad})\\.json$`,"u"),Sy=new RegExp(`^portable-migration-(${Ad})\\.json$`,"u"),Ey=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Py=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xy=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Ry=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Cy=new Set(["capability","operation","source","content"]),_d=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Td(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Id(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 Ay(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Td(e,i);if(Id(r,Cy,i),typeof r.capability!="string"||!_d.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 _y(e){let t=Td(e,"Native portable Archive transaction");if(Id(t,Ry,"Native portable Archive transaction"),t.schema!==Dn)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Ey.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!_d.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"||!Py.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"||!xy.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(Ay);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:Dn,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 Bn(e){let t=ky.exec(e);if(t)return{kind:"archive",change:t[1]};let i=Sy.exec(e);return i?{kind:"migration",change:i[1]}:null}function yt(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Bn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return ks.join(e.transactionsDir,i)}async function Ss(e,t){let i=Bn(t);if(!i)return null;let r=await I({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=ks.join(e.transactionsDir,t);if(i.kind==="archive"){let s=_y(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=bs(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 Jt(e,t){let i=yt(e,t);try{return await Ss(e,ks.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function jd(e){return e.kind==="archive"||e.journal.status!=="committed"}import He from"path";import{TextDecoder as By}from"util";import{createHash as Ty}from"node:crypto";import{constants as Ln,promises as be}from"node:fs";import ke from"node:path";function Mn(e,t){let i=ke.relative(e,t);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function Iy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function jy(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $y(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Fn(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 Es(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 Oy(e,t,i){let r=ke.resolve(e),n=ke.resolve(t);if(!Mn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Es(r,i)],o=r;for(let s of ke.relative(r,n).split(ke.sep).filter(Boolean)){await Nt(a,i),o=ke.join(o,s);let c=await Es(o,i);if(!Mn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Nt(a,i),a}async function Nt(e,t){for(let i of e){let r=await be.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!jy(i,r)||await be.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Hy(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 Gt(e){let t=Iy(e.maxBytes),i=ke.resolve(e.file),r=await Oy(e.root,ke.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>Es(ke.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Nt(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=$y(a),s=await be.realpath(i);if(!Mn(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>Mn(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ln.O_RDONLY:Ln.O_RDONLY|Ln.O_NOFOLLOW|Ln.O_NONBLOCK,l=await be.open(i,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[f,u]=await Promise.all([be.lstat(i),be.realpath(i)]);if(await Nt(r,e.label),await Nt(n,e.label),!d.isFile()||!f.isFile()||f.isSymbolicLink()||u!==s||!Fn(o,d)||!Fn(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Hy(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 Nt(r,e.label),await Nt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Fn(o,v)||!Fn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Ty("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Ly=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Fy=new Set(["id","type","source","target","staged","backup"]),My=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Vy=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Hd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var qy=256*1024,GP=1024*1024,UP=16*1024;var KP=64*1024*1024;var Wy=new By("utf-8",{fatal:!0});function qn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wn(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 Dd(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ps(e,t){if(typeof e!="string"||e.length===0||He.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Vn(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $d(e,t){if(Ps(e,t),e.includes("\\")||e!==He.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 zy(e,t){let i=qn(e,`transaction operations[${t}]`);if(Wn(i,Fy,`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`);Ps(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ps(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 Bd(e){let t=qn(e,"Native Archive transaction journal");if(Wn(t,My,"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"||!Hd.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(!Dd(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Vn(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=qn(s,`Archive transaction operations[${c}]`);if(Wn(l,Vy,`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`);$d(l.target,`Archive transaction operation ${l.id} target`);for(let d of["source","staged","backup"])l[d]!==void 0&&$d(l[d],`Archive transaction operation ${l.id} ${d}`);if(l.expectedTargetHash!==null&&Vn(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Vn(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Vn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${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 Jy(e){let t=qn(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bd(t);if(Wn(t,Ly,"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"||!Hd.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!He.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!He.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(!Dd(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(zy),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 Gy(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return He.join(e.transactionsDir,t)}function Ld(e,t){let i=Gy(e,t);return{directory:i,journal:He.join(i,"transaction.json"),events:He.join(i,"events.jsonl"),staged:He.join(i,"staged"),backups:He.join(i,"backups")}}async function Rs(e,t){let i=Ld(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}async function Cs(e,t,i={}){let r=await Rs(e,t),n=await Gt({root:e.runtimeDir,file:r.journal,maxBytes:qy,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Wy.decode(n.bytes)),o=Jy(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Yy(e,t,i){let r;try{r=await Uy.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 Cs(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(Bn(n.name))try{let a=await Ss(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(jd(a))return!0}catch{return!0}return!1}async function Xy(e,t){let i=Date.now()+5e3,r=Ky.join(e.locksDir,"root-move.lock");for(;;)try{return await Cn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Nd(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 J(e,t,i,r){let n=await Xy(e,t);try{if(await Mi(e.projectRoot),await Yy(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await An(n)}}import{createHash as Qy}from"crypto";function de(e){return Qy("sha256").update(e).digest("hex")}var vx={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var gx=8*1024*1024;var wx=64*1024,yx=64*1024;var Nx={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},bx={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var kx=(1n<<256n)-1n;var aN=ti(Dt(),1);var Bx=4*1024*1024;var oN=null;function sN(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Fd(e,t){return(...i)=>{let r=oN;if(r===null)return t(...i);let n=sN(`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 qx=Fd("hookWritePolicy",async e=>(await Zo(e))?.hook??{allow_paths:[]});var BR=256*1024;var XR={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 Ut from"node:path";var Ki=/^[a-f0-9]{64}$/u,Vd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,uN=16*1024,hC=process.platform;function dN(e,t){let i=Ut.relative(e,t);return Ut.isAbsolute(i)||i===".."||i.startsWith(`..${Ut.sep}`)?null:i.replaceAll("\\","/")||"."}function qd(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wd(e,t){if(e.length===0||qd(e)||e.includes("\\")||Ut.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=Ut.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function fN(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 As(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||qd(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function hN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(As(e.changeBranch,"Native workspace change branch"),As(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 pN(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"||!Vd.test(t.baseCommit)||typeof t.targetCommit!="string"||!Vd.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");As(t.targetBranch,"Native workspace Git target branch")}function mN(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"||!Ki.test(String(t.projectRootId))||!Ki.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");fN(t.capturedAt),Wd(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&&!Ki.test(String(t.projectRootPathId))||a&&!Ki.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ki.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&pN(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(hN(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 vN(e,t){return Ut.join(xe(e,t),"workspace.json")}function gN(e,t){let i=vN(e,t),r=Re(e,i),n=dN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Wd(n,"Native workspace file ref")}}async function wN(e,t){try{let i=gN(e,t),r=await I({root:i.root,ref:i.ref,maxBytes:uN});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Yi(e,t){let i=await wN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(mN(i),i)}var Jd=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],bN=new Set(Jd),Gd=new Set([...Jd,"minimum_runtime_version","revision"]),kN=new Set([...Gd,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),SN=new Set(["capability","operation","source","base_hash"]),EN=new Set(["shape","build","verify","archive"]),PN=new Set(["implicit","confirmed"]),xN=new Set(["pending","pass","fail"]),bt="comet-state.yaml",Ts=/^[a-f0-9]{64}$/u,Ud=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Is=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"},Yt=class extends Error{constructor(i,r){super(i!==Oe||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"},zn=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"},Xi=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"},Jn=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"},DC=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function Zi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);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(", ")}`)}function $s(e){if(!Ud.test(e))throw new Error(`Invalid Native change name: ${e}`)}function CN(e){if(!Ud.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Yd(e,t){if(e.length===0||Kt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function AN(e,t){let i=Zi(e,`spec_changes[${t}]`);if(Kd(i,SN,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(CN(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"&&Yd(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"||!Ts.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"||!Ts.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 _N(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 Os(e,t){if(Kd(e,t,bt),typeof e.name!="string")throw new Error("Native change name is required");if($s(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"||!EN.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&&!PN.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(AN),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"||!xN.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"&&Yd(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!_N(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 Ji(e){let t=Zi(e,bt);if(t.schema!==_e)throw new Error(`Expected ${_e}`);return{schema:_e,...Os(t,bN)}}function Qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _s(e,t,i){if(e===null)return null;let r=typeof e=="string"?RN.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function TN(e){if(e==null)return null;if(typeof e!="string"||!Ts.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function IN(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 Gi(e){let t=Zi(e,bt);if(t.schema!==Ae)throw new Error(`Expected ${Ae}`);if(Qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ae} minimum_runtime_version must be 2`);return{schema:Ae,minimum_runtime_version:2,revision:Qi(t.revision,"Native v2 revision"),...Os(t,Gd)}}function Ui(e){let t=Zi(e,bt);if(t.schema!==Oe){if(t.schema===_e||t.schema===Ae){let o=t.schema===_e?Ji(t):Gi(t);throw new Is(o.name,o.schema)}throw new Yt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Yt(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Qi(t.revision,"Native revision"),n=Os(t,kN),a=TN(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Oe,minimum_runtime_version:3,revision:r,verification_protocol:IN(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_s(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_s(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_s(t.partial_allowance,"Native partial_allowance","allowances")}}function jN(e){let t=Zi(e,bt);if(t.schema===_e){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema===Ae){let n=Gi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema!==Oe){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 Yt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Yt(t.schema,i).message};let r=Ui(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function oe(e,t){$s(t);let i=Kt.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return i}var $N=256*1024;async function ON(e,t=Kt.dirname(e)){let i=Kt.relative(t,e).split(Kt.sep).join("/"),r=await I({root:t,ref:i,maxBytes:$N}),n=(0,js.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 Gn(e,t){let i=Kt.join(oe(e,t),bt);await T(e.nativeRoot,i);let r=jN(await ON(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{promises as nr}from"node:fs";import Le from"node:path";var nf=ti(Dt(),1);import{promises as LN}from"node:fs";import FN from"node:path";import{execFileSync as HN}from"node:child_process";var DN=3e4,BN=8*1024*1024,Hs=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 Xd(e,t){try{return HN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:DN,maxBuffer:BN,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Hs(e,t,r)}}function L(e,t){return Xd(e,t).trim()}function Un(e){return L(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Ds(e){let t=Xd(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;nr.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 Zd="children.yaml",Bs="comet.native.children.v1",MN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VN=new Set(["schema","children"]),qN=new Set(["name","depends_on","covers"]);function ef(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tf(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 rf(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 WN(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 zN(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function JN(e,t){let i=(0,nf.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=ef(i.toJS({mapAsMap:!1}),"Native children contract");if(tf(r,VN,"Native children contract"),r.schema!==Bs)throw new Error(`Native children schema must be ${Bs}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=ef(s,`Native child ${c}`);if(tf(l,qN,`Native child ${c}`),typeof l.name!="string"||!MN.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:rf(l.depends_on,`Native child ${l.name} depends_on`),covers:rf(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return WN(n),t&&zN(n,t),{schema:Bs,children:n}}async function af(e){let t=FN.join(e.changeDir,Zd);try{await LN.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await I({root:e.changeDir,ref:Zd});return{contract:JN(i.text,e.acceptanceIds),size:i.size}}function of(e){return Z("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 XC=["$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 Kn="skill-coordinated";function YN(e){return e.state_version+1}function XN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function QN(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:it(e.summary),completed_at:e.completedAt}}function Ls(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=zt(t,QN({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return ne({...r,phase:"build",status:"active",state_version:YN(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:XN(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 cf}from"node:fs";import tr from"node:path";function Yn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xn(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 Te(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 sf(e,t){return e===null?null:Te(e,t)}function Zn(e,t,i=0){if(!Number.isSafeInteger(e)||eTe(l,`${i}.argv[${d}]`,!0)),a=Qn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Fs(r.startedAt,`${i}.startedAt`),s=Fs(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=Zn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Te(r.id,`${i}.id`),name:Te(r.name,`${i}.name`),operationId:Te(r.operationId,`${i}.operationId`),status:a,repeatable:eb(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Zn(r.executionCount,`${i}.executionCount`),argv:n,cwd:Ms(r.cwd,`${i}.cwd`),exitCode:ZN(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Te(r.log,`${i}.log`)}}function Vs(e){let t="Native local execution state",i=Yn(e,t);if(Xn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==zi)throw new Error(`Native local execution schema must be ${zi}`);let r=Yn(i.workspace,"Native local workspace");Xn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Yn(i.execution,"Native local execution");Xn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Fs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Te(o.operationId,"Native local execution.operationId"),stage:Qn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Qn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:sf(o.executionId,"Native local execution.executionId"),status:Qn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Zn(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:zi,change:Te(i.change,"Native local change"),basedOnStateVersion:Zn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ms(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ms(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:sf(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function nt(e){return Vs({schema:zi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:tr.resolve(e.projectRoot),worktreeRoot:tr.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function qs(e){let t;try{t=await cf.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 Vs(i)}async function De(e,t,i={}){let r=Vs(t);await cf.mkdir(tr.dirname(e),{recursive:!0}),await Y(e,r,i)}import{promises as ib}from"node:fs";function at(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` -`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Be(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"
")}function rb(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 nb(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===Kn?Kn:"host-attested")}function ab(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Be(o.id)} | ${Be(o.result)} | ${Be(o.source)} | ${Be(o.text)} | ${Be(at(o.reason))} |`).join(` +`),o.context,r)),o=null}};for(let{line:c,body:l}of Vi(e)){let d=l?ds(c):null,f=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=d.level;)a.pop();let u=qi(f[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:d.level,title:u,body:[],context:a.map(p=>p.text)}}else if(d){for(o!==null&&d.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=d.level;)a.pop();a.push(d)}else o!==null&&l&&o.body.push(c)}return s(),hs(n,"Specification",r)}function vs(e,t="spec.md",i=Wi.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(fs("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(d=>/^(?:non-?goals?|非目标)$/iu.test(d.text.trim()));for(let{line:d,body:f}of Vi(e)){let u=f?ds(d):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=d.trim();if(!f||o!==null||l()){c();continue}if(p.length===0||us(d,null)!==null||p.startsWith(""||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(d);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(),hs(n,"Specification mandatory requirements",r)}var Dw=/^A[1-9]\d*$/u;function Sd(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||kd.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||kd.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Bw(e,t){return e.localeCompare(t,"en")}function _n(e){let t=Sd(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Bw(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=ps(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Sd(a.source,`Native spec source for ${a.capability}`);r.push(...ms(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...vs(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=qi(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 Ed(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}var jn=ti(Dt(),1);import{promises as Lw}from"node:fs";var Vt="comet.native.v4",zi="comet.native.local-execution.v4";function gs(){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 Fw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Mw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Vw=/^A[1-9][0-9]*$/u,qw=/^[a-f0-9]{64}$/u,Ww=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"]),In=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 ee(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function te(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 q(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 ys(e,t){return e===null?null:q(e,t)}function zw(e,t){let i=q(e,t);if(!qw.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function qt(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)||ei(r,n))}function $n(e,t){return Ce(e,t,(i,r)=>q(i,`${t}[${r}]`))}function gt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Wt(e,t){let i=q(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Ns(e,t,i=!1){let r=q(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=ee(e,t);return te(i,new Set(["text","truncated"]),t),{text:q(i.text,`${t}.text`,{empty:!0}),truncated:qt(i.truncated,`${t}.truncated`)}}function Gw(e,t){let i=`Native spec_changes[${t}]`,r=ee(e,i);te(r,new Set(["capability","operation","source"]),i);let n=q(r.capability,`${i}.capability`);if(!Mw.test(n))throw new Error(`${i}.capability is invalid`);let a=V(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Ns(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 Uw(e){let t="Native workspace",i=ee(e,t);te(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=V(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=ys(i.change_branch,`${t}.change_branch`),a=ys(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 Kw(e){let t="Native loop",i=ee(e,t);te(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=$n(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return gt(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:ys(i.next_action,`${t}.next_action`)}}function Yw(e,t){let i=`Native acceptance[${t}]`,r=ee(e,i);te(r,new Set(["id","source","text","result","reason"]),i);let n=q(r.id,`${i}.id`);if(!Vw.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Ns(r.source,`${i}.source`),text:q(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 Xw(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ee(e,i);return te(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 Qw(e){let t="Native builder_handoff",i=ee(e,t);te(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=$n(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return gt(r,`${t}.addressed_acceptance_ids`),{candidate_id:q(i.candidate_id,`${t}.candidate_id`),identity_provider:q(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:q(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:Ce(i.checks,`${t}.checks`,Xw),checks_truncated:qt(i.checks_truncated,`${t}.checks_truncated`),known_limits:Ce(i.known_limits,`${t}.known_limits`,(n,a)=>Ne(n,`${t}.known_limits[${a}]`)),known_limits_truncated:qt(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Wt(i.submitted_at,`${t}.submitted_at`)}}function Zw(e,t){let i=`Native blockers[${t}]`,r=ee(e,i);te(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=$n(r.acceptance_ids,`${i}.acceptance_ids`);return gt(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 ey(e,t){let i=`Native verification.checks[${t}]`,r=ee(e,i);return te(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:q(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),argv_display:Ce(r.argv_display,`${i}.argv_display`,(n,a)=>Ne(n,`${i}.argv_display[${a}]`)),argv_truncated:qt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Ns(r.cwd_ref,`${i}.cwd_ref`,!0),status:V(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Jw(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function ty(e){let t="Native verification",i=ee(e,t);te(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Ce(i.checks,`${t}.checks`,ey);gt(r.map(a=>a.id),`${t}.checks IDs`);let n=q(i.identity_provider,`${t}.identity_provider`);return{candidate_id:q(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:q(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:Ce(i.risks,`${t}.risks`,(a,o)=>Ne(a,`${t}.risks[${o}]`)),risks_truncated:qt(i.risks_truncated,`${t}.risks_truncated`),completed_at:Wt(i.completed_at,`${t}.completed_at`)}}function xd(e,t){let i=`Native history[${t}]`,r=ee(e,i);te(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=$n(r.unresolved_ids,`${i}.unresolved_ids`);return gt(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:Wt(r.completed_at,`${i}.completed_at`)}}function iy(e){let t="Native history_overflow.outcome_counts",i=ee(e,t),r=["pass","fail","blocked","execution-error","recovery"];return te(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 ry(e){let t="Native history_overflow",i=ee(e,t);te(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:Wt(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Wt(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=iy(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 ny(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 ay(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=ee(e,"Native portable state");if(te(t,Ww,"Native portable state"),t.schema!==Vt)throw new Error(`Native portable state schema must be ${Vt}`);let i=q(t.name,"Native state name");if(!Fw.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=Ce(t.spec_changes,"Native spec_changes",Gw);gt(r.map(s=>s.capability),"Native spec change capabilities");let n=Ce(t.acceptance,"Native acceptance",Yw);gt(n.map(s=>s.id),"Native acceptance IDs");let a=Ce(t.history,"Native history",xd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Vt,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:zw(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Uw(t.workspace),loop:Kw(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Qw(t.builder_handoff),blockers:Ce(t.blockers,"Native blockers",Zw),verification:t.verification===null?null:ty(t.verification),history:a,history_overflow:ry(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:qt(t.archived,"Native archived"),created_at:Wt(t.created_at,"Native created_at")};return ny(o),ay(o),o}function zt(e,t){let i=ne(e),r=xd(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 oy(e,t){let i=(0,jn.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 Lw.readFile(e,"utf8");return ne(oy(t,"Native portable state"))}async function On(e,t,i={}){let r=ne(t);await K(e,(0,jn.stringify)(r),i)}var Tn=new Map;async function sy(e,t){let i=Tn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Tn.set(e,a),await i;try{return await t()}finally{r(),Tn.get(e)===a&&Tn.delete(e)}}async function wt(e){return sy(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 In(t,r.state_version);return await On(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ae(e.file);if(n.state_version!==t)throw new In(t,n.state_version)}}),i})}function cy(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function it(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(cy(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 Oe="comet.native.v3",Ae="comet.native.v2",_e="comet.native.v1";var Hn="comet.native.portable-migration.v1",uy=new Set(["schema","id","change","fromSchema","status","createdAt"]),dy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fy=/^[a-z0-9][a-z0-9-]{7,127}$/u,hy=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),py=new Set([_e,Ae,Oe]);function my(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vy(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 gy(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===_e?Ji(e):e.schema===Ae?Gi(e):Ui(e)}function yy(e){return ly.posix.normalize(e.replaceAll("\\","/"))}function Ny(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:yy(t.source)})}function by(e){return e==="shape"?"shape":"build"}function ky(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Sy(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 Rd(e){let t=wy(e.state);Ed(e.acceptance);let i=by(t.phase),r=i==="shape"?0:1,n=vy(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:Vt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:Ny(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:ky(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:it(Sy(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:gs(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function bs(e){let t=my(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!uy.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Hn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!fy.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"||!py.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!hy.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Hn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:gy(t.createdAt,"Native portable migration transaction createdAt")}}function Cd(e){switch(bs(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 Dn="comet.native.archive-transaction.v4",Ad="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Ey=new RegExp(`^portable-archive-(${Ad})\\.json$`,"u"),Py=new RegExp(`^portable-migration-(${Ad})\\.json$`,"u"),xy=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ry=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Cy=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Ay=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),_y=new Set(["capability","operation","source","content"]),_d=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Td(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Id(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 Ty(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Td(e,i);if(Id(r,_y,i),typeof r.capability!="string"||!_d.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 Iy(e){let t=Td(e,"Native portable Archive transaction");if(Id(t,Ay,"Native portable Archive transaction"),t.schema!==Dn)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!xy.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!_d.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"||!Ry.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"||!Cy.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(Ty);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:Dn,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 Bn(e){let t=Ey.exec(e);if(t)return{kind:"archive",change:t[1]};let i=Py.exec(e);return i?{kind:"migration",change:i[1]}:null}function yt(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Bn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return ks.join(e.transactionsDir,i)}async function Ss(e,t){let i=Bn(t);if(!i)return null;let r=await j({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=ks.join(e.transactionsDir,t);if(i.kind==="archive"){let s=Iy(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=bs(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 Jt(e,t){let i=yt(e,t);try{return await Ss(e,ks.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function jd(e){return e.kind==="archive"||e.journal.status!=="committed"}import He from"path";import{TextDecoder as Fy}from"util";import{createHash as jy}from"node:crypto";import{constants as Ln,promises as be}from"node:fs";import ke from"node:path";function Mn(e,t){let i=ke.relative(e,t);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function $y(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Oy(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Hy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Fn(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 Es(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 Dy(e,t,i){let r=ke.resolve(e),n=ke.resolve(t);if(!Mn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Es(r,i)],o=r;for(let s of ke.relative(r,n).split(ke.sep).filter(Boolean)){await Nt(a,i),o=ke.join(o,s);let c=await Es(o,i);if(!Mn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Nt(a,i),a}async function Nt(e,t){for(let i of e){let r=await be.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Oy(i,r)||await be.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function By(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 Gt(e){let t=$y(e.maxBytes),i=ke.resolve(e.file),r=await Dy(e.root,ke.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>Es(ke.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Nt(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=Hy(a),s=await be.realpath(i);if(!Mn(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>Mn(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ln.O_RDONLY:Ln.O_RDONLY|Ln.O_NOFOLLOW|Ln.O_NONBLOCK,l=await be.open(i,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[f,u]=await Promise.all([be.lstat(i),be.realpath(i)]);if(await Nt(r,e.label),await Nt(n,e.label),!d.isFile()||!f.isFile()||f.isSymbolicLink()||u!==s||!Fn(o,d)||!Fn(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await By(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 Nt(r,e.label),await Nt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Fn(o,v)||!Fn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:jy("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var My=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Vy=new Set(["id","type","source","target","staged","backup"]),qy=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Wy=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Hd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var zy=256*1024,XP=1024*1024,QP=16*1024;var ZP=64*1024*1024;var Jy=new Fy("utf-8",{fatal:!0});function qn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wn(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 Dd(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ps(e,t){if(typeof e!="string"||e.length===0||He.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Vn(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $d(e,t){if(Ps(e,t),e.includes("\\")||e!==He.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 Gy(e,t){let i=qn(e,`transaction operations[${t}]`);if(Wn(i,Vy,`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`);Ps(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ps(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 Bd(e){let t=qn(e,"Native Archive transaction journal");if(Wn(t,qy,"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"||!Hd.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(!Dd(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Vn(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=qn(s,`Archive transaction operations[${c}]`);if(Wn(l,Wy,`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`);$d(l.target,`Archive transaction operation ${l.id} target`);for(let d of["source","staged","backup"])l[d]!==void 0&&$d(l[d],`Archive transaction operation ${l.id} ${d}`);if(l.expectedTargetHash!==null&&Vn(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Vn(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Vn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${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 Uy(e){let t=qn(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bd(t);if(Wn(t,My,"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"||!Hd.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!He.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!He.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(!Dd(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(Gy),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 Ky(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return He.join(e.transactionsDir,t)}function Ld(e,t){let i=Ky(e,t);return{directory:i,journal:He.join(i,"transaction.json"),events:He.join(i,"events.jsonl"),staged:He.join(i,"staged"),backups:He.join(i,"backups")}}async function Rs(e,t){let i=Ld(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}async function Cs(e,t,i={}){let r=await Rs(e,t),n=await Gt({root:e.runtimeDir,file:r.journal,maxBytes:zy,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Jy.decode(n.bytes)),o=Uy(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Qy(e,t,i){let r;try{r=await Yy.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 Cs(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(Bn(n.name))try{let a=await Ss(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(jd(a))return!0}catch{return!0}return!1}async function Zy(e,t){let i=Date.now()+5e3,r=Xy.join(e.locksDir,"root-move.lock");for(;;)try{return await Cn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Nd(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 J(e,t,i,r){let n=await Zy(e,t);try{if(await Mi(e.projectRoot),await Qy(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await An(n)}}import{createHash as eN}from"crypto";function de(e){return eN("sha256").update(e).digest("hex")}var Nx={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var bx=8*1024*1024;var kx=64*1024,Sx=64*1024;var Ex={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Px={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var xx=(1n<<256n)-1n;var sN=ti(Dt(),1);var Vx=4*1024*1024;var cN=null;function lN(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Fd(e,t){return(...i)=>{let r=cN;if(r===null)return t(...i);let n=lN(`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 Gx=Fd("hookWritePolicy",async e=>(await Zo(e))?.hook??{allow_paths:[]});var VR=256*1024;var tC={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 Ut from"node:path";var Ki=/^[a-f0-9]{64}$/u,Vd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,fN=16*1024,gC=process.platform;function hN(e,t){let i=Ut.relative(e,t);return Ut.isAbsolute(i)||i===".."||i.startsWith(`..${Ut.sep}`)?null:i.replaceAll("\\","/")||"."}function qd(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wd(e,t){if(e.length===0||qd(e)||e.includes("\\")||Ut.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=Ut.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function pN(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 As(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||qd(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function mN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(As(e.changeBranch,"Native workspace change branch"),As(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 vN(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"||!Vd.test(t.baseCommit)||typeof t.targetCommit!="string"||!Vd.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");As(t.targetBranch,"Native workspace Git target branch")}function gN(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"||!Ki.test(String(t.projectRootId))||!Ki.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");pN(t.capturedAt),Wd(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&&!Ki.test(String(t.projectRootPathId))||a&&!Ki.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ki.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&vN(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(mN(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 Ut.join(xe(e,t),"workspace.json")}function yN(e,t){let i=wN(e,t),r=Re(e,i),n=hN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Wd(n,"Native workspace file ref")}}async function NN(e,t){try{let i=yN(e,t),r=await j({root:i.root,ref:i.ref,maxBytes:fN});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Yi(e,t){let i=await NN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(gN(i),i)}var Jd=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],SN=new Set(Jd),Gd=new Set([...Jd,"minimum_runtime_version","revision"]),EN=new Set([...Gd,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),PN=new Set(["capability","operation","source","base_hash"]),xN=new Set(["shape","build","verify","archive"]),RN=new Set(["implicit","confirmed"]),CN=new Set(["pending","pass","fail"]),bt="comet-state.yaml",Ts=/^[a-f0-9]{64}$/u,Ud=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Is=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"},Yt=class extends Error{constructor(i,r){super(i!==Oe||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"},zn=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"},Xi=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"},Jn=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"},MC=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function Zi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);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(", ")}`)}function $s(e){if(!Ud.test(e))throw new Error(`Invalid Native change name: ${e}`)}function _N(e){if(!Ud.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Yd(e,t){if(e.length===0||Kt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function TN(e,t){let i=Zi(e,`spec_changes[${t}]`);if(Kd(i,PN,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(_N(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"&&Yd(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"||!Ts.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"||!Ts.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 IN(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 Os(e,t){if(Kd(e,t,bt),typeof e.name!="string")throw new Error("Native change name is required");if($s(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"||!xN.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&&!RN.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(TN),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"||!CN.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"&&Yd(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!IN(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 Ji(e){let t=Zi(e,bt);if(t.schema!==_e)throw new Error(`Expected ${_e}`);return{schema:_e,...Os(t,SN)}}function Qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _s(e,t,i){if(e===null)return null;let r=typeof e=="string"?AN.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function jN(e){if(e==null)return null;if(typeof e!="string"||!Ts.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function $N(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 Gi(e){let t=Zi(e,bt);if(t.schema!==Ae)throw new Error(`Expected ${Ae}`);if(Qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ae} minimum_runtime_version must be 2`);return{schema:Ae,minimum_runtime_version:2,revision:Qi(t.revision,"Native v2 revision"),...Os(t,Gd)}}function Ui(e){let t=Zi(e,bt);if(t.schema!==Oe){if(t.schema===_e||t.schema===Ae){let o=t.schema===_e?Ji(t):Gi(t);throw new Is(o.name,o.schema)}throw new Yt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Yt(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Qi(t.revision,"Native revision"),n=Os(t,EN),a=jN(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Oe,minimum_runtime_version:3,revision:r,verification_protocol:$N(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_s(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_s(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_s(t.partial_allowance,"Native partial_allowance","allowances")}}function ON(e){let t=Zi(e,bt);if(t.schema===_e){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema===Ae){let n=Gi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema!==Oe){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 Yt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Yt(t.schema,i).message};let r=Ui(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function oe(e,t){$s(t);let i=Kt.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}var HN=256*1024;async function DN(e,t=Kt.dirname(e)){let i=Kt.relative(t,e).split(Kt.sep).join("/"),r=await j({root:t,ref:i,maxBytes:HN}),n=(0,js.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 Gn(e,t){let i=Kt.join(oe(e,t),bt);await T(e.nativeRoot,i);let r=ON(await DN(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{promises as nr}from"node:fs";import Le from"node:path";var nf=ti(Dt(),1);import{promises as MN}from"node:fs";import VN from"node:path";import{execFileSync as BN}from"node:child_process";var LN=3e4,FN=8*1024*1024,Hs=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 Xd(e,t){try{return BN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:LN,maxBuffer:FN,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Hs(e,t,r)}}function I(e,t){return Xd(e,t).trim()}function Un(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Ds(e){let t=Xd(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;nr.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 Zd="children.yaml",Bs="comet.native.children.v1",qN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WN=new Set(["schema","children"]),zN=new Set(["name","depends_on","covers"]);function ef(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tf(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 rf(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 JN(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 GN(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function UN(e,t){let i=(0,nf.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=ef(i.toJS({mapAsMap:!1}),"Native children contract");if(tf(r,WN,"Native children contract"),r.schema!==Bs)throw new Error(`Native children schema must be ${Bs}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=ef(s,`Native child ${c}`);if(tf(l,zN,`Native child ${c}`),typeof l.name!="string"||!qN.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:rf(l.depends_on,`Native child ${l.name} depends_on`),covers:rf(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return JN(n),t&&GN(n,t),{schema:Bs,children:n}}async function af(e){let t=VN.join(e.changeDir,Zd);try{await MN.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await j({root:e.changeDir,ref:Zd});return{contract:UN(i.text,e.acceptanceIds),size:i.size}}function of(e){return Z("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 tA=["$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 Kn="skill-coordinated";function QN(e){return e.state_version+1}function ZN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function eb(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:it(e.summary),completed_at:e.completedAt}}function Ls(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=zt(t,eb({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return ne({...r,phase:"build",status:"active",state_version:QN(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:ZN(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 cf}from"node:fs";import tr from"node:path";function Yn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xn(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 Te(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 sf(e,t){return e===null?null:Te(e,t)}function Zn(e,t,i=0){if(!Number.isSafeInteger(e)||eTe(l,`${i}.argv[${d}]`,!0)),a=Qn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Fs(r.startedAt,`${i}.startedAt`),s=Fs(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=Zn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Te(r.id,`${i}.id`),name:Te(r.name,`${i}.name`),operationId:Te(r.operationId,`${i}.operationId`),status:a,repeatable:ib(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Zn(r.executionCount,`${i}.executionCount`),argv:n,cwd:Ms(r.cwd,`${i}.cwd`),exitCode:tb(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Te(r.log,`${i}.log`)}}function Vs(e){let t="Native local execution state",i=Yn(e,t);if(Xn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==zi)throw new Error(`Native local execution schema must be ${zi}`);let r=Yn(i.workspace,"Native local workspace");Xn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Yn(i.execution,"Native local execution");Xn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Fs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Te(o.operationId,"Native local execution.operationId"),stage:Qn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Qn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:sf(o.executionId,"Native local execution.executionId"),status:Qn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Zn(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(rb);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:zi,change:Te(i.change,"Native local change"),basedOnStateVersion:Zn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ms(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ms(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:sf(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function nt(e){return Vs({schema:zi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:tr.resolve(e.projectRoot),worktreeRoot:tr.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function qs(e){let t;try{t=await cf.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 Vs(i)}async function De(e,t,i={}){let r=Vs(t);await cf.mkdir(tr.dirname(e),{recursive:!0}),await Y(e,r,i)}import{promises as nb}from"node:fs";function at(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` +`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Be(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"
")}function ab(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 ob(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===Kn?Kn:"host-attested")}function sb(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Be(o.id)} | ${Be(o.result)} | ${Be(o.source)} | ${Be(o.text)} | ${Be(at(o.reason))} |`).join(` `),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(at).join(" ");return`| ${Be(at(o.name))} | ${Be(s||"—")} | ${Be(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(` `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${at(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(` `),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${at(o)}`).join(` @@ -161,8 +161,8 @@ generated_from_state_version: ${e.state_version} ## Current result -- Result: **${rb(e)}** -- Assurance: **${nb(e)}** +- Result: **${ab(e)}** +- Assurance: **${ob(e)}** - Goal cycle: ${e.loop.goal_cycle} - Iteration: ${e.verification.iteration} - Verifier attempt: ${e.verification.attempt} @@ -196,21 +196,21 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ `:""}## Conclusion ${at(e.verification.summary)} -`}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 ir(e){let t;try{t=await ib.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 rr(e){await K(e.file,ab(e.state))}var lf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sb="comet-state.yaml",cb="state.json";function fe(e,t){if(!lf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Le.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return i}function se(e,t){return Le.join(fe(e,t),sb)}function kt(e,t){return Le.join(Pe(e,t),cb)}async function ar(e,t){try{let i=await nr.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 uf(e){return F(e).currentBranch}async function Fe(e,t){return ae(se(e,t))}async function df(e){let t=await wt({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=Le.join(fe(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await nr.rm(i,{force:!0})}return t}async function lb(e){let t=fe(e.paths,e.state.name),i=Le.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await nr.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(!lf.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=Le.join(t,...s.split("/")),l=await nr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let d=Le.join(e.paths.specsDir,o.name,"spec.md"),f="create";try{let u=await nr.lstat(d);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify"}catch(u){if(u.code!=="ENOENT")throw u}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 ub(e){let t=fe(e.paths,e.state.name),i=await I({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await I({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return _n({briefMarkdown:i.text,specs:r})}async function Ws(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 d=e.state.spec_changes[l];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&(c.operation===d.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await ub({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Pd(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await af({changeDir:fe(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?of({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 ff(e){return J(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 df({paths:e.paths,previous:t,next:i});return await De(kt(e.paths,t.name),nt({portableState:r,projectRoot:e.paths.projectRoot,branch:uf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await rr({file:Le.join(fe(e.paths,t.name),"verification.md"),state:r}),r})}async function hf(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...zt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:it(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 df({paths:e.paths,previous:t,next:r});return await De(kt(e.paths,t.name),nt({portableState:n,projectRoot:e.paths.projectRoot,branch:uf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function ea(e){if(e.state.verification===null)return"not-applicable";let t=Le.join(fe(e.paths,e.state.name),"verification.md");return await ir({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await rr({file:t,state:e.state}),"rebuilt")}import{promises as db}from"fs";import fb from"path";var zs="comet.selection.v2",hb=16*1024;function ta(e){return fb.join(e,".comet","current-change.json")}function pb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pf(e){return e===null||typeof e=="string"}function mb(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(!pb(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&&!pf(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:zs,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==zs)throw new Error(`current change selection schema must be ${zs}`);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(!pf(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 mf(e){let t;try{let r=ta(e),{bytes:n}=await mt(r,hb,{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",...mb(t)}}async function vf(e){await db.rm(ta(e),{force:!0})}async function gf(e,t,i){let r=await mf(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await vf(e),!0)}var S_=16*1024;function Js(e){return ta(e.projectRoot)}async function ia(e,t){return await Mi(e.projectRoot),gf(e.projectRoot,"native",t)}var or=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 Gs(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Us(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=U.join(e.archiveDir,t);if(!B(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ra(e){try{return await W.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function wf(e,t){let i=U.normalize(U.resolve(e)),r=U.normalize(U.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function yf(e,t){let i;try{i=await W.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=U.join(e.archiveDir,n.name);try{let o=await ae(U.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 Ks(e,t){let i=await Jt(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Nf(e,t){return await Ks(e,t)!==null||await yf(e,t)!==null}async function St(e,t){await W.mkdir(e.transactionsDir,{recursive:!0}),await Y(yt(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=ot(e.paths.projectRoot);i.some(a=>wf(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 tt(a,o.native.artifact_root);r.some(c=>wf(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 W.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(U.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 Gn(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 wb(e){let t=U.join(e.paths.specsDir,e.change.capability),i=U.join(t,"spec.md");if(!B(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await W.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 W.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([W.realpath(e.paths.specsDir),W.realpath(t)]);if(!B(o,s))throw new Error("Native canonical capability path escaped");try{let c=await W.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await W.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await W.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=U.join(fe(e.paths,e.state.name),e.change.source);await K(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await W.mkdir(t,{recursive:!0}),await K(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function Ys(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 yb(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 I({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function Nb(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(Ys(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Xs(e){let t=await Fe(e.paths,e.name),i=[];try{Ys(t)}catch(o){i.push(o.message)}if(await Ks(e.paths,e.name)===null)try{let o=await Ws({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 ir({file:U.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:Us(e.paths,Gs(t)),stateVersion:t.state_version}}async function kf(e){return J(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 Ks(e.paths,e.name),r=fe(e.paths,e.name),n=await ra(r),a=n?null:await yf(e.paths,e.name),o;if(n)o=await Fe(e.paths,e.name);else if(i)o=await ae(U.join(Us(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 Ws({paths:e.paths,state:o});if(l.drifted){let d=l.reason??"Native confirmed requirements changed";throw await hf({paths:e.paths,state:o,reason:d}),new Error(`${d}; Native change returned to Shape and requires confirmation`)}}let s=Us(e.paths,i?.archive_ref??Gs(o)),c=await ra(s);if(i&&Nb(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 ia(e.paths,o.name),await W.rm(Pe(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)Ys(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 or(l);i={schema:Dn,id:vb(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Gs(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await yb(e.paths,o),created_at:new Date().toISOString()},await St(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await St(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({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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 bb}from"node:crypto";import{promises as cr}from"node:fs";import kb from"node:path";var Sb=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function Eb(e,t){let i=await Jt(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function Sf(e,t){await cr.mkdir(e.transactionsDir,{recursive:!0}),await Y(yt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ef(e,t){await Promise.all([cr.rm(Pe(e,t),{recursive:!0,force:!0}),cr.rm(ns(e,t),{recursive:!0,force:!0}),...Sb.map(i=>cr.rm(kb.join(oe(e,t),i),{force:!0}))])}async function Pf(e,t){await De(kt(e,t.name),nt({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function xf(e,t){try{let i=await Yi(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 Rf(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 Pb(e){let t=oe(e.paths,e.state.name),i=await I({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 I({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return _n({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Cf(e,t){let i=await Gn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Af(e){return J(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Eb(e.paths,e.name),i=await ar(e.paths,e.name)?await ae(se(e.paths,e.name)):null;if(!t&&i)return await Ef(e.paths,e.name),await Pf(e.paths,i),i;let r=null,n=null;for(t||(r=await Cf(e.paths,e.name),n=await xf(e.paths,e.name),Rf(e.paths,n),t={schema:Hn,id:bb(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Sf(e.paths,t));;){let a=Cd(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Cf(e.paths,e.name),n??=await xf(e.paths,e.name),Rf(e.paths,n),i=Rd({state:r,acceptance:await Pb({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await On(se(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ef(e.paths,e.name):a.action==="commit-transaction"&&(i??=await ae(se(e.paths,e.name)),await Pf(e.paths,i)),t={...t,status:a.nextStatus},await Sf(e.paths,t)}return await cr.rm(yt(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 _f}from"node:fs";import Tf from"node:path";function xb(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 Rb(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Cb(e,t){let i=new Date().toISOString(),r=e.verification===null?e:zt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:it(t),completed_at:i});return ne({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:Rb(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 Ab(e){try{let t=await qs(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 If(e){return J(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.status==="done")return await ea({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=xb(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=kt(e.paths,e.name),n=await Ab(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(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await De(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await ea({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(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=Ls({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await wt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await _f.rm(Tf.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=nt({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await De(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",d=c||l;if(d){let u=Cb(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 wt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let f=nt({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await _f.mkdir(Tf.dirname(kt(e.paths,t.name)),{recursive:!0}),await De(r,f,{containedRoot:e.paths.runtimeDir}),await ea({paths:e.paths,state:t}),{state:t,local:f,action:d?"reverify":"resume-stable-boundary",reason:a,message:d?"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{promises as Hb}from"node:fs";import Qt from"node:path";import{execFileSync as _b}from"node:child_process";var Tb=6e4,Ib=8*1024*1024,Qs=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 Zs(e,t,i={}){let r=i.timeoutMs??Tb,n=i.maxBufferBytes??Ib;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 _b(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","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 Qs(e,t,o,{cause:a})}}import $b from"path";var Ob=["Outcome","Scope","Non-goals","Acceptance examples"],kT=[...Ob,"Constraints and invariants","Decisions","Open questions","Verification expectations"];function na(e,t){return $b.join(e.specsDir,t,"spec.md")}var lr=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function Db(e,t){let i=Qt.relative(e,t);return i===""||!Qt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qt.sep}`)}function Et(e,t){let i=Qt.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Qt.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function jf(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function Bb(e){try{if(L(e,["config","--get","user.name"])&&L(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function Lb(e,t){for(let i of ot(e))if(F(i).currentBranch===t)return i;return null}function Fb(e,t){try{Zs(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function ec(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`);Bb(t.projectRoot);let a=[Et(t.projectRoot,Js(t))];e.archiveDir&&a.push(Et(t.projectRoot,oe(t,i.name)),Et(t.projectRoot,e.archiveDir));let o=Ds(t.projectRoot).filter(l=>!jf(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:Lb(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(!Un(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Qd(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&Fb("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function Mb(e,t){try{return Zs("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function Vb(e){try{return await Hb.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function qb(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function $f(e){let t=qb(e.plan),i=null;try{let r=[Et(e.paths.projectRoot,oe(e.paths,e.name)),Et(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(c=>Et(e.paths.projectRoot,na(e.paths,c.capability))),Et(e.paths.projectRoot,Js(e.paths))],n=Ds(e.plan.changeRoot).filter(c=>!jf(c,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=[];for(let c of r){let l=Qt.resolve(e.paths.projectRoot,...c.split("/")),d=L(e.plan.changeRoot,["ls-files","--",c])!=="";(await Vb(l)||d)&&a.push(c)}if(a.length>0&&L(e.plan.changeRoot,["add","-A","--",...a]),L(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&L(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=L(e.plan.changeRoot,["rev-parse","HEAD"]),!Un(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"){if(L(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=Mb(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(l=>/^https?:\/\//u.test(l.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let c=Db(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!c?(L(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 s=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(L(s,["switch",e.plan.targetBranch]),i=s),L(s,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=s,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(i!==null){let n;try{L(i,["merge","--abort"])}catch{}try{F(i).currentBranch===e.plan.targetBranch&&L(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==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new lr(t)}}import rc from"path";var Wb=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 Of=1024*1024;var Df="scoped-text-safety",zb=1,Jb=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Gb="comet.native.checker-policy.v1";var rI=Z(Gb,{policy:Df,version:zb,limits:Jb,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Ub=["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"],nI=new Set(Ub);var Xb=Of,bI=3*Xb;var Bf={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:[]},Zb=de("comet-native-runtime:v3:scope-reopen"),UI=[{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 Ff=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Cj=new Set(Ff),ok=new Set([...Ff,"minimum_runtime_version","revision"]),Aj=new Set([...ok,"operation"]),_j=512*1024,sk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Tj=new Set([...sk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var Oj={maxAcceptanceCriteria:Wi.maxCriteria};var Fj={maxSpecs:64,maxFileBytes:pr,maxTotalBytes:4*1024*1024};import{execFile as vk}from"node:child_process";import{promisify as gk}from"node:util";var Yj={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var g$=512*1024;var ur=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var F$=64*1024;var M$=3600*1e3;var V$=gk(vk);var aa=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 RO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var DO=16*1024*1024,BO=256*1024,LO=16*1024;var WO=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var j0=16*1024*1024,oa=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"},sa=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 ca=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var qf=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ic=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:qf,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] +`}function cb(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 ir(e){let t;try{t=await nb.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=cb(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function rr(e){await K(e.file,sb(e.state))}var lf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lb="comet-state.yaml",ub="state.json";function fe(e,t){if(!lf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Le.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}function se(e,t){return Le.join(fe(e,t),lb)}function kt(e,t){return Le.join(Pe(e,t),ub)}async function ar(e,t){try{let i=await nr.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 uf(e){return F(e).currentBranch}async function Fe(e,t){return ae(se(e,t))}async function df(e){let t=await wt({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=Le.join(fe(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await nr.rm(i,{force:!0})}return t}async function db(e){let t=fe(e.paths,e.state.name),i=Le.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await nr.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(!lf.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=Le.join(t,...s.split("/")),l=await nr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let d=Le.join(e.paths.specsDir,o.name,"spec.md"),f="create";try{let u=await nr.lstat(d);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify"}catch(u){if(u.code!=="ENOENT")throw u}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 fb(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 _n({briefMarkdown:i.text,specs:r})}async function Ws(e){let t=await db(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 d=e.state.spec_changes[l];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&(c.operation===d.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await fb({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Pd(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await af({changeDir:fe(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?of({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 ff(e){return J(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 df({paths:e.paths,previous:t,next:i});return await De(kt(e.paths,t.name),nt({portableState:r,projectRoot:e.paths.projectRoot,branch:uf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await rr({file:Le.join(fe(e.paths,t.name),"verification.md"),state:r}),r})}async function hf(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...zt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:it(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 df({paths:e.paths,previous:t,next:r});return await De(kt(e.paths,t.name),nt({portableState:n,projectRoot:e.paths.projectRoot,branch:uf(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function ea(e){if(e.state.verification===null)return"not-applicable";let t=Le.join(fe(e.paths,e.state.name),"verification.md");return await ir({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await rr({file:t,state:e.state}),"rebuilt")}import{promises as hb}from"fs";import pb from"path";var zs="comet.selection.v2",mb=16*1024;function ta(e){return pb.join(e,".comet","current-change.json")}function vb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pf(e){return e===null||typeof e=="string"}function gb(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&&!pf(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:zs,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==zs)throw new Error(`current change selection schema must be ${zs}`);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(!pf(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 mf(e){let t;try{let r=ta(e),{bytes:n}=await mt(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",...gb(t)}}async function vf(e){await hb.rm(ta(e),{force:!0})}async function gf(e,t,i){let r=await mf(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await vf(e),!0)}var R_=16*1024;function Js(e){return ta(e.projectRoot)}async function ia(e,t){return await Mi(e.projectRoot),gf(e.projectRoot,"native",t)}var or=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 Gs(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Us(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=U.join(e.archiveDir,t);if(!L(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ra(e){try{return await W.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function wf(e,t){let i=U.normalize(U.resolve(e)),r=U.normalize(U.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function yf(e,t){let i;try{i=await W.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=U.join(e.archiveDir,n.name);try{let o=await ae(U.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 Ks(e,t){let i=await Jt(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Nf(e,t){return await Ks(e,t)!==null||await yf(e,t)!==null}async function St(e,t){await W.mkdir(e.transactionsDir,{recursive:!0}),await Y(yt(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=ot(e.paths.projectRoot);i.some(a=>wf(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 tt(a,o.native.artifact_root);r.some(c=>wf(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 W.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(U.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 Gn(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 yb(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 Nb(e){let t=U.join(e.paths.specsDir,e.change.capability),i=U.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 W.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 W.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([W.realpath(e.paths.specsDir),W.realpath(t)]);if(!L(o,s))throw new Error("Native canonical capability path escaped");try{let c=await W.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await W.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await W.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=U.join(fe(e.paths,e.state.name),e.change.source);await K(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await W.mkdir(t,{recursive:!0}),await K(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function Ys(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 bb(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(Ys(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Xs(e){let t=await Fe(e.paths,e.name),i=[];try{Ys(t)}catch(o){i.push(o.message)}if(await Ks(e.paths,e.name)===null)try{let o=await Ws({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 ir({file:U.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:Us(e.paths,Gs(t)),stateVersion:t.state_version}}async function kf(e){return J(e.paths,`archive portable change ${e.name}`,async()=>{let t=yb(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await Ks(e.paths,e.name),r=fe(e.paths,e.name),n=await ra(r),a=n?null:await yf(e.paths,e.name),o;if(n)o=await Fe(e.paths,e.name);else if(i)o=await ae(U.join(Us(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 Ws({paths:e.paths,state:o});if(l.drifted){let d=l.reason??"Native confirmed requirements changed";throw await hf({paths:e.paths,state:o,reason:d}),new Error(`${d}; Native change returned to Shape and requires confirmation`)}}let s=Us(e.paths,i?.archive_ref??Gs(o)),c=await ra(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 ia(e.paths,o.name),await W.rm(Pe(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)Ys(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 or(l);i={schema:Dn,id:wb(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Gs(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await bb(e.paths,o),created_at:new Date().toISOString()},await St(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await St(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({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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 Sb}from"node:crypto";import{promises as cr}from"node:fs";import Eb from"node:path";var Sf=["evidence.md","repair.md","archive.md","checkpoint.md"],Pb="verification.md";async function xb(e,t){let i=await Jt(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function Ef(e,t){await cr.mkdir(e.transactionsDir,{recursive:!0}),await Y(yt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Pf(e,t,i={}){let r=i.removeVerificationReport===!1?Sf:[...Sf,Pb];await Promise.all([cr.rm(Pe(e,t),{recursive:!0,force:!0}),cr.rm(ns(e,t),{recursive:!0,force:!0}),...r.map(n=>cr.rm(Eb.join(oe(e,t),n),{force:!0}))])}async function xf(e,t){await De(kt(e,t.name),nt({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Rf(e,t){try{let i=await Yi(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 Cf(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 Rb(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 _n({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Af(e,t){let i=await Gn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function _f(e){return J(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await xb(e.paths,e.name),i=await ar(e.paths,e.name)?await ae(se(e.paths,e.name)):null;if(!t&&i)return await Pf(e.paths,e.name,{removeVerificationReport:!1}),await xf(e.paths,i),i;let r=null,n=null;for(t||(r=await Af(e.paths,e.name),n=await Rf(e.paths,e.name),Cf(e.paths,n),t={schema:Hn,id:Sb(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Ef(e.paths,t));;){let a=Cd(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Af(e.paths,e.name),n??=await Rf(e.paths,e.name),Cf(e.paths,n),i=Rd({state:r,acceptance:await Rb({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await On(se(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Pf(e.paths,e.name):a.action==="commit-transaction"&&(i??=await ae(se(e.paths,e.name)),await xf(e.paths,i)),t={...t,status:a.nextStatus},await Ef(e.paths,t)}return await cr.rm(yt(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 Tf}from"node:fs";import If from"node:path";function Cb(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 Ab(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function _b(e,t){let i=new Date().toISOString(),r=e.verification===null?e:zt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:it(t),completed_at:i});return ne({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:Ab(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 Tb(e){try{let t=await qs(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 jf(e){return J(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.status==="done")return await ea({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=Cb(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=kt(e.paths,e.name),n=await Tb(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(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await De(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await ea({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(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=Ls({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await wt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await Tf.rm(If.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=nt({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await De(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",d=c||l;if(d){let u=_b(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 wt({file:se(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let f=nt({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await Tf.mkdir(If.dirname(kt(e.paths,t.name)),{recursive:!0}),await De(r,f,{containedRoot:e.paths.runtimeDir}),await ea({paths:e.paths,state:t}),{state:t,local:f,action:d?"reverify":"resume-stable-boundary",reason:a,message:d?"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{promises as Bb}from"node:fs";import Qt from"node:path";import{execFileSync as Ib}from"node:child_process";var jb=6e4,$b=8*1024*1024,Qs=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 Zs(e,t,i={}){let r=i.timeoutMs??jb,n=i.maxBufferBytes??$b;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 Ib(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","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 Qs(e,t,o,{cause:a})}}import Hb from"path";var Db=["Outcome","Scope","Non-goals","Acceptance examples"],xT=[...Db,"Constraints and invariants","Decisions","Open questions","Verification expectations"];function na(e,t){return Hb.join(e.specsDir,t,"spec.md")}var lr=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function Lb(e,t){let i=Qt.relative(e,t);return i===""||!Qt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qt.sep}`)}function Et(e,t){let i=Qt.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Qt.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function $f(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function Of(e){return e.split("\0").filter(Boolean)}function Fb(e,t){return Of(I(e,["ls-files","-z","--",t]))}function Mb(e,t){return Of(I(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function Vb(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 qb(e,t){for(let i of ot(e))if(F(i).currentBranch===t)return i;return null}function Wb(e,t){try{Zs(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function ec(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`);Vb(t.projectRoot);let a=[Et(t.projectRoot,Js(t))];e.archiveDir&&a.push(Et(t.projectRoot,oe(t,i.name)),Et(t.projectRoot,e.archiveDir));let o=Ds(t.projectRoot).filter(l=>!$f(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:qb(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(!Un(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Qd(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&Wb("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function zb(e,t){try{return Zs("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function Jb(e){try{return await Bb.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Gb(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function Hf(e){let t=Gb(e.plan),i=null;try{let r=[Et(e.paths.projectRoot,oe(e.paths,e.name)),Et(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>Et(e.paths.projectRoot,na(e.paths,l.capability))),Et(e.paths.projectRoot,Js(e.paths))],n=Ds(e.plan.changeRoot).filter(l=>!$f(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 d=Qt.resolve(e.paths.projectRoot,...l.split("/"));if(Fb(e.plan.changeRoot,l).length>0&&a.push(l),await Jb(d))for(let u of Mb(e.plan.changeRoot,l))o.add(u)}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"]),!Un(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"){if(I(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=zb(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(d=>/^https?:\/\//u.test(d.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let l=Lb(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(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==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new lr(t)}}import rc from"path";var Ub=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 Df=1024*1024;var Lf="scoped-text-safety",Kb=1,Yb=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Xb="comet.native.checker-policy.v1";var sI=Z(Xb,{policy:Lf,version:Kb,limits:Yb,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Qb=["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"],cI=new Set(Qb);var tk=Df,PI=3*tk;var Ff={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:[]},rk=de("comet-native-runtime:v3:scope-reopen"),QI=[{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 Vf=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Ij=new Set(Vf),uk=new Set([...Vf,"minimum_runtime_version","revision"]),jj=new Set([...uk,"operation"]),$j=512*1024,dk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Oj=new Set([...dk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var Lj={maxAcceptanceCriteria:Wi.maxCriteria};var Wj={maxSpecs:64,maxFileBytes:pr,maxTotalBytes:4*1024*1024};import{execFile as Nk}from"node:child_process";import{promisify as bk}from"node:util";var e$={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var b$=512*1024;var ur=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var W$=64*1024;var z$=3600*1e3;var J$=bk(Nk);var aa=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 TO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var MO=16*1024*1024,VO=256*1024,qO=16*1024;var UO=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var D0=16*1024*1024,oa=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"},sa=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 ca=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var zf=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ic=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:zf,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] comet native next --runner-input `,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 Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--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.","--runner-input 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 "Implementation changed" --return-to-build','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 "]},archive:{usage:`comet native archive --dry-run [--finish merge|push|pull-request|keep] comet native archive [--confirmed] [--serial-first ]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first During execution only, confirm that this change archives before detected capability peers; the value must equal .","--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 [] [--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 tc(e,t){return`${e}: ${t.map(i=>` ${i}`).join(` -`)}`}function kk(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return ic[i]||t.length>1&&ic[t[0]]?.subcommands?i:t[0]}function Sk(e=[]){let t=kk(e),i=ic[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",tc("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...qf];return n&&n.length>0&&r.push("",tc("Options",n)),r.push("",`Output: +`)}`}function xk(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return ic[i]||t.length>1&&ic[t[0]]?.subcommands?i:t[0]}function Rk(e=[]){let t=xk(e),i=ic[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",tc("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...zf];return n&&n.length>0&&r.push("",tc("Options",n)),r.push("",`Output: ${i.output}`),i.examples&&r.push("",tc("Examples",i.examples)),t===""&&r.push("","Run `comet native --help` for command-specific details."),{topic:t,usage:`${r.join(` `)} -`}}var Ek=Sk().usage;var eH=10*1024*1024,$=class extends Error{};function dr(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new $(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Zt(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new $(`${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 $(`${t} requires a value`);return e.splice(r,2),n}function nc(e){if(e.length>0)throw new $(`Unexpected argument: ${e[0]}`)}function zf(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new $(`${t} is required`);return i}function Wf(e,t){let i=rc.normalize(e),r=rc.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Pk(e){let t=rc.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||!Wf(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Wf(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function Jf(e){return e?Pk(e):Pn(process.cwd())}async function Gf(e){let t=await cd({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ei(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` -`}}function Uf(e,t){if(t instanceof $)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof oa)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 sa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof zn)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 Xi)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 ca)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Jn)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 aa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ur)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 Kf(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` -`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Yf(e,t){let i=zf(e,"change name"),r=dr(e,"--dry-run"),n=Zt(e,"--expect-preflight"),a=dr(e,"--confirmed"),o=Zt(e,"--finish"),s=Zt(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new $("--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 $("--finish must be merge, push, pull-request, or keep");let l=await Gf(t),d=await ar(l.paths,i),f=d?await Jt(l.paths,{kind:"archive",change:i}):null,u=d?!1:await Nf(l.paths,i);if(d||u){if(n)throw new $("Portable Native Archive does not use preflight hashes");if(r&&a)throw new $("--confirmed is only valid when executing Archive");if(r&&s)throw new $("--serial-first is only valid when executing Archive");if(!r&&c)throw new $("--finish is only valid with --dry-run");nc(e);let v=d&&!r&&f?.kind!=="archive"?await If({paths:l.paths,name:i}):null,h=v?.state??(d?await Fe(l.paths,i):null);if(v?.action==="reverify"||v?.action==="await-user")return ei(r?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:sr(v.state)},`${v.message} +`}}var Ck=Rk().usage;var nH=10*1024*1024,O=class extends Error{};function dr(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 Zt(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 Gf(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new O(`${t} is required`);return i}function Jf(e,t){let i=rc.normalize(e),r=rc.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ak(e){let t=rc.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||!Jf(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Jf(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function Uf(e){return e?Ak(e):Pn(process.cwd())}async function Kf(e){let t=await cd({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ei(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` +`}}function Yf(e,t){if(t instanceof O)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof oa)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 sa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof zn)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 Xi)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 ca)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Jn)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 aa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ur)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 Xf(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` +`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Qf(e,t){let i=Gf(e,"change name"),r=dr(e,"--dry-run"),n=Zt(e,"--expect-preflight"),a=dr(e,"--confirmed"),o=Zt(e,"--finish"),s=Zt(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 Kf(t),d=await ar(l.paths,i),f=d?await Jt(l.paths,{kind:"archive",change:i}):null,u=d?!1:await Nf(l.paths,i);if(d||u){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=d&&!r&&f?.kind!=="archive"?await jf({paths:l.paths,name:i}):null,h=v?.state??(d?await Fe(l.paths,i):null);if(v?.action==="reverify"||v?.action==="await-user")return ei(r?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:sr(v.state)},`${v.message} `);if(r){if(!h)return ei("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} -`);if(c)h=await ff({paths:l.paths,name:i,finish:c});else if(h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new $("Native branch and worktree isolation require --finish with --dry-run");let w=await Xs({paths:l.paths,name:i}),k=sr(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 ei("archive --dry-run",{...w,workspaceFinish:h.workspace.finish,continuation:S},`Native Archive preview: ${w.ready?"ready":"blocked"} -`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new $("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new $("Native branch and worktree isolation require a persisted --finish preview");let m=h?await ec({paths:l.paths,state:h}):null,g;try{g=await kf({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(w){if(!(w instanceof or)||!h)throw w;let k=await Xs({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 ec({paths:l.paths,state:h,archiveDir:g.archiveDir}));let N=null;if(m)try{N=await $f({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:m})}catch(w){if(!(w instanceof lr))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 ei("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:N,continuation:sr(g.state)},`Archived Native change ${i} to ${g.archiveDir} -`)}if(s)throw new $("--serial-first is only valid for portable Native changes");if(!r&&c)throw new $("--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 Af({paths:l.paths,name:i});return ei("archive",{migration:{from:"legacy",to:p.schema,completed:!0},state:p,continuation:sr(p)},`Migrated Native change ${i}; follow the returned portable continuation before Archive -`)}function xk(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}})+` -`}}async function Xf(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{dr(n,"--json"),s=Zt(n,"--project-root");let d=[...n,...a],f=await Jf(s);c=await t(d,f)}catch(d){c=Uf(e,d)}let l=o?xk(c):Kf(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` +`);if(c)h=await ff({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 Xs({paths:l.paths,name:i}),k=sr(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 ei("archive --dry-run",{...w,workspaceFinish:h.workspace.finish,continuation:S},`Native Archive preview: ${w.ready?"ready":"blocked"} +`)}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 ec({paths:l.paths,state:h}):null,g;try{g=await kf({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(w){if(!(w instanceof or)||!h)throw w;let k=await Xs({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 ec({paths:l.paths,state:h,archiveDir:g.archiveDir}));let N=null;if(m)try{N=await Hf({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:m})}catch(w){if(!(w instanceof lr))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 ei("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:N,continuation:sr(g.state)},`Archived Native change ${i} to ${g.archiveDir} +`)}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 _f({paths:l.paths,name:i});return ei("archive",{migration:{from:"legacy",to:p.schema,completed:!0},state:p,continuation:sr(p)},`Migrated Native change ${i}; follow the returned portable continuation before Archive +`)}function _k(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}})+` +`}}async function Zf(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{dr(n,"--json"),s=Zt(n,"--project-root");let d=[...n,...a],f=await Uf(s);c=await t(d,f)}catch(d){c=Yf(e,d)}let l=o?_k(c):Xf(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` `)?"":` -`)),l.exitCode}process.exitCode=await Xf("archive",Yf); +`)),l.exitCode}process.exitCode=await Zf("archive",Qf); diff --git a/assets/skills/comet-native/scripts/comet-native-doctor.mjs b/assets/skills/comet-native/scripts/comet-native-doctor.mjs index 0e5158b36..c376b8f71 100644 --- a/assets/skills/comet-native/scripts/comet-native-doctor.mjs +++ b/assets/skills/comet-native/scripts/comet-native-doctor.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var JS=Object.create;var sm=Object.defineProperty;var GS=Object.getOwnPropertyDescriptor;var US=Object.getOwnPropertyNames;var KS=Object.getPrototypeOf,YS=Object.prototype.hasOwnProperty;var Ps=(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 x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var XS=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of US(t))!YS.call(e,n)&&n!==i&&sm(e,n,{get:()=>t[n],enumerable:!(r=GS(t,n))||r.enumerable});return e};var hn=(e,t,i)=>(i=e!=null?JS(KS(e)):{},XS(t||!e||!e.__esModule?sm(i,"default",{value:e,enumerable:!0}):i,e));var J=x(Ce=>{"use strict";var Fu=Symbol.for("yaml.alias"),hm=Symbol.for("yaml.document"),Rs=Symbol.for("yaml.map"),pm=Symbol.for("yaml.pair"),Lu=Symbol.for("yaml.scalar"),xs=Symbol.for("yaml.seq"),Ni=Symbol.for("yaml.node.type"),tE=e=>!!e&&typeof e=="object"&&e[Ni]===Fu,iE=e=>!!e&&typeof e=="object"&&e[Ni]===hm,rE=e=>!!e&&typeof e=="object"&&e[Ni]===Rs,nE=e=>!!e&&typeof e=="object"&&e[Ni]===pm,mm=e=>!!e&&typeof e=="object"&&e[Ni]===Lu,aE=e=>!!e&&typeof e=="object"&&e[Ni]===xs;function vm(e){if(e&&typeof e=="object")switch(e[Ni]){case Rs:case xs:return!0}return!1}function oE(e){if(e&&typeof e=="object")switch(e[Ni]){case Fu:case Rs:case Lu:case xs:return!0}return!1}var sE=e=>(mm(e)||vm(e))&&!!e.anchor;Ce.ALIAS=Fu;Ce.DOC=hm;Ce.MAP=Rs;Ce.NODE_TYPE=Ni;Ce.PAIR=pm;Ce.SCALAR=Lu;Ce.SEQ=xs;Ce.hasAnchor=sE;Ce.isAlias=tE;Ce.isCollection=vm;Ce.isDocument=iE;Ce.isMap=rE;Ce.isNode=oE;Ce.isPair=nE;Ce.isScalar=mm;Ce.isSeq=aE});var Ia=x(Bu=>{"use strict";var Ee=J(),tt=Symbol("break visit"),gm=Symbol("skip children"),ei=Symbol("remove node");function Cs(e,t){let i=wm(t);Ee.isDocument(e)?pn(null,e.contents,i,Object.freeze([e]))===ei&&(e.contents=null):pn(null,e,i,Object.freeze([]))}Cs.BREAK=tt;Cs.SKIP=gm;Cs.REMOVE=ei;function pn(e,t,i,r){let n=ym(e,t,i,r);if(Ee.isNode(n)||Ee.isPair(n))return Nm(e,r,n),pn(e,n,i,r);if(typeof n!="symbol"){if(Ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var bm=J(),cE=Ia(),lE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},uE=e=>e.replace(/[!,[\]{}]/g,t=>lE[t]),ja=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+uE(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&&bm.isNode(t.contents)){let a={};cE.visit(t.contents,(o,s)=>{bm.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(` -`)}};ja.defaultYaml={explicit:!1,version:"1.2"};ja.defaultTags={"!!":"tag:yaml.org,2002:"};km.Directives=ja});var _s=x($a=>{"use strict";var Sm=J(),dE=Ia();function fE(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 Em(e){let t=new Set;return dE.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Pm(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function hE(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Em(e));let o=Pm(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Sm.isScalar(o.node)||Sm.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}}$a.anchorIsValid=fE;$a.anchorNames=Em;$a.createNodeAnchors=hE;$a.findNewAnchor=Pm});var Vu=x(Rm=>{"use strict";function Oa(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var pE=J();function xm(e,t,i){if(Array.isArray(e))return e.map((r,n)=>xm(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!pE.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}Cm.toJS=xm});var Ts=x(_m=>{"use strict";var mE=Vu(),Am=J(),vE=Mi(),Wu=class{constructor(t){Object.defineProperty(this,Am.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(!Am.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=vE.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?mE.applyReviver(a,{"":s},"",s):s}};_m.NodeBase=Wu});var Ha=x(Tm=>{"use strict";var gE=_s(),wE=Ia(),vn=J(),yE=Ts(),NE=Mi(),zu=class extends yE.NodeBase{constructor(t){super(vn.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=[],wE.visit(t,{Node:(a,o)=>{(vn.isAlias(o)||vn.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||(NE.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=Is(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(gE.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Is(e,t,i){if(vn.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(vn.isCollection(t)){let r=0;for(let n of t.items){let a=Is(e,n,i);a>r&&(r=a)}return r}else if(vn.isPair(t)){let r=Is(e,t.key,i),n=Is(e,t.value,i);return Math.max(r,n)}return 1}Tm.Alias=zu});var ye=x(Ju=>{"use strict";var bE=J(),kE=Ts(),SE=Mi(),EE=e=>!e||typeof e!="function"&&typeof e!="object",Fi=class extends kE.NodeBase{constructor(t){super(bE.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:SE.toJS(this.value,t,i)}toString(){return String(this.value)}};Fi.BLOCK_FOLDED="BLOCK_FOLDED";Fi.BLOCK_LITERAL="BLOCK_LITERAL";Fi.PLAIN="PLAIN";Fi.QUOTE_DOUBLE="QUOTE_DOUBLE";Fi.QUOTE_SINGLE="QUOTE_SINGLE";Ju.Scalar=Fi;Ju.isScalarValue=EE});var Da=x(jm=>{"use strict";var PE=Ha(),$r=J(),Im=ye(),RE="tag:yaml.org,2002:";function xE(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 CE(e,t,i){if($r.isDocument(e)&&(e=e.contents),$r.isNode(e))return e;if($r.isPair(e)){let d=i.schema[$r.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 PE.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=RE+t.slice(2));let l=xE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Im.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[$r.MAP]:Symbol.iterator in Object(e)?o[$r.SEQ]:o[$r.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 Im.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}jm.createNode=CE});var $s=x(js=>{"use strict";var AE=Da(),ti=J(),_E=Ts();function Gu(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 AE.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 $m=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Uu=class extends _E.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=>ti.isNode(r)||ti.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if($m(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(ti.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Gu(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(ti.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&&ti.isScalar(a)?a.value:a:ti.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!ti.isPair(i))return!1;let r=i.value;return r==null||t&&ti.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 ti.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(ti.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Gu(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};js.Collection=Uu;js.collectionFromPath=Gu;js.isEmptyPath=$m});var Ma=x(Os=>{"use strict";var TE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ku(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var IE=(e,t,i)=>e.endsWith(` +var JS=Object.create;var cm=Object.defineProperty;var GS=Object.getOwnPropertyDescriptor;var US=Object.getOwnPropertyNames;var KS=Object.getPrototypeOf,YS=Object.prototype.hasOwnProperty;var Ps=(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 x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var XS=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of US(t))!YS.call(e,n)&&n!==i&&cm(e,n,{get:()=>t[n],enumerable:!(r=GS(t,n))||r.enumerable});return e};var hn=(e,t,i)=>(i=e!=null?JS(KS(e)):{},XS(t||!e||!e.__esModule?cm(i,"default",{value:e,enumerable:!0}):i,e));var J=x(Ce=>{"use strict";var Fu=Symbol.for("yaml.alias"),pm=Symbol.for("yaml.document"),Rs=Symbol.for("yaml.map"),mm=Symbol.for("yaml.pair"),Lu=Symbol.for("yaml.scalar"),xs=Symbol.for("yaml.seq"),Ni=Symbol.for("yaml.node.type"),tE=e=>!!e&&typeof e=="object"&&e[Ni]===Fu,iE=e=>!!e&&typeof e=="object"&&e[Ni]===pm,rE=e=>!!e&&typeof e=="object"&&e[Ni]===Rs,nE=e=>!!e&&typeof e=="object"&&e[Ni]===mm,vm=e=>!!e&&typeof e=="object"&&e[Ni]===Lu,aE=e=>!!e&&typeof e=="object"&&e[Ni]===xs;function gm(e){if(e&&typeof e=="object")switch(e[Ni]){case Rs:case xs:return!0}return!1}function oE(e){if(e&&typeof e=="object")switch(e[Ni]){case Fu:case Rs:case Lu:case xs:return!0}return!1}var sE=e=>(vm(e)||gm(e))&&!!e.anchor;Ce.ALIAS=Fu;Ce.DOC=pm;Ce.MAP=Rs;Ce.NODE_TYPE=Ni;Ce.PAIR=mm;Ce.SCALAR=Lu;Ce.SEQ=xs;Ce.hasAnchor=sE;Ce.isAlias=tE;Ce.isCollection=gm;Ce.isDocument=iE;Ce.isMap=rE;Ce.isNode=oE;Ce.isPair=nE;Ce.isScalar=vm;Ce.isSeq=aE});var Ia=x(Bu=>{"use strict";var Ee=J(),tt=Symbol("break visit"),wm=Symbol("skip children"),ei=Symbol("remove node");function Cs(e,t){let i=ym(t);Ee.isDocument(e)?pn(null,e.contents,i,Object.freeze([e]))===ei&&(e.contents=null):pn(null,e,i,Object.freeze([]))}Cs.BREAK=tt;Cs.SKIP=wm;Cs.REMOVE=ei;function pn(e,t,i,r){let n=Nm(e,t,i,r);if(Ee.isNode(n)||Ee.isPair(n))return bm(e,r,n),pn(e,n,i,r);if(typeof n!="symbol"){if(Ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var km=J(),cE=Ia(),lE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},uE=e=>e.replace(/[!,[\]{}]/g,t=>lE[t]),ja=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+uE(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&&km.isNode(t.contents)){let a={};cE.visit(t.contents,(o,s)=>{km.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(` +`)}};ja.defaultYaml={explicit:!1,version:"1.2"};ja.defaultTags={"!!":"tag:yaml.org,2002:"};Sm.Directives=ja});var _s=x($a=>{"use strict";var Em=J(),dE=Ia();function fE(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 Pm(e){let t=new Set;return dE.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Rm(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function hE(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Pm(e));let o=Rm(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Em.isScalar(o.node)||Em.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}}$a.anchorIsValid=fE;$a.anchorNames=Pm;$a.createNodeAnchors=hE;$a.findNewAnchor=Rm});var Vu=x(xm=>{"use strict";function Oa(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var pE=J();function Cm(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Cm(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!pE.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}Am.toJS=Cm});var Ts=x(Tm=>{"use strict";var mE=Vu(),_m=J(),vE=Mi(),Wu=class{constructor(t){Object.defineProperty(this,_m.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(!_m.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=vE.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?mE.applyReviver(a,{"":s},"",s):s}};Tm.NodeBase=Wu});var Ha=x(Im=>{"use strict";var gE=_s(),wE=Ia(),vn=J(),yE=Ts(),NE=Mi(),zu=class extends yE.NodeBase{constructor(t){super(vn.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=[],wE.visit(t,{Node:(a,o)=>{(vn.isAlias(o)||vn.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||(NE.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=Is(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(gE.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Is(e,t,i){if(vn.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(vn.isCollection(t)){let r=0;for(let n of t.items){let a=Is(e,n,i);a>r&&(r=a)}return r}else if(vn.isPair(t)){let r=Is(e,t.key,i),n=Is(e,t.value,i);return Math.max(r,n)}return 1}Im.Alias=zu});var ye=x(Ju=>{"use strict";var bE=J(),kE=Ts(),SE=Mi(),EE=e=>!e||typeof e!="function"&&typeof e!="object",Fi=class extends kE.NodeBase{constructor(t){super(bE.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:SE.toJS(this.value,t,i)}toString(){return String(this.value)}};Fi.BLOCK_FOLDED="BLOCK_FOLDED";Fi.BLOCK_LITERAL="BLOCK_LITERAL";Fi.PLAIN="PLAIN";Fi.QUOTE_DOUBLE="QUOTE_DOUBLE";Fi.QUOTE_SINGLE="QUOTE_SINGLE";Ju.Scalar=Fi;Ju.isScalarValue=EE});var Da=x($m=>{"use strict";var PE=Ha(),$r=J(),jm=ye(),RE="tag:yaml.org,2002:";function xE(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 CE(e,t,i){if($r.isDocument(e)&&(e=e.contents),$r.isNode(e))return e;if($r.isPair(e)){let d=i.schema[$r.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 PE.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=RE+t.slice(2));let l=xE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new jm.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[$r.MAP]:Symbol.iterator in Object(e)?o[$r.SEQ]:o[$r.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 jm.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}$m.createNode=CE});var $s=x(js=>{"use strict";var AE=Da(),ti=J(),_E=Ts();function Gu(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 AE.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 Om=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Uu=class extends _E.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=>ti.isNode(r)||ti.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Om(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(ti.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Gu(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(ti.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&&ti.isScalar(a)?a.value:a:ti.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!ti.isPair(i))return!1;let r=i.value;return r==null||t&&ti.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 ti.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(ti.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Gu(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};js.Collection=Uu;js.collectionFromPath=Gu;js.isEmptyPath=Om});var Ma=x(Os=>{"use strict";var TE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ku(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var IE=(e,t,i)=>e.endsWith(` `)?Ku(i,t):i.includes(` `)?` -`+Ku(i,t):(e.endsWith(" ")?"":" ")+i;Os.indentComment=Ku;Os.lineComment=IE;Os.stringifyComment=TE});var Hm=x(Fa=>{"use strict";var jE="flow",Yu="block",Hs="quoted";function $E(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,N=-1;i===Yu&&(h=Om(e,h,t.length),h!==-1&&(d=h+c));for(let E;E=e[h+=1];){if(i===Hs&&E==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}N=h}if(E===` -`)i===Yu&&(h=Om(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(E===" "&&p&&p!==" "&&p!==` +`+Ku(i,t):(e.endsWith(" ")?"":" ")+i;Os.indentComment=Ku;Os.lineComment=IE;Os.stringifyComment=TE});var Dm=x(Fa=>{"use strict";var jE="flow",Yu="block",Hs="quoted";function $E(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,N=-1;i===Yu&&(h=Hm(e,h,t.length),h!==-1&&(d=h+c));for(let E;E=e[h+=1];){if(i===Hs&&E==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}N=h}if(E===` +`)i===Yu&&(h=Hm(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(E===" "&&p&&p!==" "&&p!==` `&&p!==" "){let S=e[h+1];S&&S!==" "&&S!==` `&&S!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Hs){for(;p===" "||p===" ";)p=E,E=e[h+=1],v=!0;let S=h>N+1?h-2:m-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+c,f=void 0}else v=!0}p=E}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let E=0;E{"use strict";var Mt=ye(),Li=Hm(),Ms=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Fs=e=>/^(%|---|\.\.\.)/m.test(e);function OE(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{"use strict";var Mt=ye(),Li=Dm(),Ms=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Fs=e=>/^(%|---|\.\.\.)/m.test(e);function OE(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;ar)return!0;if(o=a+1,n-o<=r)return!1}return!0}function La(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Fs(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'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(` `)?gn(a,t):Ds(e,t,i,r);if(!s&&!u&&n!==Mt.Scalar.PLAIN&&a.includes(` `))return Ds(e,t,i,r);if(Fs(a)){if(c==="")return t.forceBlockIndent=!0,Ds(e,t,i,r);if(s&&c===l)return gn(a,t)}let d=a.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return gn(a,t)}return s?d:Li.foldFlowLines(d,c,Li.FOLD_FLOW,Ms(t,!1))}function DE(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!==Mt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Mt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Mt.Scalar.BLOCK_FOLDED:case Mt.Scalar.BLOCK_LITERAL:return n||a?gn(o.value,t):Ds(o,t,i,r);case Mt.Scalar.QUOTE_DOUBLE:return La(o.value,t);case Mt.Scalar.QUOTE_SINGLE:return Xu(o.value,t);case Mt.Scalar.PLAIN:return HE(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Dm.stringifyString=DE});var qa=x(Zu=>{"use strict";var ME=_s(),Bi=J(),FE=Ma(),LE=Ba();function BE(e,t){let i=Object.assign({blockQuote:!0,commentString:FE.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 qE(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(Bi.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 VE(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Bi.isScalar(e)||Bi.isCollection(e))&&e.anchor;a&&ME.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 WE(e,t,i,r){if(Bi.isPair(e))return e.toString(t,i,r);if(Bi.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=Bi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=qE(t.doc.schema.tags,a));let o=VE(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):Bi.isScalar(a)?LE.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Bi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} -${t.indent}${s}`:s}Zu.createStringifyContext=BE;Zu.stringify=WE});var Bm=x(Lm=>{"use strict";var bi=J(),Mm=ye(),Fm=qa(),Va=Ma();function zE({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=bi.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(bi.isCollection(e)||!bi.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||bi.isCollection(e)||(bi.isScalar(e)?e.type===Mm.Scalar.BLOCK_FOLDED||e.type===Mm.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Fm.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Va.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Va.lineComment(m,i.indent,l(f))),m=`? ${m} -${s}:`):(m=`${m}:`,f&&(m+=Va.lineComment(m,i.indent,l(f))));let N,y,E;bi.isNode(t)?(N=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(N=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&bi.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&bi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Fm.stringify(t,i,()=>S=!0,()=>h=!0),b=" ";if(f||N||y){if(b=N?` +${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return gn(a,t)}return s?d:Li.foldFlowLines(d,c,Li.FOLD_FLOW,Ms(t,!1))}function DE(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!==Mt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Mt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Mt.Scalar.BLOCK_FOLDED:case Mt.Scalar.BLOCK_LITERAL:return n||a?gn(o.value,t):Ds(o,t,i,r);case Mt.Scalar.QUOTE_DOUBLE:return La(o.value,t);case Mt.Scalar.QUOTE_SINGLE:return Xu(o.value,t);case Mt.Scalar.PLAIN:return HE(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Mm.stringifyString=DE});var qa=x(Zu=>{"use strict";var ME=_s(),Bi=J(),FE=Ma(),LE=Ba();function BE(e,t){let i=Object.assign({blockQuote:!0,commentString:FE.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 qE(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(Bi.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 VE(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Bi.isScalar(e)||Bi.isCollection(e))&&e.anchor;a&&ME.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 WE(e,t,i,r){if(Bi.isPair(e))return e.toString(t,i,r);if(Bi.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=Bi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=qE(t.doc.schema.tags,a));let o=VE(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):Bi.isScalar(a)?LE.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Bi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} +${t.indent}${s}`:s}Zu.createStringifyContext=BE;Zu.stringify=WE});var qm=x(Bm=>{"use strict";var bi=J(),Fm=ye(),Lm=qa(),Va=Ma();function zE({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=bi.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(bi.isCollection(e)||!bi.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||bi.isCollection(e)||(bi.isScalar(e)?e.type===Fm.Scalar.BLOCK_FOLDED||e.type===Fm.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Lm.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Va.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Va.lineComment(m,i.indent,l(f))),m=`? ${m} +${s}:`):(m=`${m}:`,f&&(m+=Va.lineComment(m,i.indent,l(f))));let N,y,E;bi.isNode(t)?(N=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(N=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&bi.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&bi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Lm.stringify(t,i,()=>S=!0,()=>h=!0),b=" ";if(f||N||y){if(b=N?` `:"",y){let R=l(y);b+=` ${Va.indentComment(R,i.indent)}`}k===""&&!i.inFlow?b===` `&&E&&(b=` @@ -44,32 +44,32 @@ ${Va.indentComment(R,i.indent)}`}k===""&&!i.inFlow?b===` ${i.indent}`}else if(!p&&bi.isCollection(t)){let R=k[0],w=k.indexOf(` `),g=w!==-1,P=i.inFlow??t.flow??t.items.length===0;if(g||!P){let D=!1;if(g&&(R==="&"||R==="!")){let O=k.indexOf(" ");R==="&"&&O!==-1&&O{"use strict";var qm=Ps("process");function JE(e,...t){e==="debug"&&console.log(...t)}function GE(e,t){(e==="debug"||e==="warn")&&(typeof qm.emitWarning=="function"?qm.emitWarning(t):console.warn(t))}ed.debug=JE;ed.warn=GE});var Ws=x(Vs=>{"use strict";var qs=J(),Vm=ye(),Ls="<<",Bs={identify:e=>e===Ls||typeof e=="symbol"&&e.description===Ls,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Vm.Scalar(Symbol(Ls)),{addToJSMap:Wm}),stringify:()=>Ls},UE=(e,t)=>(Bs.identify(t)||qs.isScalar(t)&&(!t.type||t.type===Vm.Scalar.PLAIN)&&Bs.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Bs.tag&&i.default);function Wm(e,t,i){let r=zm(e,i);if(qs.isSeq(r))for(let n of r.items)id(e,t,n);else if(Array.isArray(r))for(let n of r)id(e,t,n);else id(e,t,r)}function id(e,t,i){let r=zm(e,i);if(!qs.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 zm(e,t){return e&&qs.isAlias(t)?t.resolve(e.doc,e):t}Vs.addMergeToJSMap=Wm;Vs.isMergeKey=UE;Vs.merge=Bs});var nd=x(Um=>{"use strict";var KE=td(),Jm=Ws(),YE=qa(),Gm=J(),rd=Mi();function XE(e,t,{key:i,value:r}){if(Gm.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Jm.isMergeKey(e,i))Jm.addMergeToJSMap(e,t,r);else{let n=rd.toJS(i,"",e);if(t instanceof Map)t.set(n,rd.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=QE(i,n,e),o=rd.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 QE(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Gm.isNode(e)&&i?.doc){let r=YE.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)+'..."'),KE.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)}Um.addPairToJSMap=XE});var qi=x(ad=>{"use strict";var Km=Da(),ZE=Bm(),eP=nd(),zs=J();function tP(e,t,i){let r=Km.createNode(e,void 0,i),n=Km.createNode(t,void 0,i);return new Js(r,n)}var Js=class e{constructor(t,i=null){Object.defineProperty(this,zs.NODE_TYPE,{value:zs.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return zs.isNode(i)&&(i=i.clone(t)),zs.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return eP.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?ZE.stringifyPair(this,t,i,r):JSON.stringify(this)}};ad.Pair=Js;ad.createPair=tP});var od=x(Xm=>{"use strict";var Or=J(),Ym=qa(),Gs=Ma();function iP(e,t,i){return(t.inFlow??e.flow?nP:rP)(e,t,i)}function rP({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}),d=!1,f=[];for(let v=0;vm=null,()=>d=!0);m&&(N+=Gs.lineComment(N,a,l(m))),d&&m&&(d=!1),f.push(r+N)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v{"use strict";var Vm=Ps("process");function JE(e,...t){e==="debug"&&console.log(...t)}function GE(e,t){(e==="debug"||e==="warn")&&(typeof Vm.emitWarning=="function"?Vm.emitWarning(t):console.warn(t))}ed.debug=JE;ed.warn=GE});var Ws=x(Vs=>{"use strict";var qs=J(),Wm=ye(),Ls="<<",Bs={identify:e=>e===Ls||typeof e=="symbol"&&e.description===Ls,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Wm.Scalar(Symbol(Ls)),{addToJSMap:zm}),stringify:()=>Ls},UE=(e,t)=>(Bs.identify(t)||qs.isScalar(t)&&(!t.type||t.type===Wm.Scalar.PLAIN)&&Bs.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Bs.tag&&i.default);function zm(e,t,i){let r=Jm(e,i);if(qs.isSeq(r))for(let n of r.items)id(e,t,n);else if(Array.isArray(r))for(let n of r)id(e,t,n);else id(e,t,r)}function id(e,t,i){let r=Jm(e,i);if(!qs.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 Jm(e,t){return e&&qs.isAlias(t)?t.resolve(e.doc,e):t}Vs.addMergeToJSMap=zm;Vs.isMergeKey=UE;Vs.merge=Bs});var nd=x(Km=>{"use strict";var KE=td(),Gm=Ws(),YE=qa(),Um=J(),rd=Mi();function XE(e,t,{key:i,value:r}){if(Um.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Gm.isMergeKey(e,i))Gm.addMergeToJSMap(e,t,r);else{let n=rd.toJS(i,"",e);if(t instanceof Map)t.set(n,rd.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=QE(i,n,e),o=rd.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 QE(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Um.isNode(e)&&i?.doc){let r=YE.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)+'..."'),KE.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)}Km.addPairToJSMap=XE});var qi=x(ad=>{"use strict";var Ym=Da(),ZE=qm(),eP=nd(),zs=J();function tP(e,t,i){let r=Ym.createNode(e,void 0,i),n=Ym.createNode(t,void 0,i);return new Js(r,n)}var Js=class e{constructor(t,i=null){Object.defineProperty(this,zs.NODE_TYPE,{value:zs.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return zs.isNode(i)&&(i=i.clone(t)),zs.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return eP.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?ZE.stringifyPair(this,t,i,r):JSON.stringify(this)}};ad.Pair=Js;ad.createPair=tP});var od=x(Qm=>{"use strict";var Or=J(),Xm=qa(),Gs=Ma();function iP(e,t,i){return(t.inFlow??e.flow?nP:rP)(e,t,i)}function rP({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}),d=!1,f=[];for(let v=0;vm=null,()=>d=!0);m&&(N+=Gs.lineComment(N,a,l(m))),d&&m&&(d=!1),f.push(r+N)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;vm=null);l||(l=d.length>u||N.includes(` +`+Gs.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function nP({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,d=[];for(let v=0;vm=null);l||(l=d.length>u||N.includes(` `)),v0&&(l||(l=d.reduce((y,E)=>y+E.length+2,2)+(N.length+2)>t.options.lineWidth)),l&&(N+=",")),m&&(N+=Gs.lineComment(N,r,s(m))),d.push(N),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?` ${a}${n}${h}`:` `;return`${v} -${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Us({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Gs.indentComment(t(r),e);i.push(a.trimStart())}}Xm.stringifyCollection=iP});var Wi=x(cd=>{"use strict";var aP=od(),oP=nd(),sP=$s(),Vi=J(),Ks=qi(),cP=ye();function Wa(e,t){let i=Vi.isScalar(t)?t.value:t;for(let r of e)if(Vi.isPair(r)&&(r.key===t||r.key===i||Vi.isScalar(r.key)&&r.key.value===i))return r}var sd=class extends sP.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Vi.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(Ks.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;Vi.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ks.Pair(t,t?.value):r=new Ks.Pair(t.key,t.value);let n=Wa(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Vi.isScalar(n.value)&&cP.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=Wa(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Wa(this.items,t)?.value;return(!i&&Vi.isScalar(n)?n.value:n)??void 0}has(t){return!!Wa(this.items,t)}set(t,i){this.add(new Ks.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)oP.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Vi.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})),aP.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};cd.YAMLMap=sd;cd.findPair=Wa});var wn=x(Zm=>{"use strict";var lP=J(),Qm=Wi(),uP={collection:"map",default:!0,nodeClass:Qm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return lP.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Qm.YAMLMap.from(e,t,i)};Zm.map=uP});var zi=x(ev=>{"use strict";var dP=Da(),fP=od(),hP=$s(),Xs=J(),pP=ye(),mP=Mi(),ld=class extends hP.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Xs.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ys(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Ys(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Xs.isScalar(n)?n.value:n}has(t){let i=Ys(t);return typeof i=="number"&&i=0?t:null}ev.YAMLSeq=ld});var yn=x(iv=>{"use strict";var vP=J(),tv=zi(),gP={collection:"seq",default:!0,nodeClass:tv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return vP.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>tv.YAMLSeq.from(e,t,i)};iv.seq=gP});var za=x(rv=>{"use strict";var wP=Ba(),yP={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),wP.stringifyString(e,t,i,r)}};rv.string=yP});var Qs=x(ov=>{"use strict";var nv=ye(),av={identify:e=>e==null,createNode:()=>new nv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new nv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&av.test.test(e)?e:t.options.nullStr};ov.nullTag=av});var ud=x(cv=>{"use strict";var NP=ye(),sv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new NP.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&sv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};cv.boolTag=sv});var Nn=x(lv=>{"use strict";function bP({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}lv.stringifyNumber=bP});var fd=x(Zs=>{"use strict";var kP=ye(),dd=Nn(),SP={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:dd.stringifyNumber},EP={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():dd.stringifyNumber(e)}},PP={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 kP.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:dd.stringifyNumber};Zs.float=PP;Zs.floatExp=EP;Zs.floatNaN=SP});var pd=x(tc=>{"use strict";var uv=Nn(),ec=e=>typeof e=="bigint"||Number.isInteger(e),hd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function dv(e,t,i){let{value:r}=e;return ec(r)&&r>=0?i+r.toString(t):uv.stringifyNumber(e)}var RP={identify:e=>ec(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>hd(e,2,8,i),stringify:e=>dv(e,8,"0o")},xP={identify:ec,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>hd(e,0,10,i),stringify:uv.stringifyNumber},CP={identify:e=>ec(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>hd(e,2,16,i),stringify:e=>dv(e,16,"0x")};tc.int=xP;tc.intHex=CP;tc.intOct=RP});var hv=x(fv=>{"use strict";var AP=wn(),_P=Qs(),TP=yn(),IP=za(),jP=ud(),md=fd(),vd=pd(),$P=[AP.map,TP.seq,IP.string,_P.nullTag,jP.boolTag,vd.intOct,vd.int,vd.intHex,md.floatNaN,md.floatExp,md.float];fv.schema=$P});var vv=x(mv=>{"use strict";var OP=ye(),HP=wn(),DP=yn();function pv(e){return typeof e=="bigint"||Number.isInteger(e)}var ic=({value:e})=>JSON.stringify(e),MP=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ic},{identify:e=>e==null,createNode:()=>new OP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ic},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ic},{identify:pv,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})=>pv(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:ic}],FP={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},LP=[HP.map,DP.seq].concat(MP,FP);mv.schema=LP});var wd=x(gv=>{"use strict";var Ja=Ps("buffer"),gd=ye(),BP=Ba(),qP={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ja.Buffer=="function")return Ja.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{"use strict";var rc=J(),yd=qi(),VP=ye(),WP=zi();function wv(e,t){if(rc.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new yd.Pair(new VP.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} +${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Us({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Gs.indentComment(t(r),e);i.push(a.trimStart())}}Qm.stringifyCollection=iP});var Wi=x(cd=>{"use strict";var aP=od(),oP=nd(),sP=$s(),Vi=J(),Ks=qi(),cP=ye();function Wa(e,t){let i=Vi.isScalar(t)?t.value:t;for(let r of e)if(Vi.isPair(r)&&(r.key===t||r.key===i||Vi.isScalar(r.key)&&r.key.value===i))return r}var sd=class extends sP.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Vi.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(Ks.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;Vi.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ks.Pair(t,t?.value):r=new Ks.Pair(t.key,t.value);let n=Wa(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Vi.isScalar(n.value)&&cP.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=Wa(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Wa(this.items,t)?.value;return(!i&&Vi.isScalar(n)?n.value:n)??void 0}has(t){return!!Wa(this.items,t)}set(t,i){this.add(new Ks.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)oP.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Vi.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})),aP.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};cd.YAMLMap=sd;cd.findPair=Wa});var wn=x(ev=>{"use strict";var lP=J(),Zm=Wi(),uP={collection:"map",default:!0,nodeClass:Zm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return lP.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Zm.YAMLMap.from(e,t,i)};ev.map=uP});var zi=x(tv=>{"use strict";var dP=Da(),fP=od(),hP=$s(),Xs=J(),pP=ye(),mP=Mi(),ld=class extends hP.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Xs.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ys(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Ys(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Xs.isScalar(n)?n.value:n}has(t){let i=Ys(t);return typeof i=="number"&&i=0?t:null}tv.YAMLSeq=ld});var yn=x(rv=>{"use strict";var vP=J(),iv=zi(),gP={collection:"seq",default:!0,nodeClass:iv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return vP.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>iv.YAMLSeq.from(e,t,i)};rv.seq=gP});var za=x(nv=>{"use strict";var wP=Ba(),yP={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),wP.stringifyString(e,t,i,r)}};nv.string=yP});var Qs=x(sv=>{"use strict";var av=ye(),ov={identify:e=>e==null,createNode:()=>new av.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new av.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&ov.test.test(e)?e:t.options.nullStr};sv.nullTag=ov});var ud=x(lv=>{"use strict";var NP=ye(),cv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new NP.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&cv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};lv.boolTag=cv});var Nn=x(uv=>{"use strict";function bP({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}uv.stringifyNumber=bP});var fd=x(Zs=>{"use strict";var kP=ye(),dd=Nn(),SP={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:dd.stringifyNumber},EP={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():dd.stringifyNumber(e)}},PP={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 kP.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:dd.stringifyNumber};Zs.float=PP;Zs.floatExp=EP;Zs.floatNaN=SP});var pd=x(tc=>{"use strict";var dv=Nn(),ec=e=>typeof e=="bigint"||Number.isInteger(e),hd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function fv(e,t,i){let{value:r}=e;return ec(r)&&r>=0?i+r.toString(t):dv.stringifyNumber(e)}var RP={identify:e=>ec(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>hd(e,2,8,i),stringify:e=>fv(e,8,"0o")},xP={identify:ec,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>hd(e,0,10,i),stringify:dv.stringifyNumber},CP={identify:e=>ec(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>hd(e,2,16,i),stringify:e=>fv(e,16,"0x")};tc.int=xP;tc.intHex=CP;tc.intOct=RP});var pv=x(hv=>{"use strict";var AP=wn(),_P=Qs(),TP=yn(),IP=za(),jP=ud(),md=fd(),vd=pd(),$P=[AP.map,TP.seq,IP.string,_P.nullTag,jP.boolTag,vd.intOct,vd.int,vd.intHex,md.floatNaN,md.floatExp,md.float];hv.schema=$P});var gv=x(vv=>{"use strict";var OP=ye(),HP=wn(),DP=yn();function mv(e){return typeof e=="bigint"||Number.isInteger(e)}var ic=({value:e})=>JSON.stringify(e),MP=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ic},{identify:e=>e==null,createNode:()=>new OP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ic},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ic},{identify:mv,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})=>mv(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:ic}],FP={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},LP=[HP.map,DP.seq].concat(MP,FP);vv.schema=LP});var wd=x(wv=>{"use strict";var Ja=Ps("buffer"),gd=ye(),BP=Ba(),qP={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ja.Buffer=="function")return Ja.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{"use strict";var rc=J(),yd=qi(),VP=ye(),WP=zi();function yv(e,t){if(rc.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new yd.Pair(new VP.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment} -${a.comment}`:r.comment}r=n}e.items[i]=rc.isPair(r)?r:new yd.Pair(r)}}else t("Expected a sequence for this tag");return e}function yv(e,t,i){let{replacer:r}=i,n=new WP.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(yd.createPair(s,c,i))}return n}var zP={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:wv,createNode:yv};nc.createPairs=yv;nc.pairs=zP;nc.resolvePairs=wv});var kd=x(bd=>{"use strict";var Nv=J(),Nd=Mi(),Ga=Wi(),JP=zi(),bv=ac(),Hr=class e extends JP.YAMLSeq{constructor(){super(),this.add=Ga.YAMLMap.prototype.add.bind(this),this.delete=Ga.YAMLMap.prototype.delete.bind(this),this.get=Ga.YAMLMap.prototype.get.bind(this),this.has=Ga.YAMLMap.prototype.has.bind(this),this.set=Ga.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(Nv.isPair(n)?(a=Nd.toJS(n.key,"",i),o=Nd.toJS(n.value,a,i)):a=Nd.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=bv.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Hr.tag="tag:yaml.org,2002:omap";var GP={collection:"seq",identify:e=>e instanceof Map,nodeClass:Hr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=bv.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Nv.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Hr,i)},createNode:(e,t,i)=>Hr.from(e,t,i)};bd.YAMLOMap=Hr;bd.omap=GP});var Rv=x(Sd=>{"use strict";var kv=ye();function Sv({value:e,source:t},i){return t&&(e?Ev:Pv).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Ev={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 kv.Scalar(!0),stringify:Sv},Pv={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 kv.Scalar(!1),stringify:Sv};Sd.falseTag=Pv;Sd.trueTag=Ev});var xv=x(oc=>{"use strict";var UP=ye(),Ed=Nn(),KP={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:Ed.stringifyNumber},YP={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():Ed.stringifyNumber(e)}},XP={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 UP.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:Ed.stringifyNumber};oc.float=XP;oc.floatExp=YP;oc.floatNaN=KP});var Av=x(Ka=>{"use strict";var Cv=Nn(),Ua=e=>typeof e=="bigint"||Number.isInteger(e);function sc(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 Pd(e,t,i){let{value:r}=e;if(Ua(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Cv.stringifyNumber(e)}var QP={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>sc(e,2,2,i),stringify:e=>Pd(e,2,"0b")},ZP={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>sc(e,1,8,i),stringify:e=>Pd(e,8,"0")},eR={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>sc(e,0,10,i),stringify:Cv.stringifyNumber},tR={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>sc(e,2,16,i),stringify:e=>Pd(e,16,"0x")};Ka.int=eR;Ka.intBin=QP;Ka.intHex=tR;Ka.intOct=ZP});var xd=x(Rd=>{"use strict";var uc=J(),cc=qi(),lc=Wi(),Dr=class e extends lc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;uc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new cc.Pair(t.key,null):i=new cc.Pair(t,null),lc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=lc.findPair(this.items,t);return!i&&uc.isPair(r)?uc.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=lc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new cc.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(cc.createPair(o,null,r));return a}};Dr.tag="tag:yaml.org,2002:set";var iR={collection:"map",identify:e=>e instanceof Set,nodeClass:Dr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Dr.from(e,t,i),resolve(e,t){if(uc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Dr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Rd.YAMLSet=Dr;Rd.set=iR});var Ad=x(dc=>{"use strict";var rR=Nn();function Cd(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 _v(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return rR.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 nR={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})=>Cd(e,i),stringify:_v},aR={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=>Cd(e,!1),stringify:_v},Tv={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(Tv.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 d=Cd(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};dc.floatTime=aR;dc.intTime=nR;dc.timestamp=Tv});var $v=x(jv=>{"use strict";var oR=wn(),sR=Qs(),cR=yn(),lR=za(),uR=wd(),Iv=Rv(),_d=xv(),fc=Av(),dR=Ws(),fR=kd(),hR=ac(),pR=xd(),Td=Ad(),mR=[oR.map,cR.seq,lR.string,sR.nullTag,Iv.trueTag,Iv.falseTag,fc.intBin,fc.intOct,fc.int,fc.intHex,_d.floatNaN,_d.floatExp,_d.float,uR.binary,dR.merge,fR.omap,hR.pairs,pR.set,Td.intTime,Td.floatTime,Td.timestamp];jv.schema=mR});var Wv=x($d=>{"use strict";var Mv=wn(),vR=Qs(),Fv=yn(),gR=za(),wR=ud(),Id=fd(),jd=pd(),yR=hv(),NR=vv(),Lv=wd(),Ya=Ws(),Bv=kd(),qv=ac(),Ov=$v(),Vv=xd(),hc=Ad(),Hv=new Map([["core",yR.schema],["failsafe",[Mv.map,Fv.seq,gR.string]],["json",NR.schema],["yaml11",Ov.schema],["yaml-1.1",Ov.schema]]),Dv={binary:Lv.binary,bool:wR.boolTag,float:Id.float,floatExp:Id.floatExp,floatNaN:Id.floatNaN,floatTime:hc.floatTime,int:jd.int,intHex:jd.intHex,intOct:jd.intOct,intTime:hc.intTime,map:Mv.map,merge:Ya.merge,null:vR.nullTag,omap:Bv.omap,pairs:qv.pairs,seq:Fv.seq,set:Vv.set,timestamp:hc.timestamp},bR={"tag:yaml.org,2002:binary":Lv.binary,"tag:yaml.org,2002:merge":Ya.merge,"tag:yaml.org,2002:omap":Bv.omap,"tag:yaml.org,2002:pairs":qv.pairs,"tag:yaml.org,2002:set":Vv.set,"tag:yaml.org,2002:timestamp":hc.timestamp};function kR(e,t,i){let r=Hv.get(t);if(r&&!e)return i&&!r.includes(Ya.merge)?r.concat(Ya.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Hv.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(Ya.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Dv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Dv).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}$d.coreKnownTags=bR;$d.getTags=kR});var Dd=x(zv=>{"use strict";var Od=J(),SR=wn(),ER=yn(),PR=za(),pc=Wv(),RR=(e,t)=>e.keyt.key?1:0,Hd=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?pc.getTags(t,"compat"):t?pc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?pc.coreKnownTags:{},this.tags=pc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Od.MAP,{value:SR.map}),Object.defineProperty(this,Od.SCALAR,{value:PR.string}),Object.defineProperty(this,Od.SEQ,{value:ER.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?RR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};zv.Schema=Hd});var Gv=x(Jv=>{"use strict";var xR=J(),Md=qa(),Xa=Ma();function CR(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=Md.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Xa.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(xR.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Xa.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Md.stringify(e.contents,n,()=>s=null,c);s&&(l+=Xa.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Md.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` +${a.comment}`:r.comment}r=n}e.items[i]=rc.isPair(r)?r:new yd.Pair(r)}}else t("Expected a sequence for this tag");return e}function Nv(e,t,i){let{replacer:r}=i,n=new WP.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(yd.createPair(s,c,i))}return n}var zP={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yv,createNode:Nv};nc.createPairs=Nv;nc.pairs=zP;nc.resolvePairs=yv});var kd=x(bd=>{"use strict";var bv=J(),Nd=Mi(),Ga=Wi(),JP=zi(),kv=ac(),Hr=class e extends JP.YAMLSeq{constructor(){super(),this.add=Ga.YAMLMap.prototype.add.bind(this),this.delete=Ga.YAMLMap.prototype.delete.bind(this),this.get=Ga.YAMLMap.prototype.get.bind(this),this.has=Ga.YAMLMap.prototype.has.bind(this),this.set=Ga.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(bv.isPair(n)?(a=Nd.toJS(n.key,"",i),o=Nd.toJS(n.value,a,i)):a=Nd.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=kv.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Hr.tag="tag:yaml.org,2002:omap";var GP={collection:"seq",identify:e=>e instanceof Map,nodeClass:Hr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=kv.resolvePairs(e,t),r=[];for(let{key:n}of i.items)bv.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Hr,i)},createNode:(e,t,i)=>Hr.from(e,t,i)};bd.YAMLOMap=Hr;bd.omap=GP});var xv=x(Sd=>{"use strict";var Sv=ye();function Ev({value:e,source:t},i){return t&&(e?Pv:Rv).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Pv={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 Sv.Scalar(!0),stringify:Ev},Rv={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 Sv.Scalar(!1),stringify:Ev};Sd.falseTag=Rv;Sd.trueTag=Pv});var Cv=x(oc=>{"use strict";var UP=ye(),Ed=Nn(),KP={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:Ed.stringifyNumber},YP={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():Ed.stringifyNumber(e)}},XP={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 UP.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:Ed.stringifyNumber};oc.float=XP;oc.floatExp=YP;oc.floatNaN=KP});var _v=x(Ka=>{"use strict";var Av=Nn(),Ua=e=>typeof e=="bigint"||Number.isInteger(e);function sc(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 Pd(e,t,i){let{value:r}=e;if(Ua(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Av.stringifyNumber(e)}var QP={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>sc(e,2,2,i),stringify:e=>Pd(e,2,"0b")},ZP={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>sc(e,1,8,i),stringify:e=>Pd(e,8,"0")},eR={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>sc(e,0,10,i),stringify:Av.stringifyNumber},tR={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>sc(e,2,16,i),stringify:e=>Pd(e,16,"0x")};Ka.int=eR;Ka.intBin=QP;Ka.intHex=tR;Ka.intOct=ZP});var xd=x(Rd=>{"use strict";var uc=J(),cc=qi(),lc=Wi(),Dr=class e extends lc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;uc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new cc.Pair(t.key,null):i=new cc.Pair(t,null),lc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=lc.findPair(this.items,t);return!i&&uc.isPair(r)?uc.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=lc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new cc.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(cc.createPair(o,null,r));return a}};Dr.tag="tag:yaml.org,2002:set";var iR={collection:"map",identify:e=>e instanceof Set,nodeClass:Dr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Dr.from(e,t,i),resolve(e,t){if(uc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Dr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Rd.YAMLSet=Dr;Rd.set=iR});var Ad=x(dc=>{"use strict";var rR=Nn();function Cd(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 Tv(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return rR.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 nR={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})=>Cd(e,i),stringify:Tv},aR={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=>Cd(e,!1),stringify:Tv},Iv={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(Iv.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 d=Cd(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};dc.floatTime=aR;dc.intTime=nR;dc.timestamp=Iv});var Ov=x($v=>{"use strict";var oR=wn(),sR=Qs(),cR=yn(),lR=za(),uR=wd(),jv=xv(),_d=Cv(),fc=_v(),dR=Ws(),fR=kd(),hR=ac(),pR=xd(),Td=Ad(),mR=[oR.map,cR.seq,lR.string,sR.nullTag,jv.trueTag,jv.falseTag,fc.intBin,fc.intOct,fc.int,fc.intHex,_d.floatNaN,_d.floatExp,_d.float,uR.binary,dR.merge,fR.omap,hR.pairs,pR.set,Td.intTime,Td.floatTime,Td.timestamp];$v.schema=mR});var zv=x($d=>{"use strict";var Fv=wn(),vR=Qs(),Lv=yn(),gR=za(),wR=ud(),Id=fd(),jd=pd(),yR=pv(),NR=gv(),Bv=wd(),Ya=Ws(),qv=kd(),Vv=ac(),Hv=Ov(),Wv=xd(),hc=Ad(),Dv=new Map([["core",yR.schema],["failsafe",[Fv.map,Lv.seq,gR.string]],["json",NR.schema],["yaml11",Hv.schema],["yaml-1.1",Hv.schema]]),Mv={binary:Bv.binary,bool:wR.boolTag,float:Id.float,floatExp:Id.floatExp,floatNaN:Id.floatNaN,floatTime:hc.floatTime,int:jd.int,intHex:jd.intHex,intOct:jd.intOct,intTime:hc.intTime,map:Fv.map,merge:Ya.merge,null:vR.nullTag,omap:qv.omap,pairs:Vv.pairs,seq:Lv.seq,set:Wv.set,timestamp:hc.timestamp},bR={"tag:yaml.org,2002:binary":Bv.binary,"tag:yaml.org,2002:merge":Ya.merge,"tag:yaml.org,2002:omap":qv.omap,"tag:yaml.org,2002:pairs":Vv.pairs,"tag:yaml.org,2002:set":Wv.set,"tag:yaml.org,2002:timestamp":hc.timestamp};function kR(e,t,i){let r=Dv.get(t);if(r&&!e)return i&&!r.includes(Ya.merge)?r.concat(Ya.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Dv.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(Ya.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Mv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Mv).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},[])}$d.coreKnownTags=bR;$d.getTags=kR});var Dd=x(Jv=>{"use strict";var Od=J(),SR=wn(),ER=yn(),PR=za(),pc=zv(),RR=(e,t)=>e.keyt.key?1:0,Hd=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?pc.getTags(t,"compat"):t?pc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?pc.coreKnownTags:{},this.tags=pc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Od.MAP,{value:SR.map}),Object.defineProperty(this,Od.SCALAR,{value:PR.string}),Object.defineProperty(this,Od.SEQ,{value:ER.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?RR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Jv.Schema=Hd});var Uv=x(Gv=>{"use strict";var xR=J(),Md=qa(),Xa=Ma();function CR(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=Md.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Xa.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(xR.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Xa.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Md.stringify(e.contents,n,()=>s=null,c);s&&(l+=Xa.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Md.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` `)?(i.push("..."),i.push(Xa.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(Xa.indentComment(a(c),"")))}return i.join(` `)+` -`}Jv.stringifyDocument=CR});var Qa=x(Uv=>{"use strict";var AR=Ha(),bn=$s(),kt=J(),_R=qi(),TR=Mi(),IR=Dd(),jR=Gv(),Fd=_s(),$R=Vu(),OR=Da(),Ld=qu(),Bd=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,kt.NODE_TYPE,{value:kt.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 Ld.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,{[kt.NODE_TYPE]:{value:kt.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=kt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){kn(this.contents)&&this.contents.add(t)}addIn(t,i){kn(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Fd.anchorNames(this);t.anchor=!i||r.has(i)?Fd.findNewAnchor(i||"a",r):i}return new AR.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=y=>typeof y=="number"||y instanceof String||y instanceof Number,N=i.filter(m).map(String);N.length>0&&(i=i.concat(N)),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:d,setAnchors:f,sourceObjects:p}=Fd.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=OR.createNode(t,u,v);return s&&kt.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new _R.Pair(n,a)}delete(t){return kn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return bn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):kn(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return kt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return bn.isEmptyPath(t)?!i&&kt.isScalar(this.contents)?this.contents.value:this.contents:kt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return kt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return bn.isEmptyPath(t)?this.contents!==void 0:kt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=bn.collectionFromPath(this.schema,[t],i):kn(this.contents)&&this.contents.set(t,i)}setIn(t,i){bn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=bn.collectionFromPath(this.schema,Array.from(t),i):kn(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 Ld.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 Ld.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 IR.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=TR.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"?$R.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 jR.stringifyDocument(this,t)}};function kn(e){if(kt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Uv.Document=Bd});var to=x(eo=>{"use strict";var Za=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},qd=class extends Za{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Vd=class extends Za{constructor(t,i,r){super("YAMLWarning",t,i,r)}},HR=(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)+`… +`}Gv.stringifyDocument=CR});var Qa=x(Kv=>{"use strict";var AR=Ha(),bn=$s(),kt=J(),_R=qi(),TR=Mi(),IR=Dd(),jR=Uv(),Fd=_s(),$R=Vu(),OR=Da(),Ld=qu(),Bd=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,kt.NODE_TYPE,{value:kt.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 Ld.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,{[kt.NODE_TYPE]:{value:kt.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=kt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){kn(this.contents)&&this.contents.add(t)}addIn(t,i){kn(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Fd.anchorNames(this);t.anchor=!i||r.has(i)?Fd.findNewAnchor(i||"a",r):i}return new AR.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=y=>typeof y=="number"||y instanceof String||y instanceof Number,N=i.filter(m).map(String);N.length>0&&(i=i.concat(N)),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:d,setAnchors:f,sourceObjects:p}=Fd.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=OR.createNode(t,u,v);return s&&kt.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new _R.Pair(n,a)}delete(t){return kn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return bn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):kn(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return kt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return bn.isEmptyPath(t)?!i&&kt.isScalar(this.contents)?this.contents.value:this.contents:kt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return kt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return bn.isEmptyPath(t)?this.contents!==void 0:kt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=bn.collectionFromPath(this.schema,[t],i):kn(this.contents)&&this.contents.set(t,i)}setIn(t,i){bn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=bn.collectionFromPath(this.schema,Array.from(t),i):kn(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 Ld.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 Ld.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 IR.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=TR.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"?$R.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 jR.stringifyDocument(this,t)}};function kn(e){if(kt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Kv.Document=Bd});var to=x(eo=>{"use strict";var Za=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},qd=class extends Za{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Vd=class extends Za{constructor(t,i,r){super("YAMLWarning",t,i,r)}},HR=(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)+`… `),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+=`: ${o} ${l} -`}};eo.YAMLError=Za;eo.YAMLParseError=qd;eo.YAMLWarning=Vd;eo.prettifyError=HR});var io=x(Kv=>{"use strict";function DR(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,N=null,y=null,E=null,S=null,k=null;for(let w of e)switch(v&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&a(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(h=w),u=!0;break;case"comment":{u||a(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let g=w.source.substring(1)||" ";d?d+=f+g:d=g,f="",l=!1;break}case"newline":l?d?d+=w.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,p=!0,(m||N)&&(y=w),u=!0;break;case"anchor":m&&a(w,"MULTIPLE_ANCHORS","A node can have at most one anchor"),w.source.endsWith(":")&&a(w.offset+w.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=w,k??(k=w.offset),l=!1,u=!1,v=!0;break;case"tag":{N&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),N=w,k??(k=w.offset),l=!1,u=!1,v=!0;break}case i:(m||N)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),S&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),S=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){E&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let b=e[e.length-1],R=b?b.offset+b.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:E,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:N,newlineAfterProp:y,end:R,start:k??R}}Kv.resolveProps=DR});var mc=x(Yv=>{"use strict";function Wd(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` -`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Wd(t.key)||Wd(t.value))return!0}return!1;default:return!0}}Yv.containsNewline=Wd});var zd=x(Xv=>{"use strict";var MR=mc();function FR(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&MR.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Xv.flowIndentCheck=FR});var Jd=x(Zv=>{"use strict";var Qv=J();function LR(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Qv.isScalar(a)&&Qv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Zv.mapIncludes=LR});var ag=x(ng=>{"use strict";var eg=qi(),BR=Wi(),tg=io(),qR=mc(),ig=zd(),VR=Jd(),rg="All mapping items must start at the same column";function WR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??BR.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:d,key:f,sep:p,value:v}=u,h=tg.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",rg)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` -`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||qR.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",rg);i.atKey=!0;let N=h.end,y=f?e(i,f,h,n):t(i,N,d,null,h,n);i.schema.compat&&ig.flowIndentCheck(r.indent,f,n),i.atKey=!1,VR.mapIncludes(i,s.items,y)&&n(N,"DUPLICATE_KEY","Map keys must be unique");let E=tg.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=E.end,E.found){m&&(v?.type==="block-map"&&!E.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var zR=zi(),JR=io(),GR=zd();function UR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??zR.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:d}of r.items){let f=JR.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&GR.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}og.resolveBlockSeq=UR});var Sn=x(cg=>{"use strict";function KR(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}}cg.resolveEnd=KR});var fg=x(dg=>{"use strict";var YR=J(),XR=qi(),lg=Wi(),QR=zi(),ZR=Sn(),ug=io(),ex=mc(),tx=Jd(),Gd="Block collections are not allowed within flow collections",Ud=e=>e&&(e.type==="block-map"||e.type==="block-seq");function ix({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?lg.YAMLMap:QR.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m{"use strict";function DR(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,N=null,y=null,E=null,S=null,k=null;for(let w of e)switch(v&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&a(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(h=w),u=!0;break;case"comment":{u||a(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let g=w.source.substring(1)||" ";d?d+=f+g:d=g,f="",l=!1;break}case"newline":l?d?d+=w.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,p=!0,(m||N)&&(y=w),u=!0;break;case"anchor":m&&a(w,"MULTIPLE_ANCHORS","A node can have at most one anchor"),w.source.endsWith(":")&&a(w.offset+w.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=w,k??(k=w.offset),l=!1,u=!1,v=!0;break;case"tag":{N&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),N=w,k??(k=w.offset),l=!1,u=!1,v=!0;break}case i:(m||N)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),S&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),S=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){E&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let b=e[e.length-1],R=b?b.offset+b.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:E,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:N,newlineAfterProp:y,end:R,start:k??R}}Yv.resolveProps=DR});var mc=x(Xv=>{"use strict";function Wd(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` +`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Wd(t.key)||Wd(t.value))return!0}return!1;default:return!0}}Xv.containsNewline=Wd});var zd=x(Qv=>{"use strict";var MR=mc();function FR(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&MR.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Qv.flowIndentCheck=FR});var Jd=x(eg=>{"use strict";var Zv=J();function LR(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Zv.isScalar(a)&&Zv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}eg.mapIncludes=LR});var og=x(ag=>{"use strict";var tg=qi(),BR=Wi(),ig=io(),qR=mc(),rg=zd(),VR=Jd(),ng="All mapping items must start at the same column";function WR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??BR.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:d,key:f,sep:p,value:v}=u,h=ig.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",ng)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` +`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||qR.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",ng);i.atKey=!0;let N=h.end,y=f?e(i,f,h,n):t(i,N,d,null,h,n);i.schema.compat&&rg.flowIndentCheck(r.indent,f,n),i.atKey=!1,VR.mapIncludes(i,s.items,y)&&n(N,"DUPLICATE_KEY","Map keys must be unique");let E=ig.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=E.end,E.found){m&&(v?.type==="block-map"&&!E.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var zR=zi(),JR=io(),GR=zd();function UR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??zR.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:d}of r.items){let f=JR.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&GR.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}sg.resolveBlockSeq=UR});var Sn=x(lg=>{"use strict";function KR(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}}lg.resolveEnd=KR});var hg=x(fg=>{"use strict";var YR=J(),XR=qi(),ug=Wi(),QR=zi(),ZR=Sn(),dg=io(),ex=mc(),tx=Jd(),Gd="Block collections are not allowed within flow collections",Ud=e=>e&&(e.type==="block-map"||e.type==="block-seq");function ix({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?ug.YAMLMap:QR.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m0){let m=ZR.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=` -`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}dg.resolveFlowCollection=ix});var pg=x(hg=>{"use strict";var rx=J(),nx=ye(),ax=Wi(),ox=zi(),sx=ag(),cx=sg(),lx=fg();function Kd(e,t,i,r,n,a){let o=i.type==="block-map"?sx.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?cx.resolveBlockSeq(e,t,i,r,a):lx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function ux(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offsetf.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Kd(e,t,i,n,o)}let l=Kd(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=rx.isNode(u)?u:new nx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}hg.composeCollection=ux});var Xd=x(mg=>{"use strict";var Yd=ye();function dx(e,t,i){let r=t.offset,n=fx(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Yd.Scalar.BLOCK_FOLDED:Yd.Scalar.BLOCK_LITERAL,o=t.source?hx(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` +`+R:w.comment=R,b.comment=b.comment.substring(R.length+1)}}if(!o&&!S&&!b.found){let R=k?e(i,k,b,n):t(i,b.end,S,null,b,n);l.items.push(R),d=R.range[2],Ud(k)&&n(R.range,"BLOCK_IN_FLOW",Gd)}else{i.atKey=!0;let R=b.end,w=E?e(i,E,b,n):t(i,R,y,null,b,n);Ud(E)&&n(w.range,"BLOCK_IN_FLOW",Gd),i.atKey=!1;let g=dg.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:k,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(g.found){if(!o&&!b.found&&i.options.strict){if(S)for(let O of S){if(O===g.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start0){let m=ZR.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=` +`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}fg.resolveFlowCollection=ix});var mg=x(pg=>{"use strict";var rx=J(),nx=ye(),ax=Wi(),ox=zi(),sx=og(),cx=cg(),lx=hg();function Kd(e,t,i,r,n,a){let o=i.type==="block-map"?sx.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?cx.resolveBlockSeq(e,t,i,r,a):lx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function ux(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offsetf.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Kd(e,t,i,n,o)}let l=Kd(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=rx.isNode(u)?u:new nx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}pg.composeCollection=ux});var Xd=x(vg=>{"use strict";var Yd=ye();function dx(e,t,i){let r=t.offset,n=fx(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Yd.Scalar.BLOCK_FOLDED:Yd.Scalar.BLOCK_LITERAL,o=t.source?hx(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;hc&&(c=m.length);else{m.length=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;hc||N[0]===" "?(f===" "?f=` @@ -84,7 +84,7 @@ ${l} `+o[h][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function fx({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f{"use strict";var Qd=ye(),px=Sn();function mx(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=Qd.Scalar.PLAIN,c=vx(a,l);break;case"single-quoted-scalar":s=Qd.Scalar.QUOTE_SINGLE,c=gx(a,l);break;case"double-quoted-scalar":s=Qd.Scalar.QUOTE_DOUBLE,c=wx(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=px.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function vx(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),vg(e)}function gx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),vg(e.slice(1,-1)).replace(/''/g,"'")}function vg(e){let t,i;try{t=new RegExp(`(.*?)(?{"use strict";var Qd=ye(),px=Sn();function mx(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=Qd.Scalar.PLAIN,c=vx(a,l);break;case"single-quoted-scalar":s=Qd.Scalar.QUOTE_SINGLE,c=gx(a,l);break;case"double-quoted-scalar":s=Qd.Scalar.QUOTE_DOUBLE,c=wx(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=px.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function vx(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),gg(e)}function gx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),gg(e.slice(1,-1)).replace(/''/g,"'")}function gg(e){let t,i;try{t=new RegExp(`(.*?)(?{"use strict";var Mr=J(),wg=ye(),kx=Xd(),Sx=Zd();function Ex(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?kx.resolveBlockScalar(e,t,r):Sx.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Mr.SCALAR]:c?l=Px(e.schema,n,c,i,r):t.type==="scalar"?l=Rx(e,n,t,r):l=e.schema[Mr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Mr.isScalar(d)?d:new wg.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new wg.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 Px(e,t,i,r,n){if(i==="!")return e[Mr.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[Mr.SCALAR])}function Rx({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[Mr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Mr.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}yg.composeScalar=Ex});var kg=x(bg=>{"use strict";function xx(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}bg.emptyScalarPosition=xx});var Pg=x(tf=>{"use strict";var Cx=Ha(),Ax=J(),_x=pg(),Sg=Ng(),Tx=Sn(),Ix=kg(),jx={composeNode:Eg,composeEmptyNode:ef};function Eg(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=$x(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=Sg.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=_x.composeCollection(jx,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=ef(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&&(!Ax.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 ef(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Ix.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Sg.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function $x({options:e},{offset:t,source:i,end:r},n){let a=new Cx.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=Tx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}tf.composeEmptyNode=ef;tf.composeNode=Eg});var Cg=x(xg=>{"use strict";var Ox=Qa(),Rg=Pg(),Hx=Sn(),Dx=io();function Mx(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Ox.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Dx.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?Rg.composeNode(l,n,u,o):Rg.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Hx.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}xg.composeDoc=Mx});var nf=x(Tg=>{"use strict";var Fx=Ps("process"),Lx=qu(),Bx=Qa(),ro=to(),Ag=J(),qx=Cg(),Vx=Sn();function no(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 _g(e){let t="",i=!1,r=!1;for(let n=0;n{"use strict";var Mr=J(),yg=ye(),kx=Xd(),Sx=Zd();function Ex(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?kx.resolveBlockScalar(e,t,r):Sx.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Mr.SCALAR]:c?l=Px(e.schema,n,c,i,r):t.type==="scalar"?l=Rx(e,n,t,r):l=e.schema[Mr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Mr.isScalar(d)?d:new yg.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new yg.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 Px(e,t,i,r,n){if(i==="!")return e[Mr.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[Mr.SCALAR])}function Rx({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[Mr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Mr.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}Ng.composeScalar=Ex});var Sg=x(kg=>{"use strict";function xx(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}kg.emptyScalarPosition=xx});var Rg=x(tf=>{"use strict";var Cx=Ha(),Ax=J(),_x=mg(),Eg=bg(),Tx=Sn(),Ix=Sg(),jx={composeNode:Pg,composeEmptyNode:ef};function Pg(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=$x(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=Eg.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=_x.composeCollection(jx,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=ef(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&&(!Ax.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 ef(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Ix.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Eg.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function $x({options:e},{offset:t,source:i,end:r},n){let a=new Cx.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=Tx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}tf.composeEmptyNode=ef;tf.composeNode=Pg});var Ag=x(Cg=>{"use strict";var Ox=Qa(),xg=Rg(),Hx=Sn(),Dx=io();function Mx(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Ox.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Dx.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?xg.composeNode(l,n,u,o):xg.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Hx.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Cg.composeDoc=Mx});var nf=x(Ig=>{"use strict";var Fx=Ps("process"),Lx=qu(),Bx=Qa(),ro=to(),_g=J(),qx=Ag(),Vx=Sn();function no(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 Tg(e){let t="",i=!1,r=!1;for(let n=0;n{let o=no(i);a?this.warnings.push(new ro.YAMLWarning(o,r,n)):this.errors.push(new ro.YAMLParseError(o,r,n))},this.directives=new Lx.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=_g(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} -${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ag.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ag.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r} +`)+(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 rf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=no(i);a?this.warnings.push(new ro.YAMLWarning(o,r,n)):this.errors.push(new ro.YAMLParseError(o,r,n))},this.directives=new Lx.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Tg(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} +${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(_g.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];_g.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r} ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r} -${o}`:r}}if(i){for(let a=0;a{let a=no(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=qx.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 ro.YAMLParseError(no(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 ro.YAMLParseError(no(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Vx.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} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new ro.YAMLParseError(no(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 Bx.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}}};Tg.Composer=rf});var $g=x(vc=>{"use strict";var Wx=Xd(),zx=Zd(),Jx=to(),Ig=Ba();function Gx(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 Jx.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return zx.resolveFlowScalar(e,t,r);case"block-scalar":return Wx.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Ux(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Ig.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:` +${o}`:r}}if(i){for(let a=0;a{let a=no(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=qx.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 ro.YAMLParseError(no(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 ro.YAMLParseError(no(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Vx.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} +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new ro.YAMLParseError(no(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 Bx.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}}};Ig.Composer=rf});var Og=x(vc=>{"use strict";var Wx=Xd(),zx=Zd(),Jx=to(),jg=Ba();function Gx(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 Jx.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return zx.resolveFlowScalar(e,t,r);case"block-scalar":return Wx.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Ux(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=jg.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:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),u=s.substring(0,l),d=s.substring(l+1)+` -`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return jg(f,c)||f.push({type:"newline",offset:-1,indent:r,source:` -`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function Kx(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Ig.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Yx(e,c);break;case'"':af(e,c,"double-quoted-scalar");break;case"'":af(e,c,"single-quoted-scalar");break;default:af(e,c,"scalar")}}function Yx(e,t){let i=t.indexOf(` +`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return $g(f,c)||f.push({type:"newline",offset:-1,indent:r,source:` +`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function Kx(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=jg.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Yx(e,c);break;case'"':af(e,c,"double-quoted-scalar");break;case"'":af(e,c,"single-quoted-scalar");break;default:af(e,c,"scalar")}}function Yx(e,t){let i=t.indexOf(` `),r=t.substring(0,i),n=t.substring(i+1)+` -`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];jg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function jg(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 af(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:` -`};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})}}}vc.createScalarToken=Ux;vc.resolveAsScalar=Gx;vc.setScalarValue=Kx});var Hg=x(Og=>{"use strict";var Xx=e=>"type"in e?wc(e):gc(e);function wc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=wc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=gc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=gc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=gc(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 gc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=wc(t)),i)for(let a of i)n+=a.source;return r&&(n+=wc(r)),n}Og.stringify=Xx});var Lg=x(Fg=>{"use strict";var of=Symbol("break visit"),Qx=Symbol("skip children"),Dg=Symbol("remove item");function Fr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Mg(Object.freeze([]),e,t)}Fr.BREAK=of;Fr.SKIP=Qx;Fr.REMOVE=Dg;Fr.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};Fr.parentCollection=(e,t)=>{let i=Fr.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 Mg(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{"use strict";var sf=$g(),Zx=Hg(),eC=Lg(),cf="\uFEFF",lf="",uf="",df="",tC=e=>!!e&&"items"in e,iC=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function rC(e){switch(e){case cf:return"";case lf:return"";case uf:return"";case df:return"";default:return JSON.stringify(e)}}function nC(e){switch(e){case cf:return"byte-order-mark";case lf:return"doc-mode";case uf:return"flow-error-end";case df:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];$g(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` +`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function $g(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 af(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:` +`};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})}}}vc.createScalarToken=Ux;vc.resolveAsScalar=Gx;vc.setScalarValue=Kx});var Dg=x(Hg=>{"use strict";var Xx=e=>"type"in e?wc(e):gc(e);function wc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=wc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=gc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=gc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=gc(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 gc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=wc(t)),i)for(let a of i)n+=a.source;return r&&(n+=wc(r)),n}Hg.stringify=Xx});var Bg=x(Lg=>{"use strict";var of=Symbol("break visit"),Qx=Symbol("skip children"),Mg=Symbol("remove item");function Fr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Fg(Object.freeze([]),e,t)}Fr.BREAK=of;Fr.SKIP=Qx;Fr.REMOVE=Mg;Fr.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};Fr.parentCollection=(e,t)=>{let i=Fr.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 Fg(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{"use strict";var sf=Og(),Zx=Dg(),eC=Bg(),cf="\uFEFF",lf="",uf="",df="",tC=e=>!!e&&"items"in e,iC=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function rC(e){switch(e){case cf:return"";case lf:return"";case uf:return"";case df:return"";default:return JSON.stringify(e)}}function nC(e){switch(e){case cf:return"byte-order-mark";case lf:return"doc-mode";case uf:return"flow-error-end";case df:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}it.createScalarToken=sf.createScalarToken;it.resolveAsScalar=sf.resolveAsScalar;it.setScalarValue=sf.setScalarValue;it.stringify=Zx.stringify;it.visit=eC.visit;it.BOM=cf;it.DOCUMENT=lf;it.FLOW_END=uf;it.SCALAR=df;it.isCollection=tC;it.isScalar=iC;it.prettyToken=rC;it.tokenType=nC});var pf=x(qg=>{"use strict";var ao=yc();function Ft(e){switch(e){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var Bg=new Set("0123456789ABCDEFabcdef"),aC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Nc=new Set(",[]{}"),oC=new Set(` ,[]{} +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}it.createScalarToken=sf.createScalarToken;it.resolveAsScalar=sf.resolveAsScalar;it.setScalarValue=sf.setScalarValue;it.stringify=Zx.stringify;it.visit=eC.visit;it.BOM=cf;it.DOCUMENT=lf;it.FLOW_END=uf;it.SCALAR=df;it.isCollection=tC;it.isScalar=iC;it.prettyToken=rC;it.tokenType=nC});var pf=x(Vg=>{"use strict";var ao=yc();function Ft(e){switch(e){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var qg=new Set("0123456789ABCDEFabcdef"),aC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Nc=new Set(",[]{}"),oC=new Set(` ,[]{} \r `),ff=e=>!e||oC.has(e),hf=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===` `?!0:i==="\r"?this.buffer[t+1]===` `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===` @@ -133,14 +133,14 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield ao.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(Ft(a)||t&&Nc.has(a))break;i=r}else if(Ft(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===` `?(r+=1,n=` `,a=this.buffer[r+1]):i=r),a==="#"||t&&Nc.has(a))break;if(n===` -`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Nc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ao.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(ff),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ft(r)||i&&Nc.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(;!Ft(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(aC.has(i))i=this.buffer[++t];else if(i==="%"&&Bg.has(this.buffer[t+1])&&Bg.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` +`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Nc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ao.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(ff),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ft(r)||i&&Nc.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(;!Ft(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(aC.has(i))i=this.buffer[++t];else if(i==="%"&&qg.has(this.buffer[t+1])&&qg.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,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)}};qg.Lexer=hf});var vf=x(Vg=>{"use strict";var mf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var sC=Ps("process"),Wg=yc(),cC=pf();function Ji(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function kc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&Jg(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&&zg(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent0&&(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)}};Vg.Lexer=hf});var vf=x(Wg=>{"use strict";var mf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var sC=Ps("process"),zg=yc(),cC=pf();function Ji(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function kc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&Gg(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&&Jg(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.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;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":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(Ji(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(Gg(i.key)&&!Ji(i.sep,"newline")){let o=En(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(Ji(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=En(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]}):Ji(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&&!Ji(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)){kc(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||Ji(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=bc(r),a=En(n);Jg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` +`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let 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)){kc(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;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":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(Ji(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(Ug(i.key)&&!Ji(i.sep,"newline")){let o=En(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(Ji(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=En(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]}):Ji(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&&!Ji(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)){kc(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||Ji(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=bc(r),a=En(n);Gg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=bc(t),r=En(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=bc(t),r=En(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())}}};Ug.Parser=gf});var Zg=x(so=>{"use strict";var Kg=nf(),lC=Qa(),oo=to(),uC=td(),dC=J(),fC=vf(),Yg=wf();function Xg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new fC.LineCounter||null,prettyErrors:t}}function hC(e,t={}){let{lineCounter:i,prettyErrors:r}=Xg(t),n=new Yg.Parser(i?.addNewLine),a=new Kg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(oo.prettifyError(e,i)),s.warnings.forEach(oo.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Qg(e,t={}){let{lineCounter:i,prettyErrors:r}=Xg(t),n=new Yg.Parser(i?.addNewLine),a=new Kg.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 oo.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(oo.prettifyError(e,i)),o.warnings.forEach(oo.prettifyError(e,i))),o}function pC(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Qg(e,i);if(!n)return null;if(n.warnings.forEach(a=>uC.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 mC(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 dC.isDocument(e)&&!r?e.toString(i):new lC.Document(e,r,i).toString(i)}so.parse=pC;so.parseAllDocuments=hC;so.parseDocument=Qg;so.stringify=mC});var Lr=x(Y=>{"use strict";var vC=nf(),gC=Qa(),wC=Dd(),yf=to(),yC=Ha(),Gi=J(),NC=qi(),bC=ye(),kC=Wi(),SC=zi(),EC=yc(),PC=pf(),RC=vf(),xC=wf(),Sc=Zg(),ew=Ia();Y.Composer=vC.Composer;Y.Document=gC.Document;Y.Schema=wC.Schema;Y.YAMLError=yf.YAMLError;Y.YAMLParseError=yf.YAMLParseError;Y.YAMLWarning=yf.YAMLWarning;Y.Alias=yC.Alias;Y.isAlias=Gi.isAlias;Y.isCollection=Gi.isCollection;Y.isDocument=Gi.isDocument;Y.isMap=Gi.isMap;Y.isNode=Gi.isNode;Y.isPair=Gi.isPair;Y.isScalar=Gi.isScalar;Y.isSeq=Gi.isSeq;Y.Pair=NC.Pair;Y.Scalar=bC.Scalar;Y.YAMLMap=kC.YAMLMap;Y.YAMLSeq=SC.YAMLSeq;Y.CST=EC;Y.Lexer=PC.Lexer;Y.LineCounter=RC.LineCounter;Y.Parser=xC.Parser;Y.parse=Sc.parse;Y.parseAllDocuments=Sc.parseAllDocuments;Y.parseDocument=Sc.parseDocument;Y.stringify=Sc.stringify;Y.visit=ew.visit;Y.visitAsync=ew.visitAsync});import{promises as VS}from"node:fs";import Ou from"node:path";import{promises as xu}from"fs";import xe from"path";import{promises as Dk}from"fs";import Sa from"path";import{isDeepStrictEqual as fH}from"util";import{createHash as QS}from"crypto";function cm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function lm(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))lm(e[t]);return Object.freeze(e)}function Di(e){return lm(structuredClone(e))}function Du(e,t,i,r){return e.resolveStep({pkg:Di(t),state:Di(i),context:Di(r)})}function um(e,t,i,r,n,a){return e.resolveNext({pkg:Di(t),state:Di(i),step:Di(r),outcome:Di(n),context:Di(a)})}function ZS(e,t,i){return QS("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Mu(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function dm(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Du(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Mu(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:ZS(s.runId,s.iteration,o.id),stepId:o.id};return eE(e,s,c,i)}function eE(e,t,i,r){let n=cm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function fm(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Du(r,e,t,n):void 0,o=a?Mu(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?um(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Mu(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Rh}from"fs";import yN from"path";var Rl=hn(Lr(),1);import{promises as lN}from"fs";import li from"path";import{execFileSync as CC}from"child_process";import co from"path";function Pn(e,t){return CC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function AC(e,t){let i=co.normalize(e),r=co.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ae(e){try{let t=co.resolve(Pn(e,["rev-parse","--show-toplevel"])),r=Pn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?co.resolve(r.slice(9)):t,a=null;try{a=Pn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!AC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function tw(e){try{Pn(e,["rev-parse","--is-inside-work-tree"]);let t=Pn(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:co.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 Rn(e){return tw(e).map(t=>t.root)}function Nf(e,t){try{let i=Pn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as jC}from"node:crypto";import{promises as Lt}from"node:fs";import St from"node:path";import{TextDecoder as $C}from"node:util";import bf from"path";var _C=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),TC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function IC(e){return e.toLowerCase().startsWith(".env")}function ii(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>IC(r))?"environment-file":i.some(r=>TC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>_C.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function kf(e,t){let i=ii(t);if(i)return i;let r=bf.resolve(e.projectRoot,...t.split("/")),n=bf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===bf.resolve(e.configFile)?"native-runtime":null}function Ui(e){return e!==0&&e!==0n&&e!=="0"}function Fe(e,t){return Ui(e.dev)&&Ui(t.dev)&&Ui(e.ino)&&Ui(t.ino)}function W(e,t){let i=Ui(e.dev)&&Ui(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ui(e.ino)&&Ui(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var lo=1024*1024;function Sf(e,t){let i=St.relative(e,t);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}function OC(e){let t=St.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})||St.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=ii(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 HC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function DC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ec(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function iw(e){let t=await Lt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Lt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function MC(e,t){let i=St.resolve(e),r=St.resolve(t);if(!Sf(i,r))throw new Error("Native artifact path is outside its root");let n=[await iw(i)],a=i;for(let o of St.relative(i,r).split(St.sep).filter(Boolean)){a=St.join(a,o);let s=await iw(a);if(!Sf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function rw(e){for(let t of e){let i=await Lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!DC(t,i)||await Lt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Q(e){let t=OC(e.ref),i=e.maxBytes===null?null:HC(e.maxBytes??lo),r=St.resolve(e.root,...t.split("/")),n=await MC(e.root,St.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Lt.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 Lt.realpath(r);if(!Sf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Lt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await rw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ec(a,c)||!Ec(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let E=i===null?p.length:i+1-f,S=await s.read(p,0,Math.min(p.length,E),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await rw(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Ec(c,v)||!Ec(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let N=Buffer.concat(d,f),y;try{y=new $C("utf-8",{fatal:!0}).decode(N)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:jC("sha256").update(N).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as FC}from"crypto";import{promises as Le}from"fs";import Bt from"path";function Pf(e,t){let i=Bt.relative(e,t);return i===""||!Bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Bt.sep}`)}function LC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ef(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function nw(e){let t=await Le.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 Le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function uo(e){for(let t of e){let i=await Le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!LC(t,i)||await Le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function BC(e,t){let i=Bt.resolve(e),r=Bt.resolve(t);if(!Pf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await nw(i)],a=Bt.relative(i,r).split(Bt.sep).filter(Boolean),o=i;for(let s of a){await uo(n),o=Bt.join(o,s);try{await Le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await nw(o);if(!Pf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await uo(n),n}async function qC(e){let t;try{t=await Le.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 aw(e,t,i={}){let r=Bt.dirname(e),n=i.containedRoot?await BC(i.containedRoot,r):null;n||await Le.mkdir(r,{recursive:!0});let a=Bt.join(r,`.${Bt.basename(e)}.${FC()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Le.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([Le.lstat(a),Le.realpath(a)]);if(await uo(n),!c.isFile()||c.isSymbolicLink()||!Ef(s,c)||!Pf(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Ef(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await uo(n);let c=await Le.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Ef(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Le.link(a,e),await Le.unlink(a)):await Le.rename(a,e),await qC(r)}catch(c){if(await o?.close(),!n)await Le.rm(a,{force:!0});else try{await uo(n),await Le.rm(a,{force:!0})}catch{}throw c}}async function ue(e,t,i={}){await aw(e,t,i)}async function ow(e,t,i={}){await aw(e,t,i)}async function te(e,t,i={}){await ue(e,JSON.stringify(t,null,2)+` -`,i)}import dA from"path";var fo=hn(Lr(),1);import Rc from"path";var ho=64*1024,xc=1024,Cc=64,cw=5,VC=[".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/**",".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/**"],WC=["**/.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"],zC=[...VC,...WC].sort((e,t)=>e.localeCompare(t,"en"));var qt={include:["**/*"],exclude:[...zC],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Pc={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it. +`,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=bc(t),r=En(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=bc(t),r=En(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())}}};Kg.Parser=gf});var ew=x(so=>{"use strict";var Yg=nf(),lC=Qa(),oo=to(),uC=td(),dC=J(),fC=vf(),Xg=wf();function Qg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new fC.LineCounter||null,prettyErrors:t}}function hC(e,t={}){let{lineCounter:i,prettyErrors:r}=Qg(t),n=new Xg.Parser(i?.addNewLine),a=new Yg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(oo.prettifyError(e,i)),s.warnings.forEach(oo.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Zg(e,t={}){let{lineCounter:i,prettyErrors:r}=Qg(t),n=new Xg.Parser(i?.addNewLine),a=new Yg.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 oo.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(oo.prettifyError(e,i)),o.warnings.forEach(oo.prettifyError(e,i))),o}function pC(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Zg(e,i);if(!n)return null;if(n.warnings.forEach(a=>uC.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 mC(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 dC.isDocument(e)&&!r?e.toString(i):new lC.Document(e,r,i).toString(i)}so.parse=pC;so.parseAllDocuments=hC;so.parseDocument=Zg;so.stringify=mC});var Lr=x(Y=>{"use strict";var vC=nf(),gC=Qa(),wC=Dd(),yf=to(),yC=Ha(),Gi=J(),NC=qi(),bC=ye(),kC=Wi(),SC=zi(),EC=yc(),PC=pf(),RC=vf(),xC=wf(),Sc=ew(),tw=Ia();Y.Composer=vC.Composer;Y.Document=gC.Document;Y.Schema=wC.Schema;Y.YAMLError=yf.YAMLError;Y.YAMLParseError=yf.YAMLParseError;Y.YAMLWarning=yf.YAMLWarning;Y.Alias=yC.Alias;Y.isAlias=Gi.isAlias;Y.isCollection=Gi.isCollection;Y.isDocument=Gi.isDocument;Y.isMap=Gi.isMap;Y.isNode=Gi.isNode;Y.isPair=Gi.isPair;Y.isScalar=Gi.isScalar;Y.isSeq=Gi.isSeq;Y.Pair=NC.Pair;Y.Scalar=bC.Scalar;Y.YAMLMap=kC.YAMLMap;Y.YAMLSeq=SC.YAMLSeq;Y.CST=EC;Y.Lexer=PC.Lexer;Y.LineCounter=RC.LineCounter;Y.Parser=xC.Parser;Y.parse=Sc.parse;Y.parseAllDocuments=Sc.parseAllDocuments;Y.parseDocument=Sc.parseDocument;Y.stringify=Sc.stringify;Y.visit=tw.visit;Y.visitAsync=tw.visitAsync});import{promises as VS}from"node:fs";import Ou from"node:path";import{promises as xu}from"fs";import xe from"path";import{promises as Mk}from"fs";import Sa from"path";import{isDeepStrictEqual as fH}from"util";import{createHash as QS}from"crypto";function lm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function um(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))um(e[t]);return Object.freeze(e)}function Di(e){return um(structuredClone(e))}function Du(e,t,i,r){return e.resolveStep({pkg:Di(t),state:Di(i),context:Di(r)})}function dm(e,t,i,r,n,a){return e.resolveNext({pkg:Di(t),state:Di(i),step:Di(r),outcome:Di(n),context:Di(a)})}function ZS(e,t,i){return QS("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Mu(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function fm(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Du(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Mu(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:ZS(s.runId,s.iteration,o.id),stepId:o.id};return eE(e,s,c,i)}function eE(e,t,i,r){let n=lm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function hm(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Du(r,e,t,n):void 0,o=a?Mu(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?dm(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Mu(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Rh}from"fs";import NN from"path";var Rl=hn(Lr(),1);import{promises as uN}from"fs";import li from"path";import{execFileSync as CC}from"child_process";import co from"path";function Pn(e,t){return CC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function AC(e,t){let i=co.normalize(e),r=co.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ae(e){try{let t=co.resolve(Pn(e,["rev-parse","--show-toplevel"])),r=Pn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?co.resolve(r.slice(9)):t,a=null;try{a=Pn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!AC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function iw(e){try{Pn(e,["rev-parse","--is-inside-work-tree"]);let t=Pn(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:co.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 Rn(e){return iw(e).map(t=>t.root)}function Nf(e,t){try{let i=Pn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as jC}from"node:crypto";import{promises as Lt}from"node:fs";import St from"node:path";import{TextDecoder as $C}from"node:util";import bf from"path";var _C=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),TC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function IC(e){return e.toLowerCase().startsWith(".env")}function ii(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>IC(r))?"environment-file":i.some(r=>TC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>_C.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function kf(e,t){let i=ii(t);if(i)return i;let r=bf.resolve(e.projectRoot,...t.split("/")),n=bf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===bf.resolve(e.configFile)?"native-runtime":null}function Ui(e){return e!==0&&e!==0n&&e!=="0"}function Fe(e,t){return Ui(e.dev)&&Ui(t.dev)&&Ui(e.ino)&&Ui(t.ino)}function W(e,t){let i=Ui(e.dev)&&Ui(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ui(e.ino)&&Ui(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var lo=1024*1024;function Sf(e,t){let i=St.relative(e,t);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}function OC(e){let t=St.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})||St.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=ii(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 HC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function DC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ec(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function rw(e){let t=await Lt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Lt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function MC(e,t){let i=St.resolve(e),r=St.resolve(t);if(!Sf(i,r))throw new Error("Native artifact path is outside its root");let n=[await rw(i)],a=i;for(let o of St.relative(i,r).split(St.sep).filter(Boolean)){a=St.join(a,o);let s=await rw(a);if(!Sf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function nw(e){for(let t of e){let i=await Lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!DC(t,i)||await Lt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Q(e){let t=OC(e.ref),i=e.maxBytes===null?null:HC(e.maxBytes??lo),r=St.resolve(e.root,...t.split("/")),n=await MC(e.root,St.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Lt.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 Lt.realpath(r);if(!Sf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Lt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await nw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ec(a,c)||!Ec(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let E=i===null?p.length:i+1-f,S=await s.read(p,0,Math.min(p.length,E),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await nw(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Ec(c,v)||!Ec(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let N=Buffer.concat(d,f),y;try{y=new $C("utf-8",{fatal:!0}).decode(N)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:jC("sha256").update(N).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as FC}from"crypto";import{promises as Le}from"fs";import Bt from"path";function Pf(e,t){let i=Bt.relative(e,t);return i===""||!Bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Bt.sep}`)}function LC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ef(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function aw(e){let t=await Le.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 Le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function uo(e){for(let t of e){let i=await Le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!LC(t,i)||await Le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function BC(e,t){let i=Bt.resolve(e),r=Bt.resolve(t);if(!Pf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await aw(i)],a=Bt.relative(i,r).split(Bt.sep).filter(Boolean),o=i;for(let s of a){await uo(n),o=Bt.join(o,s);try{await Le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await aw(o);if(!Pf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await uo(n),n}async function qC(e){let t;try{t=await Le.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 ow(e,t,i={}){let r=Bt.dirname(e),n=i.containedRoot?await BC(i.containedRoot,r):null;n||await Le.mkdir(r,{recursive:!0});let a=Bt.join(r,`.${Bt.basename(e)}.${FC()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Le.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([Le.lstat(a),Le.realpath(a)]);if(await uo(n),!c.isFile()||c.isSymbolicLink()||!Ef(s,c)||!Pf(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Ef(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await uo(n);let c=await Le.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Ef(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Le.link(a,e),await Le.unlink(a)):await Le.rename(a,e),await qC(r)}catch(c){if(await o?.close(),!n)await Le.rm(a,{force:!0});else try{await uo(n),await Le.rm(a,{force:!0})}catch{}throw c}}async function ue(e,t,i={}){await ow(e,t,i)}async function sw(e,t,i={}){await ow(e,t,i)}async function te(e,t,i={}){await ue(e,JSON.stringify(t,null,2)+` +`,i)}import dA from"path";var fo=hn(Lr(),1);import Rc from"path";var ho=64*1024,xc=1024,Cc=64,lw=5,VC=[".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/**",".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/**"],WC=["**/.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"],zC=[...VC,...WC].sort((e,t)=>e.localeCompare(t,"en"));var qt={include:["**/*"],exclude:[...zC],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Pc={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it. # ambient_resume: true | false`,hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents. # language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time. # clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation. @@ -158,44 +158,44 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。 # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。 # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。 -# 可选值:true | false`}};function lw(e,t){return Pc[t][e]}function JC(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Pc.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Pc.en)return o}if(n===2&&t===null&&a==="hook")return"hook";if(n===2&&t==="hook"&&a==="allow_paths")return"hook.allow_paths";if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Pc.en)return o}return null}function po(e,t){let i=[],r=null,n=null;for(let a of(0,fo.stringify)(e).trimEnd().split(` -`)){let o=JC(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of lw(o,t).split(` +# 可选值:true | false`}};function uw(e,t){return Pc[t][e]}function JC(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Pc.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Pc.en)return o}if(n===2&&t===null&&a==="hook")return"hook";if(n===2&&t==="hook"&&a==="allow_paths")return"hook.allow_paths";if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Pc.en)return o}return null}function po(e,t){let i=[],r=null,n=null;for(let a of(0,fo.stringify)(e).trimEnd().split(` +`)){let o=JC(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of uw(o,t).split(` `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":a.startsWith("hook:")?r="hook":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(` -`)}function GC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Rc.posix.isAbsolute(i)||Rc.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 Cn(e){let t=GC(e,"native.artifact_root");return t.length===0?".":t.join("/")}function uw(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 Ac(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||Rc.posix.isAbsolute(r)||Rc.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 An(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function dw(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 _c(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>xc)throw new Error(`${t} exceeds ${xc} characters`);let i=0;for(let r=0;rCc)throw new Error(`${t} contains more than ${Cc} wildcard tokens`);return e}function sw(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=>_c(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Rf(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 UC(e){if(e===void 0)return{...qt,include:[...qt.include],exclude:[...qt.exclude]};let t=An(e,"native.snapshot");return{include:sw(t.include,"native.snapshot.include",qt.include),exclude:sw(t.exclude,"native.snapshot.exclude",qt.exclude),max_files:Rf(t.max_files,qt.max_files,"native.snapshot.max_files"),max_total_bytes:Rf(t.max_total_bytes,qt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Rf(t.max_duration_ms,qt.max_duration_ms,"native.snapshot.max_duration_ms")}}function KC(e){if(e===void 0)return;let t=An(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=An(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:Cn(r),toArtifactRoot:Cn(n),stage:a,...o?{cleanup:o}:{}}}function YC(e,t={}){let i=An(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??cw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=KC(i.pending_root_move);return{artifact_root:Cn(r),language:dw(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:UC(i.snapshot),...s?{pending_root_move:s}:{}}}function XC(e){let t=An(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:uw(t.artifact_layout),language:dw(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function QC(e){let i=An(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)=>Ac(r,`hook.allow_paths[${n}]`)))]}}function ZC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function eA(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 _n(e,t={}){let i=(0,fo.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=ZC(n.ambient_resume),o=n.hook===void 0?void 0:QC(n.hook),s=n.native===void 0?void 0:YC(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:XC(n.classic),l=eA(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 fw(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function hw(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.pending_root_move?{pending_root_move:fw(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function xn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function mo(e,t){let i=hw(t),r=_n((0,fo.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...xn(e.hook),allow_paths:[...r.hook.allow_paths]}),r.native){let a=xn(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=xn(a.pending_root_move),c=fw(r.native.pending_root_move),l=xn(s.cleanup),u=xn(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...xn(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as iA}from"crypto";import{promises as jc}from"fs";import Ki from"path";import{constants as Tc,promises as Br}from"fs";var Vt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function xf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function pw(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function vo(e){return{dev:e.dev,ino:e.ino,birthtime:xf(e)}}function Ic(e,t){let i=vo(e),r=vo(t);return Fe(i,r)?W(i,r):W(i,r)&&xf(e)===xf(t)&&pw(e)===pw(t)&&e.size===t.size}async function qr(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 Br.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Vt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Vt("too-large",`${r} exceeds ${t} bytes`);let o=await Br.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:vo(a)});let s=process.platform==="win32"?Tc.O_RDONLY:Tc.O_RDONLY|Tc.O_NOFOLLOW|Tc.O_NONBLOCK,c;try{c=await Br.open(e,s)}catch(l){throw l.code==="ELOOP"?new Vt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Br.lstat(e,{bigint:n}),Br.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ic(a,l)||!Ic(a,u))throw new Vt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:vo(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:E}=await c.read(v,0,Math.min(v.length,y),null);if(E===0)break;if(p+=E,p>t)throw new Vt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([c.stat({bigint:n}),Br.lstat(e,{bigint:n}),Br.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||N!==o||!Ic(a,h)||!Ic(a,m))throw new Vt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:vo(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:N}}finally{await c.close()}}function tA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Cf(e,t){let i=Ki.relative(e,t);return i===""||!Ki.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ki.sep}`)}async function mw(e,t){let i=Ki.resolve(e),r=await jc.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return jc.realpath(i)}async function vw(e,t,i,r){let n=e;for(let a=0;a{if(!Cf(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await vw(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var go=".comet/config.yaml";function Af(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function rA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function $c(e,t={}){return(await wo(e,t)).document}async function gw(e){try{return(await Yi(e,go,ho,{label:go})).bytes}catch(t){if(rA(t))return null;throw t}}function ww(e){return e?{exists:!0,sha256:iA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Oc(e){return ww(await gw(e))}async function wo(e,t={}){let i=await gw(e);return{document:i?_n(i.toString("utf8"),t):null,identity:ww(i)}}async function _f(e){return(await $c(e))?.config??null}var TL=16*1024;async function Tf(e,t){if(!t)return;let i=await Oc(e);if(!Af(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as yw,promises as Xi}from"fs";import U from"path";import sA from"os";var Hc=".comet/config.yaml",cA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function If(e){try{return await Xi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function lA(e){try{let t=await Xi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function jn(e,t){let i=U.relative(e,t);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}async function In(e){let t=[],i=e;for(;!await If(i);){let n=U.dirname(i);if(n===i)break;t.push(U.basename(i)),i=n}let r=await Xi.realpath(i);return U.resolve(r,...t.reverse())}async function jf(e){try{return(await Xi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $f(e){let t=U.resolve(e);try{(await Xi.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=U.resolve(sA.homedir());for(;;){if(!(t===r&&i!==r)){let o=U.join(t,...Hc.split("/")),s=t===i||await lA(o);if(await If(o)&&s)return t}if(await If(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return i;t=a}}function Dc(e){return Cn(e)}async function uA(e,t){let i=Dc(t),r=U.resolve(e,...i.split("/")),n=await Xi.realpath(e),a=await In(r);if(!jn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Be(e,t){let i=Dc(t),r=await uA(e,i),n=U.join(r,"comet");if(await jf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([In(r),In(n)]);if(!jn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await jf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Xi.realpath(s),In(c)]);if(!jn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Hc.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function bw(e){if(!cA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function rt(e,t){bw(t);let i=U.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Vr(e,t){bw(t);let i=U.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=rt(e,t);if(yw(i))return i;let r=Vr(e,t);return yw(r)?r:i}async function Nw(e){try{let t=await Xi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function No(e,t){let i=rt(e,t),r=Vr(e,t),[n,a]=await Promise.all([Nw(i),Nw(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Qi(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=U.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=U.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return jn(U.resolve(e),U.resolve(t))}async function T(e,t){let i=U.resolve(e),r=U.resolve(t);if(!jn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await jf(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([In(i),In(r)]);if(!jn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Of=qt;var Mc=_c;async function Ne(e){let t=(await $c(e))?.config??null;return t?.native?t:null}async function $n(e){let t=await Ne(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 Zi(e,t,i={}){let r=await wo(e,{allowPartialProject:!0}),n=mo(r.document?.value??{},t),a=dA.join(e,...Hc.split("/"));await ue(a,po(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Tf(e,r.identity)}})}import{promises as cT}from"fs";import lT from"path";import{AsyncLocalStorage as fA}from"async_hooks";import{randomUUID as Pw}from"crypto";import{promises as Et}from"fs";import Rw from"os";import de from"path";var Sw=16*1024,Hf=".coordinator",hA=5e3,Ew=new fA,Fc=new Map;function pA(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function mA(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 xw(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 Df(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Fe(i,r)?W(i,r):W(i,r)&&e.size===t.size}function Lc(e,t){return Df(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function vA(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Lc(e.identity,t.identity)}async function ri(e){let t,i;try{let r=await qr(e,Sw,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Vt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${Sw} 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:mA(JSON.parse(t.toString("utf8")),e),identity:xw(i)}}async function gA(e){return(await ri(e))?.owner??null}function Mf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Rw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=SA(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function wA(e,t){try{await Et.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Et.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Bc(e,t){let i=await ri(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Lc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Et.mkdir(t,{recursive:!0});let r=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${Pw()}.removed`);try{await Et.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ri(r);if(!n||n.owner.id!==e.owner.id||!Df(n.identity,e.identity))throw await wA(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Et.rm(r,{force:!0}),"removed"}function Cw(e){return{id:Pw(),pid:process.pid,hostname:Rw.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Aw(e,t){let i;try{i=await Et.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await gA(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)+` -`,"utf8"),await i.sync(),xw(await i.stat({bigint:!0}))}finally{await i.close()}}async function yA(e,t){let i=await T(e.runtimeDir,e.locksDir);await Et.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,de.join(i,Hf));await Et.mkdir(r,{recursive:!0});let n=Cw(t),a=de.join(r,`.${n.id}.tmp`),o=de.join(r,`${n.id}.claim`);try{let s=await Aw(a,n);await Et.rename(a,o);let c=await ri(o);if(!c||!Df(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 Et.rm(a,{force:!0})}}async function NA(e){let t=de.dirname(e.file),i=!1,r=de.basename(e.file);for(let n of await Et.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=de.join(t,n.name);if(de.resolve(a)!==de.resolve(e.file))try{let o=await ri(a),s=Mf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bc(o,t);continue}n.name=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 kA(e){let t=Fc.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Fc.set(e,n),await t,()=>{i(),Fc.get(e)===n&&Fc.delete(e)}}async function qc(e,t,i){let r=de.resolve(e.locksDir),n=Ew.getStore();if(n?.has(r))return i();let a=await kA(r);try{let o=await bA(e,t),s=new Map(n??[]);return s.set(r,o),await Ew.run(s,async()=>{try{return await i()}finally{await _w(o)}})}finally{a()}}async function On(e,t,i){let r=[...new Map(e.map(a=>[de.resolve(a.locksDir),a])).values()].sort((a,o)=>de.resolve(a.locksDir).localeCompare(de.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?qc(o,t,()=>n(a+1)):i()};return n(0)}async function er(e,t,i){return qc(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await Et.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,de.join(r,pA(t))),a=Cw(i),o=await Aw(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function tr(e){await ri(e.file)&&await qc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${de.basename(e.file)}`,async()=>{let t=await ri(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Lc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=de.join(e.locksDir,Hf);await Bc(t,i)})}function SA(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function bo(e){return Mf(await ri(e))}async function Ff(e,t,i){return qc(e,`take over ${de.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(de.resolve(de.dirname(n))!==de.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ri(n),o=Mf(a);if(o.status==="missing")return{status:"missing"};if(i&&!vA(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=de.join(r,Hf);return await Bc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as A_}from"node:fs";import Yf from"node:path";import p_ from"node:path";import Lw from"node:path";import Tw from"node:path";import{createHash as EA}from"crypto";function Wt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function PA(e,t){t.has(e)&&Wt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&Wt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Wt("symbol properties are not supported"),`[${e.map(r=>Lf(r,t)).join(",")}]`}finally{t.delete(e)}}function RA(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Wt("only plain objects are supported"),t.has(e)&&Wt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Wt("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))&&Wt("accessor properties are not supported"),`${JSON.stringify(o)}:${Lf(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Lf(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)||Wt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?PA(e,t):RA(e,t);case"bigint":case"function":case"symbol":case"undefined":return Wt(`${typeof e} values are not supported`)}return Wt("unsupported value type")}function ko(e){return Lf(e,new Set)}function M(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 EA("sha256").update(`${e} -${ko(t)}`).digest("hex")}var xA="comet.native.acceptance.v1",CA=/^acceptance-[a-f0-9]{64}$/u,AA=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),_A=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,TA=/^[a-f0-9]{64}$/u,IA=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function jA(e,t){return et?1:0}var ki=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Eo=Object.freeze({maxCriteria:1024}),Iw="",jw="";function $w(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:i,truncated:!0}}function Ow(e,t){let i=t.toString(36),r=M("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function $A(e){if(!TA.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=IA.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==M("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function OA(e,t){let i=$w(e.text,ki.maxTextBytes),r=e.context.slice(0,ki.maxContextItems).map(n=>$w(n,ki.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Dw(e){let t=$A({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(jA),n=r.slice(0,ki.maxFailedCheckIds),a=e.criteria.slice(t,t+ki.maxItems);for(let c of a){let l=[...i,OA(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:uki.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:oki.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function qf(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 Bf(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 Hw(e){return e.includes("-->")||e.includes("--!>")}function*Hn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` +`)}function GC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Rc.posix.isAbsolute(i)||Rc.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 Cn(e){let t=GC(e,"native.artifact_root");return t.length===0?".":t.join("/")}function dw(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 Ac(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||Rc.posix.isAbsolute(r)||Rc.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 An(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function fw(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 _c(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>xc)throw new Error(`${t} exceeds ${xc} characters`);let i=0;for(let r=0;rCc)throw new Error(`${t} contains more than ${Cc} wildcard tokens`);return e}function cw(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=>_c(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Rf(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 UC(e){if(e===void 0)return{...qt,include:[...qt.include],exclude:[...qt.exclude]};let t=An(e,"native.snapshot");return{include:cw(t.include,"native.snapshot.include",qt.include),exclude:cw(t.exclude,"native.snapshot.exclude",qt.exclude),max_files:Rf(t.max_files,qt.max_files,"native.snapshot.max_files"),max_total_bytes:Rf(t.max_total_bytes,qt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Rf(t.max_duration_ms,qt.max_duration_ms,"native.snapshot.max_duration_ms")}}function KC(e){if(e===void 0)return;let t=An(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=An(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:Cn(r),toArtifactRoot:Cn(n),stage:a,...o?{cleanup:o}:{}}}function YC(e,t={}){let i=An(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??lw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=KC(i.pending_root_move);return{artifact_root:Cn(r),language:fw(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:UC(i.snapshot),...s?{pending_root_move:s}:{}}}function XC(e){let t=An(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:dw(t.artifact_layout),language:fw(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function QC(e){let i=An(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)=>Ac(r,`hook.allow_paths[${n}]`)))]}}function ZC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function eA(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 _n(e,t={}){let i=(0,fo.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=ZC(n.ambient_resume),o=n.hook===void 0?void 0:QC(n.hook),s=n.native===void 0?void 0:YC(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:XC(n.classic),l=eA(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 hw(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function pw(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.pending_root_move?{pending_root_move:hw(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function xn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function mo(e,t){let i=pw(t),r=_n((0,fo.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...xn(e.hook),allow_paths:[...r.hook.allow_paths]}),r.native){let a=xn(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=xn(a.pending_root_move),c=hw(r.native.pending_root_move),l=xn(s.cleanup),u=xn(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...xn(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as iA}from"crypto";import{promises as jc}from"fs";import Ki from"path";import{constants as Tc,promises as Br}from"fs";var Vt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function xf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function mw(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function vo(e){return{dev:e.dev,ino:e.ino,birthtime:xf(e)}}function Ic(e,t){let i=vo(e),r=vo(t);return Fe(i,r)?W(i,r):W(i,r)&&xf(e)===xf(t)&&mw(e)===mw(t)&&e.size===t.size}async function qr(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 Br.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Vt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Vt("too-large",`${r} exceeds ${t} bytes`);let o=await Br.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:vo(a)});let s=process.platform==="win32"?Tc.O_RDONLY:Tc.O_RDONLY|Tc.O_NOFOLLOW|Tc.O_NONBLOCK,c;try{c=await Br.open(e,s)}catch(l){throw l.code==="ELOOP"?new Vt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Br.lstat(e,{bigint:n}),Br.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ic(a,l)||!Ic(a,u))throw new Vt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:vo(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:E}=await c.read(v,0,Math.min(v.length,y),null);if(E===0)break;if(p+=E,p>t)throw new Vt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([c.stat({bigint:n}),Br.lstat(e,{bigint:n}),Br.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||N!==o||!Ic(a,h)||!Ic(a,m))throw new Vt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:vo(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:N}}finally{await c.close()}}function tA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Cf(e,t){let i=Ki.relative(e,t);return i===""||!Ki.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ki.sep}`)}async function vw(e,t){let i=Ki.resolve(e),r=await jc.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return jc.realpath(i)}async function gw(e,t,i,r){let n=e;for(let a=0;a{if(!Cf(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await gw(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var go=".comet/config.yaml";function Af(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function rA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function $c(e,t={}){return(await wo(e,t)).document}async function ww(e){try{return(await Yi(e,go,ho,{label:go})).bytes}catch(t){if(rA(t))return null;throw t}}function yw(e){return e?{exists:!0,sha256:iA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Oc(e){return yw(await ww(e))}async function wo(e,t={}){let i=await ww(e);return{document:i?_n(i.toString("utf8"),t):null,identity:yw(i)}}async function _f(e){return(await $c(e))?.config??null}var IL=16*1024;async function Tf(e,t){if(!t)return;let i=await Oc(e);if(!Af(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as Nw,promises as Xi}from"fs";import U from"path";import sA from"os";var Hc=".comet/config.yaml",cA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function If(e){try{return await Xi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function lA(e){try{let t=await Xi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function jn(e,t){let i=U.relative(e,t);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}async function In(e){let t=[],i=e;for(;!await If(i);){let n=U.dirname(i);if(n===i)break;t.push(U.basename(i)),i=n}let r=await Xi.realpath(i);return U.resolve(r,...t.reverse())}async function jf(e){try{return(await Xi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $f(e){let t=U.resolve(e);try{(await Xi.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=U.resolve(sA.homedir());for(;;){if(!(t===r&&i!==r)){let o=U.join(t,...Hc.split("/")),s=t===i||await lA(o);if(await If(o)&&s)return t}if(await If(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return i;t=a}}function Dc(e){return Cn(e)}async function uA(e,t){let i=Dc(t),r=U.resolve(e,...i.split("/")),n=await Xi.realpath(e),a=await In(r);if(!jn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Be(e,t){let i=Dc(t),r=await uA(e,i),n=U.join(r,"comet");if(await jf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([In(r),In(n)]);if(!jn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await jf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Xi.realpath(s),In(c)]);if(!jn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Hc.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function kw(e){if(!cA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function rt(e,t){kw(t);let i=U.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Vr(e,t){kw(t);let i=U.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=rt(e,t);if(Nw(i))return i;let r=Vr(e,t);return Nw(r)?r:i}async function bw(e){try{let t=await Xi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function No(e,t){let i=rt(e,t),r=Vr(e,t),[n,a]=await Promise.all([bw(i),bw(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Qi(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=U.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=U.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return jn(U.resolve(e),U.resolve(t))}async function T(e,t){let i=U.resolve(e),r=U.resolve(t);if(!jn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await jf(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([In(i),In(r)]);if(!jn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Of=qt;var Mc=_c;async function Ne(e){let t=(await $c(e))?.config??null;return t?.native?t:null}async function $n(e){let t=await Ne(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 Zi(e,t,i={}){let r=await wo(e,{allowPartialProject:!0}),n=mo(r.document?.value??{},t),a=dA.join(e,...Hc.split("/"));await ue(a,po(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Tf(e,r.identity)}})}import{promises as cT}from"fs";import lT from"path";import{AsyncLocalStorage as fA}from"async_hooks";import{randomUUID as Rw}from"crypto";import{promises as Et}from"fs";import xw from"os";import de from"path";var Ew=16*1024,Hf=".coordinator",hA=5e3,Pw=new fA,Fc=new Map;function pA(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function mA(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 Cw(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 Df(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Fe(i,r)?W(i,r):W(i,r)&&e.size===t.size}function Lc(e,t){return Df(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function vA(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Lc(e.identity,t.identity)}async function ri(e){let t,i;try{let r=await qr(e,Ew,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Vt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${Ew} 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:mA(JSON.parse(t.toString("utf8")),e),identity:Cw(i)}}async function gA(e){return(await ri(e))?.owner??null}function Mf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==xw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=SA(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function wA(e,t){try{await Et.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Et.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Bc(e,t){let i=await ri(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Lc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Et.mkdir(t,{recursive:!0});let r=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${Rw()}.removed`);try{await Et.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ri(r);if(!n||n.owner.id!==e.owner.id||!Df(n.identity,e.identity))throw await wA(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Et.rm(r,{force:!0}),"removed"}function Aw(e){return{id:Rw(),pid:process.pid,hostname:xw.hostname(),createdAt:new Date().toISOString(),operation:e}}async function _w(e,t){let i;try{i=await Et.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await gA(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)+` +`,"utf8"),await i.sync(),Cw(await i.stat({bigint:!0}))}finally{await i.close()}}async function yA(e,t){let i=await T(e.runtimeDir,e.locksDir);await Et.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,de.join(i,Hf));await Et.mkdir(r,{recursive:!0});let n=Aw(t),a=de.join(r,`.${n.id}.tmp`),o=de.join(r,`${n.id}.claim`);try{let s=await _w(a,n);await Et.rename(a,o);let c=await ri(o);if(!c||!Df(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 Et.rm(a,{force:!0})}}async function NA(e){let t=de.dirname(e.file),i=!1,r=de.basename(e.file);for(let n of await Et.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=de.join(t,n.name);if(de.resolve(a)!==de.resolve(e.file))try{let o=await ri(a),s=Mf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bc(o,t);continue}n.name=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 kA(e){let t=Fc.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Fc.set(e,n),await t,()=>{i(),Fc.get(e)===n&&Fc.delete(e)}}async function qc(e,t,i){let r=de.resolve(e.locksDir),n=Pw.getStore();if(n?.has(r))return i();let a=await kA(r);try{let o=await bA(e,t),s=new Map(n??[]);return s.set(r,o),await Pw.run(s,async()=>{try{return await i()}finally{await Tw(o)}})}finally{a()}}async function On(e,t,i){let r=[...new Map(e.map(a=>[de.resolve(a.locksDir),a])).values()].sort((a,o)=>de.resolve(a.locksDir).localeCompare(de.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?qc(o,t,()=>n(a+1)):i()};return n(0)}async function er(e,t,i){return qc(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await Et.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,de.join(r,pA(t))),a=Aw(i),o=await _w(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function tr(e){await ri(e.file)&&await qc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${de.basename(e.file)}`,async()=>{let t=await ri(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Lc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=de.join(e.locksDir,Hf);await Bc(t,i)})}function SA(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function bo(e){return Mf(await ri(e))}async function Ff(e,t,i){return qc(e,`take over ${de.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(de.resolve(de.dirname(n))!==de.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ri(n),o=Mf(a);if(o.status==="missing")return{status:"missing"};if(i&&!vA(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=de.join(r,Hf);return await Bc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as A_}from"node:fs";import Yf from"node:path";import p_ from"node:path";import Bw from"node:path";import Iw from"node:path";import{createHash as EA}from"crypto";function Wt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function PA(e,t){t.has(e)&&Wt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&Wt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Wt("symbol properties are not supported"),`[${e.map(r=>Lf(r,t)).join(",")}]`}finally{t.delete(e)}}function RA(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Wt("only plain objects are supported"),t.has(e)&&Wt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Wt("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))&&Wt("accessor properties are not supported"),`${JSON.stringify(o)}:${Lf(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Lf(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)||Wt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?PA(e,t):RA(e,t);case"bigint":case"function":case"symbol":case"undefined":return Wt(`${typeof e} values are not supported`)}return Wt("unsupported value type")}function ko(e){return Lf(e,new Set)}function M(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 EA("sha256").update(`${e} +${ko(t)}`).digest("hex")}var xA="comet.native.acceptance.v1",CA=/^acceptance-[a-f0-9]{64}$/u,AA=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),_A=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,TA=/^[a-f0-9]{64}$/u,IA=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function jA(e,t){return et?1:0}var ki=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Eo=Object.freeze({maxCriteria:1024}),jw="",$w="";function Ow(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:i,truncated:!0}}function Hw(e,t){let i=t.toString(36),r=M("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function $A(e){if(!TA.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=IA.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==M("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function OA(e,t){let i=Ow(e.text,ki.maxTextBytes),r=e.context.slice(0,ki.maxContextItems).map(n=>Ow(n,ki.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Mw(e){let t=$A({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(jA),n=r.slice(0,ki.maxFailedCheckIds),a=e.criteria.slice(t,t+ki.maxItems);for(let c of a){let l=[...i,OA(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:uki.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:oki.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function qf(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 Bf(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 Dw(e){return e.includes("-->")||e.includes("--!>")}function*Hn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(` -`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Bf(l,t);else if(i)Hw(l)&&(i=!1);else if(r!==null)new RegExp(``,"iu").test(l)&&(r=null);else{let d=Bf(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith(""||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(),Wf(n,"Specification mandatory requirements",r)}function FA(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||DA(i)||Tw.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=Tw.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!_A.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function LA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!AA.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Mw(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=LA(i,r),a=n.acceptance_id;if(typeof a!="string"||!CA.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return FA(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Fw(e){let t=HA(e);if(t.some(({line:l,body:u})=>!u&&(l===Iw||l===jw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Iw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===jw?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(` -`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Mw(o),c=BA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function BA(e){let t=Mw([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var qA=/^A[1-9]\d*$/u;function Bw(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Lw.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Lw.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function VA(e,t){return e.localeCompare(t,"en")}function Jc(e){let t=Bw(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>VA(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=Vc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Bw(a.source,`Native spec source for ${a.capability}`);r.push(...Wc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...zc(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=So(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 qw(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}var Kc=hn(Lr(),1);import{promises as WA}from"node:fs";var Dn="comet.native.v4",Po="comet.native.local-execution.v4";function zf(){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 zA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GA=/^A[1-9][0-9]*$/u,UA=/^[a-f0-9]{64}$/u,KA=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"]),Uc=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 at(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ot(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 Te(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 Gf(e,t){return e===null?null:Te(e,t)}function YA(e,t){let i=Te(e,t);if(!UA.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Mn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function fe(e,t,i=0){if(!Number.isSafeInteger(e)||ei(r,n))}function Yc(e,t){return ni(e,t,(i,r)=>Te(i,`${t}[${r}]`))}function Wr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Fn(e,t){let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Uf(e,t,i=!1){let r=Te(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 zt(e,t){let i=at(e,t);return ot(i,new Set(["text","truncated"]),t),{text:Te(i.text,`${t}.text`,{empty:!0}),truncated:Mn(i.truncated,`${t}.truncated`)}}function QA(e,t){let i=`Native spec_changes[${t}]`,r=at(e,i);ot(r,new Set(["capability","operation","source"]),i);let n=Te(r.capability,`${i}.capability`);if(!JA.test(n))throw new Error(`${i}.capability is invalid`);let a=_e(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Uf(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 ZA(e){let t="Native workspace",i=at(e,t);ot(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=_e(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Gf(i.change_branch,`${t}.change_branch`),a=Gf(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:_e(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 e_(e){let t="Native loop",i=at(e,t);ot(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=Yc(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Wr(r,`${t}.previous_unresolved_ids`),{stage:_e(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:fe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:fe(i.iteration,`${t}.iteration`),attempt:fe(i.attempt,`${t}.attempt`),retry_epoch:fe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:fe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:fe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:fe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Gf(i.next_action,`${t}.next_action`)}}function t_(e,t){let i=`Native acceptance[${t}]`,r=at(e,i);ot(r,new Set(["id","source","text","result","reason"]),i);let n=Te(r.id,`${i}.id`);if(!GA.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Uf(r.source,`${i}.source`),text:Te(r.text,`${i}.text`),result:_e(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:zt(r.reason,`${i}.reason`)}}function i_(e,t){let i=`Native builder_handoff.checks[${t}]`,r=at(e,i);return ot(r,new Set(["name","result","note"]),i),{name:zt(r.name,`${i}.name`),result:_e(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:zt(r.note,`${i}.note`)}}function r_(e){let t="Native builder_handoff",i=at(e,t);ot(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=Yc(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Wr(r,`${t}.addressed_acceptance_ids`),{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:Te(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Te(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),summary:zt(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ni(i.checks,`${t}.checks`,i_),checks_truncated:Mn(i.checks_truncated,`${t}.checks_truncated`),known_limits:ni(i.known_limits,`${t}.known_limits`,(n,a)=>zt(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Mn(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Fn(i.submitted_at,`${t}.submitted_at`)}}function n_(e,t){let i=`Native blockers[${t}]`,r=at(e,i);ot(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Yc(r.acceptance_ids,`${i}.acceptance_ids`);return Wr(n,`${i}.acceptance_ids`),{owner:_e(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:zt(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:_e(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function a_(e,t){let i=`Native verification.checks[${t}]`,r=at(e,i);return ot(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Te(r.id,`${i}.id`),name:zt(r.name,`${i}.name`),argv_display:ni(r.argv_display,`${i}.argv_display`,(n,a)=>zt(n,`${i}.argv_display[${a}]`)),argv_truncated:Mn(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Uf(r.cwd_ref,`${i}.cwd_ref`,!0),status:_e(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:XA(r.exit_code,`${i}.exit_code`),duration_ms:fe(r.duration_ms,`${i}.duration_ms`)}}function o_(e){let t="Native verification",i=at(e,t);ot(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ni(i.checks,`${t}.checks`,a_);Wr(r.map(a=>a.id),`${t}.checks IDs`);let n=Te(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Te(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),attempt:fe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":_e(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:_e(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:zt(i.summary,`${t}.summary`),risks:ni(i.risks,`${t}.risks`,(a,o)=>zt(a,`${t}.risks[${o}]`)),risks_truncated:Mn(i.risks_truncated,`${t}.risks_truncated`),completed_at:Fn(i.completed_at,`${t}.completed_at`)}}function Ww(e,t){let i=`Native history[${t}]`,r=at(e,i);ot(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Yc(r.unresolved_ids,`${i}.unresolved_ids`);return Wr(n,`${i}.unresolved_ids`),{goal_cycle:fe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:fe(r.iteration,`${i}.iteration`),attempt:fe(r.attempt,`${i}.attempt`),outcome:_e(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:zt(r.summary,`${i}.summary`),completed_at:Fn(r.completed_at,`${i}.completed_at`)}}function s_(e){let t="Native history_overflow.outcome_counts",i=at(e,t),r=["pass","fail","blocked","execution-error","recovery"];return ot(i,new Set(r),t),{pass:fe(i.pass,`${t}.pass`),fail:fe(i.fail,`${t}.fail`),blocked:fe(i.blocked,`${t}.blocked`),"execution-error":fe(i["execution-error"],`${t}.execution-error`),recovery:fe(i.recovery,`${t}.recovery`)}}function c_(e){let t="Native history_overflow",i=at(e,t);ot(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=fe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Fn(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Fn(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=s_(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 l_(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 u_(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 nt(e){let t=at(e,"Native portable state");if(ot(t,KA,"Native portable state"),t.schema!==Dn)throw new Error(`Native portable state schema must be ${Dn}`);let i=Te(t.name,"Native state name");if(!zA.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=ni(t.spec_changes,"Native spec_changes",QA);Wr(r.map(s=>s.capability),"Native spec change capabilities");let n=ni(t.acceptance,"Native acceptance",t_);Wr(n.map(s=>s.id),"Native acceptance IDs");let a=ni(t.history,"Native history",Ww);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Dn,name:i,language:_e(t.language,["en","zh-CN"],"Native state language"),phase:_e(t.phase,["shape","build","verify","archive"],"Native state phase"),status:_e(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:fe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:YA(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:ZA(t.workspace),loop:e_(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:r_(t.builder_handoff),blockers:ni(t.blockers,"Native blockers",n_),verification:t.verification===null?null:o_(t.verification),history:a,history_overflow:c_(t.history_overflow),verification_result:_e(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:_e(t.verification_report,["verification.md"],"Native verification_report"),archived:Mn(t.archived,"Native archived"),created_at:Fn(t.created_at,"Native created_at")};return l_(o),u_(o),o}function Ln(e,t){let i=nt(e),r=Ww(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 nt({...i,history:n,history_overflow:a})}function d_(e,t){let i=(0,Kc.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 Ue(e){let t=await WA.readFile(e,"utf8");return nt(d_(t,"Native portable state"))}async function Xc(e,t,i={}){let r=nt(t);await ue(e,(0,Kc.stringify)(r),i)}var Gc=new Map;async function f_(e,t){let i=Gc.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Gc.set(e,a),await i;try{return await t()}finally{r(),Gc.get(e)===a&&Gc.delete(e)}}async function zr(e){return f_(e.file,async()=>{let t=fe(e.expectedStateVersion,"Native expected state version",1),i=nt(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ue(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Uc(t,r.state_version);return await Xc(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ue(e.file);if(n.state_version!==t)throw new Uc(t,n.state_version)}}),i})}function h_(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ir(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(h_(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 ge="comet.native.v3",we="comet.native.v2",Ke="comet.native.v1",rr="comet.native.transition.v3",Si="comet.native.transition.v2",Jr="comet.native.transition.v1";var Qc="comet.native.portable-migration.v1",m_=new Set(["schema","id","change","fromSchema","status","createdAt"]),v_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,g_=/^[a-z0-9][a-z0-9-]{7,127}$/u,w_=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),y_=new Set([Ke,we,ge]);function N_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function b_(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 k_(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 S_(e){return e.schema===Ke?Gr(e):e.schema===we?ai(e):st(e)}function E_(e){return p_.posix.normalize(e.replaceAll("\\","/"))}function P_(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:E_(t.source)})}function R_(e){return e==="shape"?"shape":"build"}function x_(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function C_(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 zw(e){let t=S_(e.state);qw(e.acceptance);let i=R_(t.phase),r=i==="shape"?0:1,n=b_(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 nt({schema:Dn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:P_(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:x_(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:ir(C_(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:zf(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Kf(e){let t=N_(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!m_.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Qc)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!g_.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!v_.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!y_.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!w_.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Qc,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:k_(t.createdAt,"Native portable migration transaction createdAt")}}function Jw(e){switch(Kf(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 Zc="comet.native.archive-transaction.v4",Gw="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",__=new RegExp(`^portable-archive-(${Gw})\\.json$`,"u"),T_=new RegExp(`^portable-migration-(${Gw})\\.json$`,"u"),I_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,j_=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$_=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),O_=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),H_=new Set(["capability","operation","source","content"]),Uw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Kw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yw(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 D_(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Kw(e,i);if(Yw(r,H_,i),typeof r.capability!="string"||!Uw.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 M_(e){let t=Kw(e,"Native portable Archive transaction");if(Yw(t,O_,"Native portable Archive transaction"),t.schema!==Zc)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!I_.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Uw.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"||!j_.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"||!$_.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(D_);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:Zc,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 Ur(e){let t=__.exec(e);if(t)return{kind:"archive",change:t[1]};let i=T_.exec(e);return i?{kind:"migration",change:i[1]}:null}function nr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Ur(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Yf.join(e.transactionsDir,i)}async function Ro(e,t){let i=Ur(t);if(!i)return null;let r=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Yf.join(e.transactionsDir,t);if(i.kind==="archive"){let s=M_(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=Kf(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 el(e,t){let i=nr(e,t);try{return await Ro(e,Yf.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Xw(e){let t;try{t=await A_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Ur(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function Qw(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as xo}from"fs";import Pt from"path";import{TextDecoder as V_}from"util";import{createHash as F_}from"node:crypto";import{constants as tl,promises as z}from"node:fs";import K from"node:path";import{TextDecoder as L_}from"node:util";function qe(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}function Zw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function qn(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ey(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Bn(e,t){return W({...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 ar(e,t){let i=await z.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function or(e,t,i){let r=K.resolve(e),n=K.resolve(t);if(!qe(r,n))throw new Error(`${i} is outside its managed root`);let a=[await ar(r,i)],o=r;for(let s of K.relative(r,n).split(K.sep).filter(Boolean)){await ve(a,i),o=K.join(o,s);let c=await ar(o,i);if(!qe(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ve(a,i),a}async function ve(e,t){for(let i of e){let r=await z.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!qn(i,r)||await z.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function B_(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 ie(e){let t=Zw(e.maxBytes),i=K.resolve(e.file),r=await or(e.root,K.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>ar(K.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ve(r,e.label);let a=await z.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=ey(a),s=await z.realpath(i);if(!qe(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>qe(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?tl.O_RDONLY:tl.O_RDONLY|tl.O_NOFOLLOW|tl.O_NONBLOCK,l=await z.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Bn(o,u)||!Bn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await B_(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Bn(o,v)||!Bn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:F_("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function il(e){let t=await ie(e),i;try{i=new L_("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function pt(e){let t=await or(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await z.readdir(e.directory,{withFileTypes:!0});else{let r=Zw(e.maxEntries);i=[];let n=await z.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ve(t,e.label),{entries:i,verify:()=>ve(t,e.label)}}async function Jt(e){let t=await or(e.root,e.directory,e.label);return{verify:()=>ve(t,e.label)}}async function q_(e){let t=K.resolve(e.directory),i=K.resolve(e.quarantine);if(K.dirname(i)!==K.dirname(t)||!qe(K.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await or(e.root,K.dirname(t),e.label),n=await ar(t,e.label);if(!qe(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ve(r,e.label);let a=await z.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!qn(n,a)||await z.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await z.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await z.rename(t,i),await ve(r,e.label);let o=await z.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!qn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await z.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function ty(e){await q_(e)}async function rl(e){let t=K.resolve(e.file),i=await or(e.root,K.dirname(t),e.label),r=await z.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=ey(r),a=await z.realpath(t);if(!qe(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Bn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ve(i,e.label);let[l,u]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Bn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await z.rm(t),await ve(i,e.label)}async function Xf(e){let t=K.resolve(e.directory),i=await or(e.root,K.dirname(t),e.label),r=await ar(t,e.label);if(!qe(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ve(i,e.label);let n=await z.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!qn(r,n)||await z.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await z.rmdir(t),await ve(i,e.label)}async function oi(e){let t=K.resolve(e.root),i=K.resolve(e.directory);if(!qe(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await ar(t,e.label)],n=t;for(let a of K.relative(t,i).split(K.sep).filter(Boolean)){await ve(r,e.label),n=K.join(n,a);try{await z.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await ar(n,e.label);if(!qe(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await ve(r,e.label)}async function Qf(e){let t=K.resolve(e.root),i=K.resolve(e.source),r=K.resolve(e.target);if(i===r||!qe(t,i)||!qe(t,r)||qe(i,r)||qe(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await oi({root:t,directory:K.dirname(r),label:`${e.label} target parent`});let n=await or(t,K.dirname(i),e.label),a=await or(t,K.dirname(r),e.label),o=await ar(i,e.label);if(!qe(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await z.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ve(n,e.label),ve(a,e.label)]);let s=await z.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!qn(o,s)||await z.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await z.rename(i,r),await Promise.all([ve(n,e.label),ve(a,e.label)]);let c=await z.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!qn(o,c)||!qe(n[0].realPath,await z.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await z.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function sr(e){let t=await ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await ow(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await z.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var W_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),z_=new Set(["id","type","source","target","staged","backup"]),J_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),G_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),U_=new Set(["sequence","timestamp","type","operationId"]),ay=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),oy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),K_=256*1024,Y_=1024*1024,sy=16*1024,al=1024,th=64*1024*1024,X_=2e4,cy=new V_("utf-8",{fatal:!0});function Co(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ao(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 Wn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Zf(e,t){if(typeof e!="string"||e.length===0||Pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function nl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function iy(e,t){if(Zf(e,t),e.includes("\\")||e!==Pt.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 Q_(e,t){let i=Co(e,`transaction operations[${t}]`);if(Ao(i,z_,`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`);Zf(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Zf(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 sl(e){let t=Co(e,"Native Archive transaction journal");if(Ao(t,J_,"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"||!ay.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(!Wn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(nl(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=Co(s,`Archive transaction operations[${c}]`);if(Ao(l,G_,`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`);iy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&iy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&nl(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(nl(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`);nl(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 ih(e){let t=Co(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return sl(t);if(Ao(t,W_,"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"||!ay.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Pt.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(!Wn(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(Q_),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 ly(e,t){let i=Co(e,`Native transaction event at line ${t}`);if(Ao(i,U_,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Wn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!oy.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function Z_(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;rString(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Wn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Wn(e)}function Vn(e,t){return e.lengthsy)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Vn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!Z_(n))return!1;if(r.length<24)return!0;if(!Wn(n))return!1;let a='","type":"',o=r.slice(24);if(Vn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of oy){if(Vn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(eT(l))return!0}else if(Vn(l,'"}'))return!0}return!1}function iT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>sy)throw new Error(`Native transaction event at line ${t} is too large`);return ly(JSON.parse(e),t)}function rT(e){let t=e.split(` -`),i=t.at(-1)==="";if(i&&t.pop(),t.length>al)throw new Error(`Native transaction event log exceeds ${al} events`);let r=[];for(let n=0;nJSON.stringify(t)).join(` +`),o.context,r)),o=null}};for(let{line:c,body:l}of Hn(e)){let u=l?qf(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=So(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,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(),Wf(n,"Specification",r)}function zc(e,t="spec.md",i=Eo.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(Vf("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:d}of Hn(e)){let f=d?qf(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Bf(u,null)!==null||p.startsWith(""||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(),Wf(n,"Specification mandatory requirements",r)}function FA(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||DA(i)||Iw.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=Iw.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!_A.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function LA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!AA.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Fw(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=LA(i,r),a=n.acceptance_id;if(typeof a!="string"||!CA.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return FA(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Lw(e){let t=HA(e);if(t.some(({line:l,body:u})=>!u&&(l===jw||l===$w)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===jw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===$w?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(` +`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Fw(o),c=BA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function BA(e){let t=Fw([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var qA=/^A[1-9]\d*$/u;function qw(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Bw.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Bw.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function VA(e,t){return e.localeCompare(t,"en")}function Jc(e){let t=qw(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>VA(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=Vc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=qw(a.source,`Native spec source for ${a.capability}`);r.push(...Wc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...zc(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=So(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 Vw(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}var Kc=hn(Lr(),1);import{promises as WA}from"node:fs";var Dn="comet.native.v4",Po="comet.native.local-execution.v4";function zf(){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 zA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GA=/^A[1-9][0-9]*$/u,UA=/^[a-f0-9]{64}$/u,KA=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"]),Uc=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 at(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ot(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 Te(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 Gf(e,t){return e===null?null:Te(e,t)}function YA(e,t){let i=Te(e,t);if(!UA.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Mn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function fe(e,t,i=0){if(!Number.isSafeInteger(e)||ei(r,n))}function Yc(e,t){return ni(e,t,(i,r)=>Te(i,`${t}[${r}]`))}function Wr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Fn(e,t){let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Uf(e,t,i=!1){let r=Te(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 zt(e,t){let i=at(e,t);return ot(i,new Set(["text","truncated"]),t),{text:Te(i.text,`${t}.text`,{empty:!0}),truncated:Mn(i.truncated,`${t}.truncated`)}}function QA(e,t){let i=`Native spec_changes[${t}]`,r=at(e,i);ot(r,new Set(["capability","operation","source"]),i);let n=Te(r.capability,`${i}.capability`);if(!JA.test(n))throw new Error(`${i}.capability is invalid`);let a=_e(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Uf(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 ZA(e){let t="Native workspace",i=at(e,t);ot(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=_e(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Gf(i.change_branch,`${t}.change_branch`),a=Gf(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:_e(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 e_(e){let t="Native loop",i=at(e,t);ot(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=Yc(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Wr(r,`${t}.previous_unresolved_ids`),{stage:_e(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:fe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:fe(i.iteration,`${t}.iteration`),attempt:fe(i.attempt,`${t}.attempt`),retry_epoch:fe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:fe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:fe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:fe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Gf(i.next_action,`${t}.next_action`)}}function t_(e,t){let i=`Native acceptance[${t}]`,r=at(e,i);ot(r,new Set(["id","source","text","result","reason"]),i);let n=Te(r.id,`${i}.id`);if(!GA.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Uf(r.source,`${i}.source`),text:Te(r.text,`${i}.text`),result:_e(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:zt(r.reason,`${i}.reason`)}}function i_(e,t){let i=`Native builder_handoff.checks[${t}]`,r=at(e,i);return ot(r,new Set(["name","result","note"]),i),{name:zt(r.name,`${i}.name`),result:_e(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:zt(r.note,`${i}.note`)}}function r_(e){let t="Native builder_handoff",i=at(e,t);ot(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=Yc(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Wr(r,`${t}.addressed_acceptance_ids`),{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:Te(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Te(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),summary:zt(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ni(i.checks,`${t}.checks`,i_),checks_truncated:Mn(i.checks_truncated,`${t}.checks_truncated`),known_limits:ni(i.known_limits,`${t}.known_limits`,(n,a)=>zt(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Mn(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Fn(i.submitted_at,`${t}.submitted_at`)}}function n_(e,t){let i=`Native blockers[${t}]`,r=at(e,i);ot(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Yc(r.acceptance_ids,`${i}.acceptance_ids`);return Wr(n,`${i}.acceptance_ids`),{owner:_e(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:zt(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:_e(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function a_(e,t){let i=`Native verification.checks[${t}]`,r=at(e,i);return ot(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Te(r.id,`${i}.id`),name:zt(r.name,`${i}.name`),argv_display:ni(r.argv_display,`${i}.argv_display`,(n,a)=>zt(n,`${i}.argv_display[${a}]`)),argv_truncated:Mn(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Uf(r.cwd_ref,`${i}.cwd_ref`,!0),status:_e(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:XA(r.exit_code,`${i}.exit_code`),duration_ms:fe(r.duration_ms,`${i}.duration_ms`)}}function o_(e){let t="Native verification",i=at(e,t);ot(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ni(i.checks,`${t}.checks`,a_);Wr(r.map(a=>a.id),`${t}.checks IDs`);let n=Te(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Te(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),attempt:fe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":_e(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:_e(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:zt(i.summary,`${t}.summary`),risks:ni(i.risks,`${t}.risks`,(a,o)=>zt(a,`${t}.risks[${o}]`)),risks_truncated:Mn(i.risks_truncated,`${t}.risks_truncated`),completed_at:Fn(i.completed_at,`${t}.completed_at`)}}function zw(e,t){let i=`Native history[${t}]`,r=at(e,i);ot(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Yc(r.unresolved_ids,`${i}.unresolved_ids`);return Wr(n,`${i}.unresolved_ids`),{goal_cycle:fe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:fe(r.iteration,`${i}.iteration`),attempt:fe(r.attempt,`${i}.attempt`),outcome:_e(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:zt(r.summary,`${i}.summary`),completed_at:Fn(r.completed_at,`${i}.completed_at`)}}function s_(e){let t="Native history_overflow.outcome_counts",i=at(e,t),r=["pass","fail","blocked","execution-error","recovery"];return ot(i,new Set(r),t),{pass:fe(i.pass,`${t}.pass`),fail:fe(i.fail,`${t}.fail`),blocked:fe(i.blocked,`${t}.blocked`),"execution-error":fe(i["execution-error"],`${t}.execution-error`),recovery:fe(i.recovery,`${t}.recovery`)}}function c_(e){let t="Native history_overflow",i=at(e,t);ot(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=fe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Fn(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Fn(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=s_(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 l_(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 u_(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 nt(e){let t=at(e,"Native portable state");if(ot(t,KA,"Native portable state"),t.schema!==Dn)throw new Error(`Native portable state schema must be ${Dn}`);let i=Te(t.name,"Native state name");if(!zA.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=ni(t.spec_changes,"Native spec_changes",QA);Wr(r.map(s=>s.capability),"Native spec change capabilities");let n=ni(t.acceptance,"Native acceptance",t_);Wr(n.map(s=>s.id),"Native acceptance IDs");let a=ni(t.history,"Native history",zw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Dn,name:i,language:_e(t.language,["en","zh-CN"],"Native state language"),phase:_e(t.phase,["shape","build","verify","archive"],"Native state phase"),status:_e(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:fe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:YA(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:ZA(t.workspace),loop:e_(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:r_(t.builder_handoff),blockers:ni(t.blockers,"Native blockers",n_),verification:t.verification===null?null:o_(t.verification),history:a,history_overflow:c_(t.history_overflow),verification_result:_e(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:_e(t.verification_report,["verification.md"],"Native verification_report"),archived:Mn(t.archived,"Native archived"),created_at:Fn(t.created_at,"Native created_at")};return l_(o),u_(o),o}function Ln(e,t){let i=nt(e),r=zw(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 nt({...i,history:n,history_overflow:a})}function d_(e,t){let i=(0,Kc.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 Ue(e){let t=await WA.readFile(e,"utf8");return nt(d_(t,"Native portable state"))}async function Xc(e,t,i={}){let r=nt(t);await ue(e,(0,Kc.stringify)(r),i)}var Gc=new Map;async function f_(e,t){let i=Gc.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Gc.set(e,a),await i;try{return await t()}finally{r(),Gc.get(e)===a&&Gc.delete(e)}}async function zr(e){return f_(e.file,async()=>{let t=fe(e.expectedStateVersion,"Native expected state version",1),i=nt(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ue(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Uc(t,r.state_version);return await Xc(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ue(e.file);if(n.state_version!==t)throw new Uc(t,n.state_version)}}),i})}function h_(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ir(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(h_(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 ge="comet.native.v3",we="comet.native.v2",Ke="comet.native.v1",rr="comet.native.transition.v3",Si="comet.native.transition.v2",Jr="comet.native.transition.v1";var Qc="comet.native.portable-migration.v1",m_=new Set(["schema","id","change","fromSchema","status","createdAt"]),v_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,g_=/^[a-z0-9][a-z0-9-]{7,127}$/u,w_=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),y_=new Set([Ke,we,ge]);function N_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function b_(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 k_(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 S_(e){return e.schema===Ke?Gr(e):e.schema===we?ai(e):st(e)}function E_(e){return p_.posix.normalize(e.replaceAll("\\","/"))}function P_(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:E_(t.source)})}function R_(e){return e==="shape"?"shape":"build"}function x_(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function C_(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 Jw(e){let t=S_(e.state);Vw(e.acceptance);let i=R_(t.phase),r=i==="shape"?0:1,n=b_(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 nt({schema:Dn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:P_(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:x_(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:ir(C_(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:zf(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Kf(e){let t=N_(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!m_.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Qc)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!g_.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!v_.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!y_.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!w_.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Qc,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:k_(t.createdAt,"Native portable migration transaction createdAt")}}function Gw(e){switch(Kf(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 Zc="comet.native.archive-transaction.v4",Uw="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",__=new RegExp(`^portable-archive-(${Uw})\\.json$`,"u"),T_=new RegExp(`^portable-migration-(${Uw})\\.json$`,"u"),I_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,j_=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$_=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),O_=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),H_=new Set(["capability","operation","source","content"]),Kw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Yw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xw(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 D_(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Yw(e,i);if(Xw(r,H_,i),typeof r.capability!="string"||!Kw.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 M_(e){let t=Yw(e,"Native portable Archive transaction");if(Xw(t,O_,"Native portable Archive transaction"),t.schema!==Zc)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!I_.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Kw.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"||!j_.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"||!$_.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(D_);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:Zc,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 Ur(e){let t=__.exec(e);if(t)return{kind:"archive",change:t[1]};let i=T_.exec(e);return i?{kind:"migration",change:i[1]}:null}function nr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Ur(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Yf.join(e.transactionsDir,i)}async function Ro(e,t){let i=Ur(t);if(!i)return null;let r=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Yf.join(e.transactionsDir,t);if(i.kind==="archive"){let s=M_(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=Kf(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 el(e,t){let i=nr(e,t);try{return await Ro(e,Yf.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Qw(e){let t;try{t=await A_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Ur(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function Zw(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as xo}from"fs";import Pt from"path";import{TextDecoder as V_}from"util";import{createHash as F_}from"node:crypto";import{constants as tl,promises as z}from"node:fs";import K from"node:path";import{TextDecoder as L_}from"node:util";function qe(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}function ey(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function qn(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ty(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Bn(e,t){return W({...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 ar(e,t){let i=await z.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function or(e,t,i){let r=K.resolve(e),n=K.resolve(t);if(!qe(r,n))throw new Error(`${i} is outside its managed root`);let a=[await ar(r,i)],o=r;for(let s of K.relative(r,n).split(K.sep).filter(Boolean)){await ve(a,i),o=K.join(o,s);let c=await ar(o,i);if(!qe(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ve(a,i),a}async function ve(e,t){for(let i of e){let r=await z.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!qn(i,r)||await z.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function B_(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 ie(e){let t=ey(e.maxBytes),i=K.resolve(e.file),r=await or(e.root,K.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>ar(K.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ve(r,e.label);let a=await z.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=ty(a),s=await z.realpath(i);if(!qe(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>qe(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?tl.O_RDONLY:tl.O_RDONLY|tl.O_NOFOLLOW|tl.O_NONBLOCK,l=await z.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Bn(o,u)||!Bn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await B_(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Bn(o,v)||!Bn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:F_("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function il(e){let t=await ie(e),i;try{i=new L_("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function pt(e){let t=await or(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await z.readdir(e.directory,{withFileTypes:!0});else{let r=ey(e.maxEntries);i=[];let n=await z.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ve(t,e.label),{entries:i,verify:()=>ve(t,e.label)}}async function Jt(e){let t=await or(e.root,e.directory,e.label);return{verify:()=>ve(t,e.label)}}async function q_(e){let t=K.resolve(e.directory),i=K.resolve(e.quarantine);if(K.dirname(i)!==K.dirname(t)||!qe(K.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await or(e.root,K.dirname(t),e.label),n=await ar(t,e.label);if(!qe(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ve(r,e.label);let a=await z.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!qn(n,a)||await z.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await z.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await z.rename(t,i),await ve(r,e.label);let o=await z.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!qn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await z.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function iy(e){await q_(e)}async function rl(e){let t=K.resolve(e.file),i=await or(e.root,K.dirname(t),e.label),r=await z.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=ty(r),a=await z.realpath(t);if(!qe(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Bn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ve(i,e.label);let[l,u]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Bn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await z.rm(t),await ve(i,e.label)}async function Xf(e){let t=K.resolve(e.directory),i=await or(e.root,K.dirname(t),e.label),r=await ar(t,e.label);if(!qe(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ve(i,e.label);let n=await z.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!qn(r,n)||await z.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await z.rmdir(t),await ve(i,e.label)}async function oi(e){let t=K.resolve(e.root),i=K.resolve(e.directory);if(!qe(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await ar(t,e.label)],n=t;for(let a of K.relative(t,i).split(K.sep).filter(Boolean)){await ve(r,e.label),n=K.join(n,a);try{await z.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await ar(n,e.label);if(!qe(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await ve(r,e.label)}async function Qf(e){let t=K.resolve(e.root),i=K.resolve(e.source),r=K.resolve(e.target);if(i===r||!qe(t,i)||!qe(t,r)||qe(i,r)||qe(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await oi({root:t,directory:K.dirname(r),label:`${e.label} target parent`});let n=await or(t,K.dirname(i),e.label),a=await or(t,K.dirname(r),e.label),o=await ar(i,e.label);if(!qe(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await z.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ve(n,e.label),ve(a,e.label)]);let s=await z.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!qn(o,s)||await z.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await z.rename(i,r),await Promise.all([ve(n,e.label),ve(a,e.label)]);let c=await z.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!qn(o,c)||!qe(n[0].realPath,await z.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await z.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function sr(e){let t=await ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await sw(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await z.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var W_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),z_=new Set(["id","type","source","target","staged","backup"]),J_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),G_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),U_=new Set(["sequence","timestamp","type","operationId"]),oy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),sy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),K_=256*1024,Y_=1024*1024,cy=16*1024,al=1024,th=64*1024*1024,X_=2e4,ly=new V_("utf-8",{fatal:!0});function Co(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ao(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 Wn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Zf(e,t){if(typeof e!="string"||e.length===0||Pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function nl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function ry(e,t){if(Zf(e,t),e.includes("\\")||e!==Pt.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 Q_(e,t){let i=Co(e,`transaction operations[${t}]`);if(Ao(i,z_,`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`);Zf(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Zf(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 sl(e){let t=Co(e,"Native Archive transaction journal");if(Ao(t,J_,"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"||!oy.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(!Wn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(nl(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=Co(s,`Archive transaction operations[${c}]`);if(Ao(l,G_,`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`);ry(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&ry(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&nl(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(nl(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`);nl(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 ih(e){let t=Co(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return sl(t);if(Ao(t,W_,"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"||!oy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Pt.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(!Wn(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(Q_),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 uy(e,t){let i=Co(e,`Native transaction event at line ${t}`);if(Ao(i,U_,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Wn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!sy.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function Z_(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;rString(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Wn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Wn(e)}function Vn(e,t){return e.lengthcy)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Vn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!Z_(n))return!1;if(r.length<24)return!0;if(!Wn(n))return!1;let a='","type":"',o=r.slice(24);if(Vn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of sy){if(Vn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(eT(l))return!0}else if(Vn(l,'"}'))return!0}return!1}function iT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>cy)throw new Error(`Native transaction event at line ${t} is too large`);return uy(JSON.parse(e),t)}function rT(e){let t=e.split(` +`),i=t.at(-1)==="";if(i&&t.pop(),t.length>al)throw new Error(`Native transaction event log exceeds ${al} events`);let r=[];for(let n=0;nJSON.stringify(t)).join(` `)} -`}function nT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Pt.join(e.transactionsDir,t)}function cl(e,t){let i=nT(e,t);return{directory:i,journal:Pt.join(i,"transaction.json"),events:Pt.join(i,"events.jsonl"),staged:Pt.join(i,"staged"),backups:Pt.join(i,"backups")}}async function si(e,t){let i=cl(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function aT(e,t){if(t.length===0||Pt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=Pt.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function cr(e,t){let i=aT(e,t);return T(j(e,i),i)}async function Kr(e){try{return await xo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function rh(e,t,i={}){let r=await si(e,t);try{await xo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ie({root:e.runtimeDir,file:r.events,maxBytes:Y_,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=cy.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=rT(a),s=uy(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function ry(e,t,i){let r=await rh(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Rt(e,t,i,r){let n=await si(e,t),a=await rh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await ue(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>ry(e,t,a)}),o;if(a.events.length>=al)throw new Error(`Native transaction event log ${t} exceeds ${al} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return ly(s,s.sequence),await xo.mkdir(n.directory,{recursive:!0}),await ue(n.events,uy([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>ry(e,t,a)}),s}async function dy(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=ih(t);let i=await si(e,t.id);await xo.mkdir(i.staged,{recursive:!0}),await xo.mkdir(i.backups,{recursive:!0}),await te(i.journal,t,{containedRoot:e.runtimeDir}),await Rt(e,t.id,"prepared")}async function mt(e,t,i={}){let r=await si(e,t),n=await ie({root:e.runtimeDir,file:r.journal,maxBytes:K_,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(cy.decode(n.bytes)),o=ih(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function lr(e,t,i={}){return(await rh(e,t,i)).events}async function ol(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=ih({...t,status:i});return await te((await si(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function eh(e,t,i){try{return await ie({root:j(e,t),file:t,maxBytes:th,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function nh(e,t,i,r){let n=await eh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await eh(e,i,`${r} target`);await oi({root:j(e,i),directory:Pt.dirname(i),label:`${r} target parent`}),await sr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:th,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function fy(e,t,i){let r=await eh(e,t,i);r&&await rl({root:j(e,t),file:t,maxBytes:th,expectedHash:r.hash,expectedSize:r.size,label:i})}async function ny(e,t){if(!t.backup)return;let i=await cr(e,t.target),r=await cr(e,t.backup);!await Kr(i)||await Kr(r)||await nh(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function oT(e,t){let i=await cr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await ny(e,t),await nh(e,await cr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await ny(e,t),await fy(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await cr(e,t.source),[n,a]=await Promise.all([Kr(r),Kr(i)]);if(!n&&a){await(await pt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:X_})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Qf({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function hy(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await ol(e,t,"applying"):t,n=await lr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Rt(e,r.id,"operation-started",s.id),await oT(e,s),await Rt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await mt(e,r.id),r}async function sT(e,t){let i=await cr(e,t.target),r=t.backup?await cr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await cr(e,t.source);if(await Kr(i)){if(await Kr(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Qf({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Kr(r)?await nh(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await fy(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function ll(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await lr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await ol(e,t,"rolling-back");await Rt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await sT(e,a);return await Rt(e,r.id,"rollback-completed"),r=await ol(e,r,"rolled-back"),r}async function zn(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Rt(e,t.id,i),i==="commit"?ol(e,t,"committed"):t}async function uT(e,t,i){let r;try{r=await cT.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 mt(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(Ur(n.name))try{let a=await Ro(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Qw(a))return!0}catch{return!0}return!1}async function dT(e,t){let i=Date.now()+5e3,r=lT.join(e.locksDir,"root-move.lock");for(;;)try{return await er(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bo(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 he(e,t,i,r){let n=await dT(e,t);try{if(await $n(e.projectRoot),await uT(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await tr(n)}}function py(e){return Number.isSafeInteger(e)&&e>=1}async function my(e){if(!py(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!py(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as pl}from"crypto";import{spawn as Py}from"node:child_process";import{promises as oe}from"fs";import q from"path";import{createHash as vy}from"crypto";import{createReadStream as fT}from"fs";async function Gt(e){let t=vy("sha256");for await(let i of fT(e))t.update(i);return t.digest("hex")}function F(e){return vy("sha256").update(e).digest("hex")}var ul={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},uh=1e3,hT=8*1024*1024,pT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mT=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),vT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),gT=new Set(["schema","include","exclude","hash"]),wT=new Set(["provider","gitSelection","physicalSelection","projection"]),yT=new Set(["provider","selection"]),NT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),bT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),kT=new Set(["schema","status","before","after"]),ST=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),ET=new Set(["path","hash","size","type","gitObjectId"]),PT=new Set(["path","size","type","reason"]),RT=new Set(["ref","hash","count"]),xT=new Set(["change-created","legacy-migration","explicit"]),CT=new Set(["file","directory","other"]),AT=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),ml=/^[a-f0-9]{64}$/u,Ry=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,_T=new Set(["EACCES","EPERM"]),Yn=64*1024,ch=64*1024,TT=6e4,IT=1e3,jT=2,dh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},$T={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function xy(e){let t=e.deadlineMs??TT;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ut(e){return Math.max(0,e.deadlineAt-Date.now())}function L(e){return Ut(e)>=1}function ah(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Un(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function OT(e){let t={...$T,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function HT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&q.win32.isAbsolute(r)?q.win32.resolve(r):"C:\\Windows",a=q.win32.join(n,"System32","taskkill.exe");if(!q.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=Py(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),IT),u.unref()}catch{d(!1)}});for(let s=0;s{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=HT(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?ah(v.error):ah()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Cy(e){let t={...dh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function dl(e,t,i,r=ch){let{child:n,completion:a}=fh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=Yn)return;let v=Yn-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function oh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function To(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=fh(e,t,i,r.stdin!==void 0),c=[],l=pl("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,N=!1,y=!1,E=S=>{let k=0;for(;k0&&(h.byteLength+w.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,N=!0):h=Buffer.concat([h,w])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let g=h.byteLength+1;!m&&v<=r.maxRecords&&p+g<=r.maxBytes?(c.push(h),p+=g):N=!0,h=Buffer.alloc(0),m=!1,k=b+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(N=!0);let k=r.outputChunkBytes;if(k===void 0){E(S);return}for(let b=0;b{if(d>=Yn)return;let k=Yn-d,b=Buffer.from(S).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(S!==null&&b.includes(S)&&k===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:N,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function fl(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function DT(e,t,i){if(i.length===0)return new Set;let r=await To(e,t,["check-ignore","--no-index","-z","--stdin"],{...dh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=fl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function MT(e,t,i){let{child:r,completion:n}=fh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Yn)return;let d=Yn-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Kn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||q.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||q.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function FT(e,t){return e.map(i=>{let r=Kn(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function LT(e){let t=q.resolve(e);for(;;){try{return await oe.lstat(q.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=q.dirname(t);if(i===t)return!1;t=i}}async function Ay(e,t,i,r={}){let n=q.resolve(t.projectRoot),a=q.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=q.relative(n,q.resolve(f)).replaceAll("\\","/"),v=Kn(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await To(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await To(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await To(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function _y(e){return{stageBefore:oh(e.stagedBefore),combined:oh(e.combined),stageAfter:oh(e.stagedAfter)}}async function Ty(e,t,i=dh,r={}){let n=q.resolve(t.projectRoot);if(!await LT(n))return null;let a;try{a=await dl(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Un(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Ay(e,t,i,r)}catch(y){throw Un(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let E of y){let S=fl(E),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?[0-7]{6}) (?[a-f0-9]{40}|[a-f0-9]{64}) (?[0-3])$/u.exec(S.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Kn(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};p(s.records),p(l.records);let v=c.records.map(fl),h=FT(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),N=new Set(h.filter((y,E)=>!u.has(y)&&v[E].endsWith("/")));for(let y of f)N.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:N,omissions:[],overflow:null,evidence:null,initialFence:_y(o)}}function dr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function gy(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function BT(e,t){return!dr(e.stageBefore,e.stageAfter)||!dr(e.stageAfter,t.stageBefore)||!dr(e.combined,t.combined)||!dr(t.stageBefore,t.stageAfter)}async function Iy(e,t,i,r,n){let a;try{a=await Ay(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Un(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=_y(a),c=gy(o)||gy(s),l=BT(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:F(`comet.native.git-selection-overflow.v2 -${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var qT=(1n<<256n)-1n;function VT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function wy(e){let t=q.resolve(e.paths.projectRoot),i=q.resolve(e.paths.nativeRoot),r=q.resolve(e.paths.runtimeDir),n=q.resolve(e.paths.configFile),a=q.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>Ut(e.execution)>=1?!0:(p=!0,h=!0,!1),N=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),b=pl("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;Re.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(S)},y=async S=>{if(h||!m())return;let k;try{k=await oe.opendir(S)}catch(P){if(!m())return;if(!ke(P)&&!be(P)||S===t&&ke(P))throw P;v||=be(P),p||=ke(P),h=!0;return}if(!m()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let b=!1,R;try{for(;!h&&m();){let P;try{P=await k.read()}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z)||S===t&&ke(Z))throw Z;v||=be(Z),p||=ke(Z),h=!0;break}if(!m()||P===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let D=q.join(S,P.name),O=zT(t,D);if(D===n||D===a||Kt(i,D)||Kt(r,D)||e.denylist.some(Z=>Kt(Z,D))||ii(O)!==null)continue;if(!m())break;let De;try{De=await oe.lstat(D)}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z))throw Z;if(v=!0,N({path:O,type:"other"}),s.push({path:O,size:null,type:"file",reason:ke(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;let ce=VT(De);if(ce==="directory"){if(KT(e.policy,O))continue;if(!m())break;let Z;try{Z=await oe.realpath(D)}catch(Zt){if(!m())break;if(!ke(Zt)&&!be(Zt))throw Zt;if(v=!0,N({path:O,type:ce}),s.push({path:O,size:null,type:"directory",reason:ke(Zt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;if(!$(e.physicalProjectRoot,Z)||Kt(e.physicalNativeRoot,Z))continue;if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||(await y(D),h))break;continue}if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||h)break}}catch(P){b=!0,R=P}let w;try{await k.close()}catch(P){w=P}let g=m();if(b)throw R;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let E=p?F(`comet.native.physical-selection-incomplete.v1 +`}function nT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Pt.join(e.transactionsDir,t)}function cl(e,t){let i=nT(e,t);return{directory:i,journal:Pt.join(i,"transaction.json"),events:Pt.join(i,"events.jsonl"),staged:Pt.join(i,"staged"),backups:Pt.join(i,"backups")}}async function si(e,t){let i=cl(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function aT(e,t){if(t.length===0||Pt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=Pt.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function cr(e,t){let i=aT(e,t);return T(j(e,i),i)}async function Kr(e){try{return await xo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function rh(e,t,i={}){let r=await si(e,t);try{await xo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ie({root:e.runtimeDir,file:r.events,maxBytes:Y_,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=ly.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=rT(a),s=dy(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function ny(e,t,i){let r=await rh(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Rt(e,t,i,r){let n=await si(e,t),a=await rh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await ue(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>ny(e,t,a)}),o;if(a.events.length>=al)throw new Error(`Native transaction event log ${t} exceeds ${al} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return uy(s,s.sequence),await xo.mkdir(n.directory,{recursive:!0}),await ue(n.events,dy([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>ny(e,t,a)}),s}async function fy(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=ih(t);let i=await si(e,t.id);await xo.mkdir(i.staged,{recursive:!0}),await xo.mkdir(i.backups,{recursive:!0}),await te(i.journal,t,{containedRoot:e.runtimeDir}),await Rt(e,t.id,"prepared")}async function mt(e,t,i={}){let r=await si(e,t),n=await ie({root:e.runtimeDir,file:r.journal,maxBytes:K_,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(ly.decode(n.bytes)),o=ih(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function lr(e,t,i={}){return(await rh(e,t,i)).events}async function ol(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=ih({...t,status:i});return await te((await si(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function eh(e,t,i){try{return await ie({root:j(e,t),file:t,maxBytes:th,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function nh(e,t,i,r){let n=await eh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await eh(e,i,`${r} target`);await oi({root:j(e,i),directory:Pt.dirname(i),label:`${r} target parent`}),await sr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:th,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function hy(e,t,i){let r=await eh(e,t,i);r&&await rl({root:j(e,t),file:t,maxBytes:th,expectedHash:r.hash,expectedSize:r.size,label:i})}async function ay(e,t){if(!t.backup)return;let i=await cr(e,t.target),r=await cr(e,t.backup);!await Kr(i)||await Kr(r)||await nh(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function oT(e,t){let i=await cr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await ay(e,t),await nh(e,await cr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await ay(e,t),await hy(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await cr(e,t.source),[n,a]=await Promise.all([Kr(r),Kr(i)]);if(!n&&a){await(await pt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:X_})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Qf({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function py(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await ol(e,t,"applying"):t,n=await lr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Rt(e,r.id,"operation-started",s.id),await oT(e,s),await Rt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await mt(e,r.id),r}async function sT(e,t){let i=await cr(e,t.target),r=t.backup?await cr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await cr(e,t.source);if(await Kr(i)){if(await Kr(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Qf({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Kr(r)?await nh(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await hy(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function ll(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await lr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await ol(e,t,"rolling-back");await Rt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await sT(e,a);return await Rt(e,r.id,"rollback-completed"),r=await ol(e,r,"rolled-back"),r}async function zn(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Rt(e,t.id,i),i==="commit"?ol(e,t,"committed"):t}async function uT(e,t,i){let r;try{r=await cT.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 mt(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(Ur(n.name))try{let a=await Ro(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Zw(a))return!0}catch{return!0}return!1}async function dT(e,t){let i=Date.now()+5e3,r=lT.join(e.locksDir,"root-move.lock");for(;;)try{return await er(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bo(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 he(e,t,i,r){let n=await dT(e,t);try{if(await $n(e.projectRoot),await uT(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await tr(n)}}function my(e){return Number.isSafeInteger(e)&&e>=1}async function vy(e){if(!my(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!my(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as pl}from"crypto";import{spawn as Ry}from"node:child_process";import{promises as oe}from"fs";import q from"path";import{createHash as gy}from"crypto";import{createReadStream as fT}from"fs";async function Gt(e){let t=gy("sha256");for await(let i of fT(e))t.update(i);return t.digest("hex")}function F(e){return gy("sha256").update(e).digest("hex")}var ul={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},uh=1e3,hT=8*1024*1024,pT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mT=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),vT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),gT=new Set(["schema","include","exclude","hash"]),wT=new Set(["provider","gitSelection","physicalSelection","projection"]),yT=new Set(["provider","selection"]),NT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),bT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),kT=new Set(["schema","status","before","after"]),ST=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),ET=new Set(["path","hash","size","type","gitObjectId"]),PT=new Set(["path","size","type","reason"]),RT=new Set(["ref","hash","count"]),xT=new Set(["change-created","legacy-migration","explicit"]),CT=new Set(["file","directory","other"]),AT=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),ml=/^[a-f0-9]{64}$/u,xy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,_T=new Set(["EACCES","EPERM"]),Yn=64*1024,ch=64*1024,TT=6e4,IT=1e3,jT=2,dh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},$T={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Cy(e){let t=e.deadlineMs??TT;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ut(e){return Math.max(0,e.deadlineAt-Date.now())}function L(e){return Ut(e)>=1}function ah(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Un(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function OT(e){let t={...$T,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function HT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&q.win32.isAbsolute(r)?q.win32.resolve(r):"C:\\Windows",a=q.win32.join(n,"System32","taskkill.exe");if(!q.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=Ry(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),IT),u.unref()}catch{d(!1)}});for(let s=0;s{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=HT(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?ah(v.error):ah()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Ay(e){let t={...dh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function dl(e,t,i,r=ch){let{child:n,completion:a}=fh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=Yn)return;let v=Yn-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function oh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function To(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=fh(e,t,i,r.stdin!==void 0),c=[],l=pl("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,N=!1,y=!1,E=S=>{let k=0;for(;k0&&(h.byteLength+w.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,N=!0):h=Buffer.concat([h,w])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let g=h.byteLength+1;!m&&v<=r.maxRecords&&p+g<=r.maxBytes?(c.push(h),p+=g):N=!0,h=Buffer.alloc(0),m=!1,k=b+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(N=!0);let k=r.outputChunkBytes;if(k===void 0){E(S);return}for(let b=0;b{if(d>=Yn)return;let k=Yn-d,b=Buffer.from(S).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(S!==null&&b.includes(S)&&k===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:N,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function fl(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function DT(e,t,i){if(i.length===0)return new Set;let r=await To(e,t,["check-ignore","--no-index","-z","--stdin"],{...dh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=fl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function MT(e,t,i){let{child:r,completion:n}=fh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Yn)return;let d=Yn-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Kn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||q.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||q.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function FT(e,t){return e.map(i=>{let r=Kn(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function LT(e){let t=q.resolve(e);for(;;){try{return await oe.lstat(q.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=q.dirname(t);if(i===t)return!1;t=i}}async function _y(e,t,i,r={}){let n=q.resolve(t.projectRoot),a=q.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=q.relative(n,q.resolve(f)).replaceAll("\\","/"),v=Kn(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await To(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await To(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await To(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Ty(e){return{stageBefore:oh(e.stagedBefore),combined:oh(e.combined),stageAfter:oh(e.stagedAfter)}}async function Iy(e,t,i=dh,r={}){let n=q.resolve(t.projectRoot);if(!await LT(n))return null;let a;try{a=await dl(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Un(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await _y(e,t,i,r)}catch(y){throw Un(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let E of y){let S=fl(E),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?[0-7]{6}) (?[a-f0-9]{40}|[a-f0-9]{64}) (?[0-3])$/u.exec(S.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Kn(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};p(s.records),p(l.records);let v=c.records.map(fl),h=FT(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),N=new Set(h.filter((y,E)=>!u.has(y)&&v[E].endsWith("/")));for(let y of f)N.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:N,omissions:[],overflow:null,evidence:null,initialFence:Ty(o)}}function dr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function wy(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function BT(e,t){return!dr(e.stageBefore,e.stageAfter)||!dr(e.stageAfter,t.stageBefore)||!dr(e.combined,t.combined)||!dr(t.stageBefore,t.stageAfter)}async function jy(e,t,i,r,n){let a;try{a=await _y(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Un(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=Ty(a),c=wy(o)||wy(s),l=BT(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:F(`comet.native.git-selection-overflow.v2 +${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var qT=(1n<<256n)-1n;function VT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function yy(e){let t=q.resolve(e.paths.projectRoot),i=q.resolve(e.paths.nativeRoot),r=q.resolve(e.paths.runtimeDir),n=q.resolve(e.paths.configFile),a=q.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>Ut(e.execution)>=1?!0:(p=!0,h=!0,!1),N=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),b=pl("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;Re.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(S)},y=async S=>{if(h||!m())return;let k;try{k=await oe.opendir(S)}catch(P){if(!m())return;if(!ke(P)&&!be(P)||S===t&&ke(P))throw P;v||=be(P),p||=ke(P),h=!0;return}if(!m()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let b=!1,R;try{for(;!h&&m();){let P;try{P=await k.read()}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z)||S===t&&ke(Z))throw Z;v||=be(Z),p||=ke(Z),h=!0;break}if(!m()||P===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let D=q.join(S,P.name),O=zT(t,D);if(D===n||D===a||Kt(i,D)||Kt(r,D)||e.denylist.some(Z=>Kt(Z,D))||ii(O)!==null)continue;if(!m())break;let De;try{De=await oe.lstat(D)}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z))throw Z;if(v=!0,N({path:O,type:"other"}),s.push({path:O,size:null,type:"file",reason:ke(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;let ce=VT(De);if(ce==="directory"){if(KT(e.policy,O))continue;if(!m())break;let Z;try{Z=await oe.realpath(D)}catch(Zt){if(!m())break;if(!ke(Zt)&&!be(Zt))throw Zt;if(v=!0,N({path:O,type:ce}),s.push({path:O,size:null,type:"directory",reason:ke(Zt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;if(!$(e.physicalProjectRoot,Z)||Kt(e.physicalNativeRoot,Z))continue;if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||(await y(D),h))break;continue}if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||h)break}}catch(P){b=!0,R=P}let w;try{await k.close()}catch(P){w=P}let g=m();if(b)throw R;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let E=p?F(`comet.native.physical-selection-incomplete.v1 ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):F(`comet.native.physical-selection.v1 -${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function jy(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function WT(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!jy(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function $y(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function yy(e,t){let r=(await dl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Ry.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${r}`)}async function Ny(e,t){let i=await yy(e,t),r=await MT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await yy(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function _o(e,t){if(ii(t)!==null)return!1;let i=q.resolve(e.projectRoot,...t.split("/"));return!Kt(q.resolve(e.nativeRoot),i)&&!Kt(q.resolve(e.runtimeDir),i)}function hh(e,t={}){let i=Ei(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.lengthq.resolve(e,...i.split(/[\\/]/u)))}function Kt(e,t){let i=q.resolve(e),r=q.resolve(t);return r===i||$(i,r)}function ke(e){return _T.has(e.code??"")}function be(e){return e.code==="ENOENT"}function ph(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` +${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function $y(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function WT(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!$y(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Oy(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Ny(e,t){let r=(await dl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!xy.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${r}`)}async function by(e,t){let i=await Ny(e,t),r=await MT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Ny(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function _o(e,t){if(ii(t)!==null)return!1;let i=q.resolve(e.projectRoot,...t.split("/"));return!Kt(q.resolve(e.nativeRoot),i)&&!Kt(q.resolve(e.runtimeDir),i)}function hh(e,t={}){let i=Ei(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.lengthq.resolve(e,...i.split(/[\\/]/u)))}function Kt(e,t){let i=q.resolve(e),r=q.resolve(t);return r===i||$(i,r)}function ke(e){return _T.has(e.code??"")}function be(e){return e.code==="ENOENT"}function ph(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` `)}function GT(e,t){return F(`comet.native.snapshot-policy.v1 -${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function sh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function UT(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function by(e){let t=Mc(e,"Native snapshot pattern"),i=[];for(let r=0;r{let a=n?UT(n):void 0;if(a&&!a())return!1;let o=sh(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=sh(i,c,a),o===null||o.size===0)return!1}return sh(i,o,a)?.has(i.length)??!1}}function Oy(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Mc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>Mc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=GT(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(by),excludeMatchers:i.map(by),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function KT(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function ky(e,t,i){if(!e)return!0;let r=()=>L(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function Io(e,t,i){let r=JSON.stringify(i);return F(`${e} +${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function sh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function UT(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function ky(e){let t=Mc(e,"Native snapshot pattern"),i=[];for(let r=0;r{let a=n?UT(n):void 0;if(a&&!a())return!1;let o=sh(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=sh(i,c,a),o===null||o.size===0)return!1}return sh(i,o,a)?.has(i.length)??!1}}function Hy(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Mc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>Mc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=GT(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(ky),excludeMatchers:i.map(ky),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function KT(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Sy(e,t,i){if(!e)return!0;let r=()=>L(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function Io(e,t,i){let r=JSON.stringify(i);return F(`${e} ${Buffer.byteLength(t)}:${t} -${Buffer.byteLength(r)}:${r}`)}function lh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function hl(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!lh(i))return e.splice(t,1),i}return null}function ur(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function YT(e,t,i,r){if(!L(r))return{status:"budget-exhausted"};let n;try{n=await oe.open(e,"r")}catch(c){if(!L(r))return{status:"budget-exhausted"};throw c}if(!L(r))return await n.close(),{status:"budget-exhausted"};let a=pl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!L(r))return{status:"budget-exhausted"};let c=await n.stat();if(!L(r))return{status:"budget-exhausted"};if(!c.isFile()||!ur(i,c))return{status:"changed"};for(;;){if(!L(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!L(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!L(r))return{status:"budget-exhausted"};let d=await n.stat();return L(r)?!d.isFile()||!ur(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ct(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Gn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ci(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=q.posix.normalize(e);if(i!==e||q.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function XT(e,t){let i=xt(e,`Native snapshot entry ${t}`);Ct(i,ET,`Native snapshot entry ${t}`);let r=Hy(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ci(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Ry.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function QT(e,t){let i=xt(e,`Native snapshot omission ${t}`);if(Ct(i,PT,`Native snapshot omission ${t}`),!CT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!AT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Hy(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ci(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function ZT(e){let t=xt(e,"Native snapshot omission overflow");if(Ct(t,RT,"Native snapshot omission overflow"),typeof t.hash!="string"||!ml.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Gn(t.count,"Native snapshot omission overflow count")}}function Jn(e,t){let i=xt(e,t);if(Ct(i,bT,t),typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ci(i.recordCount,`${t} recordCount`),n=ci(i.storedRecordCount,`${t} storedRecordCount`),a=ci(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function Sy(e){let t=xt(e,"Native Git selection evidence");if(Ct(t,NT,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=Jn(t.stageBefore,"Native Git selection stageBefore"),r=Jn(t.combined,"Native Git selection combined"),n=Jn(t.stageAfter,"Native Git selection stageAfter"),a=Jn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Jn(t.finalCombined,"Native Git selection finalCombined"),s=Jn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!dr(i,n)||!dr(n,a)||!dr(r,o)||!dr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Ey(e,t){let i=xt(e,t);if(Ct(i,ST,t),typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ci(i.visitedNodeCount,`${t} visitedNodeCount`),n=ci(i.recordCount,`${t} recordCount`),a=ci(i.storedRecordCount,`${t} storedRecordCount`),o=ci(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function eI(e){let t=xt(e,"Native physical selection evidence");if(Ct(t,kT,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Ey(t.before,"Native physical selection before"),r=Ey(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!jy(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Ei(e){let t=xt(e,"Native content snapshot manifest");if(Ct(t,mT,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!xT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=xt(t.capture,"Native content snapshot capture");if(Ct(b,wT,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:Sy(b.gitSelection),w=b.physicalSelection===void 0?void 0:eI(b.physicalSelection),g=null;if(b.projection!==void 0){let P=xt(b.projection,"Native content snapshot projection");if(Ct(P,yT,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...P.selection===void 0?{}:{selection:Sy(P.selection)}}}if(b.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&g)throw new Error("Native physical-tree capture cannot combine selection and projection");i=g?{provider:"physical-tree",projection:g}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=xt(t.limits,"Native content snapshot limits");Ct(r,vT,"Native content snapshot limits");let n={maxFiles:Gn(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Gn(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Gn(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Gn(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Gn(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=xt(t.policy,"Native snapshot policy");if(Ct(b,gT,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Oy({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(XT),s=t.omitted.map(QT),c=ci(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:ZT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,R)=>b+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>uh||c0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),N=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...N])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,E=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(E!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(N.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(ph(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function vl(e,t,i={}){let r=Ei(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=q.resolve(e.projectRoot),a=xy(i),o=Cy(i.gitSelectionLimits),s=await Ty(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set($y(s).filter(w=>_o(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>_o(e,w)),d=(w,g)=>g.some(P=>w===P||w.startsWith(`${P}/`)),f=w=>d(w,l),p=w=>d(w,u),v=[...r.entries.map(w=>w.path),...r.omitted.flatMap(w=>w.type==="directory"?[w.path,`${w.path}/`]:[w.path])].filter(w=>!c.has(w)&&!f(w)&&!p(w)),h=await DT(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!p(w.path)&&_o(e,w.path)&&(c.has(w.path)||!h.has(w.path)));await Iy(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let w of l)N.push({path:w,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((w,g)=>w.path.localeCompare(g.path,"en"));let y=r.omitted.filter(w=>f(w.path)||p(w.path)||!_o(e,w.path)?!1:h.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of N)y.some(g=>g.path===w.path&&g.reason===w.reason)||y.push(w);y.sort((w,g)=>w.path.localeCompare(g.path,"en"));let E=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,S=Io(S,"git-selection",{source:"git-selection",...s.overflow}));let k=w=>{E+=1,S=Io(S,"omission",w)};for(;y.length>uh;){let w=hl(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(w)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+E===0,entries:m,omitted:y,omittedCount:y.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:E}}:{}}),R=b();for(;ph(R)>r.limits.maxManifestBytes;){let w=hl(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(w),R=b()}return Ei(R)}function Dy(e,t){if(!pT.test(t))throw new Error(`Invalid Native change name: ${t}`);return q.join(H(e,t),"baseline-manifest.json")}async function gl(e,t={}){let i={maxFiles:t.limits?.maxFiles??ul.maxFiles,maxFileBytes:t.limits?.maxFileBytes??ul.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??ul.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??ul.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Oy(t.policy),n=xy({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Cy(t.gitSelectionLimits),o=OT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=q.resolve(e.projectRoot),c=await oe.realpath(s),l=q.resolve(e.nativeRoot),u=await oe.realpath(l),d=q.resolve(e.runtimeDir),f=q.resolve(e.configFile),p=q.join(s,".comet","current-change.json"),v=JT(s,t.denylist??[]),h=[],m=[],N=new Map,y=new Map,E=0,S=0,k=F("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,w=null,g=_=>{S+=1,k=Io(k,"omission",_)},P=_=>{if(E+=1,m.length{E+=_.count,S+=_.count,k=Io(k,"git-selection",{source:"git-selection",..._})},O=_=>{S+=1,k=Io(k,"manifest-entry",{reason:"manifest-size",entry:_})},De=async(_,A)=>{h.push(_),b+=_.size,N.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ce=(_,A)=>{let I=h.findIndex(ae=>ae.path===_);if(I<0)return;let[V]=h.splice(I,1);b-=V.size,N.delete(_),P(A)},Z=async(_,A,I,V)=>{if(!I.isFile()||I.isSymbolicLink()||!L(n))return;let ae;try{ae=await oe.realpath(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n)||!$(c,ae)||Kt(u,ae))return;if(h.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let G,B,pe;try{if(G=await YT(ae,I.size,I,n),G.status==="budget-exhausted"||!L(n))return;if(G.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!L(n)||(pe=await oe.realpath(_),!L(n)))return;B=await oe.lstat(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(L(n)){if(G.bytes!==I.size||pe!==ae||!ur(I,G.finalStat)||!ur(G.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}L(n)&&await De({path:A,hash:G.hash,size:B.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:ae,stat:B})}},Zt=async(_,A,I)=>{if(!L(n))return;let V,ae,G;try{if(V=await oe.readlink(_,{encoding:"buffer"}),!L(n)||(G=await oe.lstat(_),!L(n)))return;ae=await oe.readlink(_,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:null,type:"other",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n))return;if(!G.isSymbolicLink()||!ur(I,G)||G.mtimeMs!==I.mtimeMs||G.ctimeMs!==I.ctimeMs||!V.equals(ae)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=V.byteLength;if(h.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(b+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let pe=pl("sha256").update("symlink\0").update(V).digest("hex");L(n)&&await De({path:A,hash:pe,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:G})},Dt=async()=>{for(let[_,A]of[...N]){if(!L(n))return;if(A.kind==="file"){let B,pe;try{if(B=await oe.realpath(A.target),!L(n))return;pe=await oe.lstat(A.target)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"file",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(B!==A.realTarget||!pe.isFile()||pe.isSymbolicLink()||!ur(A.stat,pe)||pe.size!==A.stat.size||pe.mtimeMs!==A.stat.mtimeMs||pe.ctimeMs!==A.stat.ctimeMs)&&ce(_,{path:_,size:pe.isFile()?pe.size:null,type:pe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,pe;try{if(B=await oe.lstat(A.target),!L(n))return;pe=await oe.readlink(A.target,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"other",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(!B.isSymbolicLink()||!ur(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(pe))&&ce(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,V;try{if(I=await oe.realpath(A.target),!L(n))return;V=await oe.lstat(A.target)}catch{if(!L(n))return;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;if(!(I===A.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&ur(A.stat,V)&&$(c,I)&&!Kt(u,I))){ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let G;try{if(!L(n))return;G=await Ny(n,I)}catch(B){if(Un(B))throw B;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;G.dirty?ce(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):G.hash!==A.hash&&ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!L(n))return;try{let I=await oe.lstat(A);if(!L(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!L(n))return;if(be(I))continue;if(!ke(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},ft=await Ty(n,e,a,t.gitSelectionHooks);if(ft===null){let _=await wy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||N.has(V.path))continue;if(Ut(n)<1)break;if(!ky(r,V.path,n))continue;if(Ut(n)<1)break;let ae=q.resolve(s,...V.path.split("/")),G;try{G=await oe.lstat(ae)}catch(B){if(!L(n))break;if(!ke(B)&&!be(B))throw B;P({path:V.path,size:null,type:"file",reason:be(B)?"changed-during-read":"unreadable"});continue}if(Ut(n)<1)break;if(V.type==="symlink"&&G.isSymbolicLink()){if(await Zt(ae,V.path,G),Ut(n)<1)break;continue}if(V.type!=="file"||!G.isFile()||G.isSymbolicLink()){P({path:V.path,size:G.isFile()?G.size:null,type:G.isDirectory()?"directory":G.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Z(ae,V.path,G),Ut(n)<1)break}Ut(n)>=1&&await Dt();let A=await wy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=WT(_.evidence,A.evidence);w=I.evidence;for(let V of[..._.omissions,...A.omissions,...I.omissions])m.some(ae=>ae.path===V.path&&ae.reason===V.reason)||P(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let C=Ei(_);for(let le of C.entries)le.gitObjectId!==void 0&&A.set(le.path,le);I=A.size>0}let V=new Set,ae=!0;try{let C=await To(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(C.overflow)I=!1,ae=!1,A.clear();else for(let le of C.records){let me=fl(le),Ge=me.indexOf(" "),Me=Ge<0?null:Kn(me.slice(Ge+1));if(Ge!==1||Me===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");me[0]!=="H"&&V.add(Me)}}catch(C){if(Un(C))throw C;I=!1,ae=!1,A.clear()}let G=new Set;try{let C=await dl(n,s,["ls-files","--modified","-z"],ch);for(let le of C.toString("utf8").split("\0")){let me=Kn(le);me!==null&&G.add(me)}}catch{I=!1,ae=!1,A.clear()}let B=new Set,pe=new Set;for(let C of $y(ft)){if(N.has(C)||!_o(e,C))continue;if(Ut(n)<1)break;if(!ky(r,C,n))continue;if(Ut(n)<1)break;let le=q.resolve(s,...C.split("/"));if(le===f||le===p||Kt(d,le)||v.some(ht=>Kt(ht,le)))continue;if(ft.gitlinks.has(C)){if(h.length>=i.maxFiles){P({path:C,size:0,type:"file",reason:"file-count"});continue}let ht,Es;try{[ht,Es]=await Promise.all([oe.realpath(le),oe.lstat(le)])}catch{P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Es.isSymbolicLink()||!Es.isDirectory()||!$(c,ht)||Kt(u,ht)){P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let fn=await Ny(n,ht);if(fn.dirty){P({path:C,size:null,type:"directory",reason:"gitlink-dirty"});continue}await De({path:C,hash:fn.hash,size:0,type:"file"},{kind:"gitlink",target:le,realTarget:ht,stat:Es,hash:fn.hash})}catch(fn){if(Un(fn))throw fn;P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let me;try{me=await oe.lstat(le)}catch(ht){if(be(ht)&&ft.tracked.has(C)){y.set(C,le);continue}if(!ke(ht)&&!be(ht))throw ht;P({path:C,size:null,type:"file",reason:be(ht)?"changed-during-read":"unreadable"});continue}if(me.isSymbolicLink()){await Zt(le,C,me);continue}if(!me.isFile()){ft.nestedRepositories.has(C)||P({path:C,size:null,type:"other",reason:"changed-during-read"});continue}let Ge=ft.trackedObjectIds.get(C),Me=Ge?A.get(C):void 0;if(I&&Me?.gitObjectId!==void 0&&Me.gitObjectId===Ge&&!V.has(C)&&!G.has(C)){if(h.length>=i.maxFiles){P({path:C,size:Me.size,type:"file",reason:"file-count"});continue}if(Me.size>i.maxFileBytes){P({path:C,size:Me.size,type:"file",reason:"file-size"});continue}if(b+Me.size>i.maxTotalBytes){P({path:C,size:Me.size,type:"file",reason:"total-size"});continue}h.push({...Me}),b+=Me.size,B.add(C);continue}let om=ae&&!V.has(C)&&!G.has(C)?Ge:void 0;await Z(le,C,me,om),om!==void 0&&pe.add(C)}if(await Dt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Iy(n,e,a,ft,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&pe.size>0){let C=await dl(n,s,["ls-files","--modified","-z"],ch),le=new Set;for(let me of C.toString("utf8").split("\0")){let Ge=Kn(me);Ge!==null&&le.add(Ge)}for(let me of B){if(!le.has(me))continue;let Ge=h.find(Me=>Me.path===me);ce(me,{path:me,size:Ge?.size??null,type:"file",reason:"changed-during-read"})}for(let me of pe){if(!le.has(me))continue;let Ge=h.find(Me=>Me.path===me);Ge&&delete Ge.gitObjectId}}for(let C of ft.omissions)P(C);ft.overflow&&D(ft.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let zS=ft===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...ft.evidence?{gitSelection:ft.evidence}:{}},am=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:zS,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:E,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),Hu=am();for(;ph(Hu)>i.maxManifestBytes;){if(m.filter(A=>!lh(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))E+=1,O(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Hu=am()}return Hu}async function mh(e,t,i={}){let n=(await Ne(e.projectRoot))?.native.snapshot??Of;return gl(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function vh(e,t,i){let r=Dy(e,t);await T(j(e,r),r),await te(r,Ei(i))}async function Xn(e,t){let i=Dy(e,t),r=j(e,i);await T(r,i);try{let n=await il({root:r,file:i,maxBytes:hT,label:"Native baseline snapshot manifest"});return Ei(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as NI}from"crypto";import bI from"path";var vt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as pI}from"node:crypto";import{constants as yl,promises as Ye}from"node:fs";import gt from"node:path";import{TextDecoder as mI}from"node:util";import uI from"path";var oI=hn(Lr(),1);var j1=4*1024*1024;var sI=null;function cI(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function My(e,t){return(...i)=>{let r=sI;if(r===null)return t(...i);let n=cI(`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 M1=My("hookWritePolicy",async e=>(await _f(e))?.hook??{allow_paths:[]});var Fy=(e,t)=>{let i=e[t];return i==null?null:String(i)};function $o(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function jo(e,t){let i=$o(e,t);if(uI.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function dI(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Ly(e){if(!e.run_id)return null;let t=$o(e,"run_id"),i=$o(e,"skill"),r=$o(e,"skill_version"),n=$o(e,"skill_hash"),a=jo(e,"pending_ref"),o=jo(e,"trajectory_ref"),s=jo(e,"context_ref"),c=jo(e,"artifacts_ref"),l=jo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Fy(e,"current_step"),iteration:u,pending:Fy(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:dI(e)}}var Iq=256*1024;var fI=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function hI(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Ly(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function wl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!fI.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return hI(t)}var Ve={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Ho(e,t){let i=gt.relative(e,t);return i===""||!gt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gt.sep}`)}function qy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Oo(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function vI(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function fr(e,t,i){let r=vt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=gt.resolve(e),a=gt.resolve(n,...r.slice(8).split("/"));if(!Ho(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function By(e){let t=await Ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function gh(e,t){let i=gt.resolve(e),r=gt.resolve(t);if(!Ho(i,r))throw new Error("Native Run path is outside its change");let n=[await By(i)],a=i;for(let o of gt.relative(i,r).split(gt.sep).filter(Boolean)){a=gt.join(a,o);let s;try{s=await By(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ho(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Nl(e){for(let t of e){let i=await Ye.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!vI(t,i)||await Ye.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function gI(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 Yr(e,t,i,r,n){let a=await gh(e,gt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Ye.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=qy(o),c=await Ye.realpath(t);if(!Ho(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?yl.O_RDONLY:yl.O_RDONLY|yl.O_NOFOLLOW|yl.O_NONBLOCK,u;try{u=await Ye.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Nl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Oo(s,d)||!Oo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await gI(u,i,r);await n?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Nl(a),!m.isFile()||m.isSymbolicLink()||N!==c||!Oo(s,h)||!Oo(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new mI("utf-8",{fatal:!0}).decode(v)}catch(E){throw new Error(`${r} is not valid UTF-8`,{cause:E})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function wI(e,t,i){let r=await gh(e,gt.dirname(t));if(!r)return{exists:!1};let n;try{n=await Ye.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Ye.realpath(t);if(!Ho(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Nl(r),{exists:!0,identity:qy(n),realPath:a}}async function yI(e,t,i,r){let n=await gh(e,gt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await Ye.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Oo(i.identity,a)||await Ye.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Nl(n)}async function bl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await wI(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ue(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await yI(e.changeDir,e.file,i,e.label)}});let r=await Yr(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Vy(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Wy(e){return`${JSON.stringify(e,null,2)} -`}function hr(e){return wl(e)}async function Ie(e,t){let i=fr(e,"stateRef"),r=await Yr(e,i,Ve.runStateBytes,"Native Run state",t);return r?wl(Vy(r.text,"Native Run state")):null}async function Xr(e,t,i){let r=wl(t);await bl({changeDir:e,file:fr(e,"stateRef"),content:Wy(r),maxBytes:Ve.runStateBytes,label:"Native Run state",hooks:i})}async function Xe(e,t,i){let r=fr(e,"trajectoryRef",t),n=await Yr(e,r,Ve.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ve.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ve.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function zy(e,t,i){return(await Yr(e,fr(e,"trajectoryRef",t),Ve.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Jy(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=fr(e,"trajectoryRef",t),o=await Yr(e,a,Ve.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(pI("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await bl({changeDir:e,file:a,content:i,maxBytes:Ve.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function Gy(e,t,i,r){let n=fr(e,"trajectoryRef",t),a=`${JSON.stringify(i)} -`;if(Buffer.byteLength(a,"utf8")>Ve.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ve.trajectoryEventBytes} bytes`);let o=await Yr(e,n,Ve.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ve.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ve.trajectoryEvents} events`);await bl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Ve.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Qn(e,t,i){let r=await Yr(e,fr(e,"checkpointRef",t),Ve.checkpointBytes,"Native Run checkpoint",i);return r?Vy(r.text,"Native Run checkpoint"):null}async function Uy(e,t,i,r){await bl({changeDir:e,file:fr(e,"checkpointRef",t),content:Wy(i),maxBytes:Ve.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var kI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kl=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function wh(e){return NI("sha256").update(e).digest("hex")}function SI(e,t){if(!kI.test(t))throw new Error(`Invalid Native change name: ${t}`);return bI.join(H(e,t),"trajectory.jsonl")}function EI(e){let t=e.split(/\n/u),i=0;for(let r=0;r=Math.max(0,t.length-1)}function RI(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=EI(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(` -`)])}catch(d){if(!PI(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:wh(t),targetHash:wh(l),tailHash:wh(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Ky(e,t){let i=SI(e,t);await T(j(e,i),i);let r=H(e,t),n=await zy(r,vt.trajectoryRef);return n===null?{status:"clean",file:i}:RI(i,Buffer.from(n))}async function Zn(e,t){let i=await Ky(e,t);return"inspection"in i?i.inspection:i}async function Sl(e,t){let i=await Zn(e,t);if(i.status!=="clean")throw new kl(i)}async function Yy(e,t,i){return he(e,`repair trajectory tail for ${t}`,async()=>{let r=await Ky(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new kl(r)}try{await Jy(H(e,t),vt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await Zn(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as CI}from"node:crypto";import{promises as El}from"node:fs";import Pi from"node:path";var Do=/^[a-f0-9]{64}$/u,Xy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,AI=16*1024,Nh=process.platform,_I=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ea(e){return _I.has(e)}function eN(e,t){let i=Pi.relative(e,t);return Pi.isAbsolute(i)||i===".."||i.startsWith(`..${Pi.sep}`)?null:i.replaceAll("\\","/")||"."}function tN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function iN(e,t){if(e.length===0||tN(e)||e.includes("\\")||Pi.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=Pi.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function bh(e,t){return CI("sha256").update(`${e} -${t}`).digest("hex")}async function Qy(e,t){let i=await El.realpath(t),r=await El.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nh==="win32"?Pi.normalize(i).toLowerCase():i;return bh(e,`${n} +${Buffer.byteLength(r)}:${r}`)}function lh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function hl(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!lh(i))return e.splice(t,1),i}return null}function ur(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function YT(e,t,i,r){if(!L(r))return{status:"budget-exhausted"};let n;try{n=await oe.open(e,"r")}catch(c){if(!L(r))return{status:"budget-exhausted"};throw c}if(!L(r))return await n.close(),{status:"budget-exhausted"};let a=pl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!L(r))return{status:"budget-exhausted"};let c=await n.stat();if(!L(r))return{status:"budget-exhausted"};if(!c.isFile()||!ur(i,c))return{status:"changed"};for(;;){if(!L(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!L(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!L(r))return{status:"budget-exhausted"};let d=await n.stat();return L(r)?!d.isFile()||!ur(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ct(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Gn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ci(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Dy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=q.posix.normalize(e);if(i!==e||q.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function XT(e,t){let i=xt(e,`Native snapshot entry ${t}`);Ct(i,ET,`Native snapshot entry ${t}`);let r=Dy(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ci(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!xy.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function QT(e,t){let i=xt(e,`Native snapshot omission ${t}`);if(Ct(i,PT,`Native snapshot omission ${t}`),!CT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!AT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Dy(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ci(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function ZT(e){let t=xt(e,"Native snapshot omission overflow");if(Ct(t,RT,"Native snapshot omission overflow"),typeof t.hash!="string"||!ml.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Gn(t.count,"Native snapshot omission overflow count")}}function Jn(e,t){let i=xt(e,t);if(Ct(i,bT,t),typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ci(i.recordCount,`${t} recordCount`),n=ci(i.storedRecordCount,`${t} storedRecordCount`),a=ci(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function Ey(e){let t=xt(e,"Native Git selection evidence");if(Ct(t,NT,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=Jn(t.stageBefore,"Native Git selection stageBefore"),r=Jn(t.combined,"Native Git selection combined"),n=Jn(t.stageAfter,"Native Git selection stageAfter"),a=Jn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Jn(t.finalCombined,"Native Git selection finalCombined"),s=Jn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!dr(i,n)||!dr(n,a)||!dr(r,o)||!dr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Py(e,t){let i=xt(e,t);if(Ct(i,ST,t),typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ci(i.visitedNodeCount,`${t} visitedNodeCount`),n=ci(i.recordCount,`${t} recordCount`),a=ci(i.storedRecordCount,`${t} storedRecordCount`),o=ci(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function eI(e){let t=xt(e,"Native physical selection evidence");if(Ct(t,kT,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Py(t.before,"Native physical selection before"),r=Py(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!$y(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Ei(e){let t=xt(e,"Native content snapshot manifest");if(Ct(t,mT,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!xT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=xt(t.capture,"Native content snapshot capture");if(Ct(b,wT,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:Ey(b.gitSelection),w=b.physicalSelection===void 0?void 0:eI(b.physicalSelection),g=null;if(b.projection!==void 0){let P=xt(b.projection,"Native content snapshot projection");if(Ct(P,yT,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...P.selection===void 0?{}:{selection:Ey(P.selection)}}}if(b.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&g)throw new Error("Native physical-tree capture cannot combine selection and projection");i=g?{provider:"physical-tree",projection:g}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=xt(t.limits,"Native content snapshot limits");Ct(r,vT,"Native content snapshot limits");let n={maxFiles:Gn(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Gn(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Gn(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Gn(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Gn(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=xt(t.policy,"Native snapshot policy");if(Ct(b,gT,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Hy({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(XT),s=t.omitted.map(QT),c=ci(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:ZT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,R)=>b+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>uh||c0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),N=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...N])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,E=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(E!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(N.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(ph(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function vl(e,t,i={}){let r=Ei(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=q.resolve(e.projectRoot),a=Cy(i),o=Ay(i.gitSelectionLimits),s=await Iy(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Oy(s).filter(w=>_o(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>_o(e,w)),d=(w,g)=>g.some(P=>w===P||w.startsWith(`${P}/`)),f=w=>d(w,l),p=w=>d(w,u),v=[...r.entries.map(w=>w.path),...r.omitted.flatMap(w=>w.type==="directory"?[w.path,`${w.path}/`]:[w.path])].filter(w=>!c.has(w)&&!f(w)&&!p(w)),h=await DT(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!p(w.path)&&_o(e,w.path)&&(c.has(w.path)||!h.has(w.path)));await jy(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let w of l)N.push({path:w,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((w,g)=>w.path.localeCompare(g.path,"en"));let y=r.omitted.filter(w=>f(w.path)||p(w.path)||!_o(e,w.path)?!1:h.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of N)y.some(g=>g.path===w.path&&g.reason===w.reason)||y.push(w);y.sort((w,g)=>w.path.localeCompare(g.path,"en"));let E=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,S=Io(S,"git-selection",{source:"git-selection",...s.overflow}));let k=w=>{E+=1,S=Io(S,"omission",w)};for(;y.length>uh;){let w=hl(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(w)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+E===0,entries:m,omitted:y,omittedCount:y.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:E}}:{}}),R=b();for(;ph(R)>r.limits.maxManifestBytes;){let w=hl(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(w),R=b()}return Ei(R)}function My(e,t){if(!pT.test(t))throw new Error(`Invalid Native change name: ${t}`);return q.join(H(e,t),"baseline-manifest.json")}async function gl(e,t={}){let i={maxFiles:t.limits?.maxFiles??ul.maxFiles,maxFileBytes:t.limits?.maxFileBytes??ul.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??ul.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??ul.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Hy(t.policy),n=Cy({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Ay(t.gitSelectionLimits),o=OT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=q.resolve(e.projectRoot),c=await oe.realpath(s),l=q.resolve(e.nativeRoot),u=await oe.realpath(l),d=q.resolve(e.runtimeDir),f=q.resolve(e.configFile),p=q.join(s,".comet","current-change.json"),v=JT(s,t.denylist??[]),h=[],m=[],N=new Map,y=new Map,E=0,S=0,k=F("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,w=null,g=_=>{S+=1,k=Io(k,"omission",_)},P=_=>{if(E+=1,m.length{E+=_.count,S+=_.count,k=Io(k,"git-selection",{source:"git-selection",..._})},O=_=>{S+=1,k=Io(k,"manifest-entry",{reason:"manifest-size",entry:_})},De=async(_,A)=>{h.push(_),b+=_.size,N.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ce=(_,A)=>{let I=h.findIndex(ae=>ae.path===_);if(I<0)return;let[V]=h.splice(I,1);b-=V.size,N.delete(_),P(A)},Z=async(_,A,I,V)=>{if(!I.isFile()||I.isSymbolicLink()||!L(n))return;let ae;try{ae=await oe.realpath(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n)||!$(c,ae)||Kt(u,ae))return;if(h.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let G,B,pe;try{if(G=await YT(ae,I.size,I,n),G.status==="budget-exhausted"||!L(n))return;if(G.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!L(n)||(pe=await oe.realpath(_),!L(n)))return;B=await oe.lstat(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(L(n)){if(G.bytes!==I.size||pe!==ae||!ur(I,G.finalStat)||!ur(G.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}L(n)&&await De({path:A,hash:G.hash,size:B.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:ae,stat:B})}},Zt=async(_,A,I)=>{if(!L(n))return;let V,ae,G;try{if(V=await oe.readlink(_,{encoding:"buffer"}),!L(n)||(G=await oe.lstat(_),!L(n)))return;ae=await oe.readlink(_,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:null,type:"other",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n))return;if(!G.isSymbolicLink()||!ur(I,G)||G.mtimeMs!==I.mtimeMs||G.ctimeMs!==I.ctimeMs||!V.equals(ae)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=V.byteLength;if(h.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(b+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let pe=pl("sha256").update("symlink\0").update(V).digest("hex");L(n)&&await De({path:A,hash:pe,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:G})},Dt=async()=>{for(let[_,A]of[...N]){if(!L(n))return;if(A.kind==="file"){let B,pe;try{if(B=await oe.realpath(A.target),!L(n))return;pe=await oe.lstat(A.target)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"file",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(B!==A.realTarget||!pe.isFile()||pe.isSymbolicLink()||!ur(A.stat,pe)||pe.size!==A.stat.size||pe.mtimeMs!==A.stat.mtimeMs||pe.ctimeMs!==A.stat.ctimeMs)&&ce(_,{path:_,size:pe.isFile()?pe.size:null,type:pe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,pe;try{if(B=await oe.lstat(A.target),!L(n))return;pe=await oe.readlink(A.target,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"other",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(!B.isSymbolicLink()||!ur(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(pe))&&ce(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,V;try{if(I=await oe.realpath(A.target),!L(n))return;V=await oe.lstat(A.target)}catch{if(!L(n))return;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;if(!(I===A.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&ur(A.stat,V)&&$(c,I)&&!Kt(u,I))){ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let G;try{if(!L(n))return;G=await by(n,I)}catch(B){if(Un(B))throw B;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;G.dirty?ce(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):G.hash!==A.hash&&ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!L(n))return;try{let I=await oe.lstat(A);if(!L(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!L(n))return;if(be(I))continue;if(!ke(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},ft=await Iy(n,e,a,t.gitSelectionHooks);if(ft===null){let _=await yy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||N.has(V.path))continue;if(Ut(n)<1)break;if(!Sy(r,V.path,n))continue;if(Ut(n)<1)break;let ae=q.resolve(s,...V.path.split("/")),G;try{G=await oe.lstat(ae)}catch(B){if(!L(n))break;if(!ke(B)&&!be(B))throw B;P({path:V.path,size:null,type:"file",reason:be(B)?"changed-during-read":"unreadable"});continue}if(Ut(n)<1)break;if(V.type==="symlink"&&G.isSymbolicLink()){if(await Zt(ae,V.path,G),Ut(n)<1)break;continue}if(V.type!=="file"||!G.isFile()||G.isSymbolicLink()){P({path:V.path,size:G.isFile()?G.size:null,type:G.isDirectory()?"directory":G.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Z(ae,V.path,G),Ut(n)<1)break}Ut(n)>=1&&await Dt();let A=await yy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=WT(_.evidence,A.evidence);w=I.evidence;for(let V of[..._.omissions,...A.omissions,...I.omissions])m.some(ae=>ae.path===V.path&&ae.reason===V.reason)||P(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let C=Ei(_);for(let le of C.entries)le.gitObjectId!==void 0&&A.set(le.path,le);I=A.size>0}let V=new Set,ae=!0;try{let C=await To(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(C.overflow)I=!1,ae=!1,A.clear();else for(let le of C.records){let me=fl(le),Ge=me.indexOf(" "),Me=Ge<0?null:Kn(me.slice(Ge+1));if(Ge!==1||Me===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");me[0]!=="H"&&V.add(Me)}}catch(C){if(Un(C))throw C;I=!1,ae=!1,A.clear()}let G=new Set;try{let C=await dl(n,s,["ls-files","--modified","-z"],ch);for(let le of C.toString("utf8").split("\0")){let me=Kn(le);me!==null&&G.add(me)}}catch{I=!1,ae=!1,A.clear()}let B=new Set,pe=new Set;for(let C of Oy(ft)){if(N.has(C)||!_o(e,C))continue;if(Ut(n)<1)break;if(!Sy(r,C,n))continue;if(Ut(n)<1)break;let le=q.resolve(s,...C.split("/"));if(le===f||le===p||Kt(d,le)||v.some(ht=>Kt(ht,le)))continue;if(ft.gitlinks.has(C)){if(h.length>=i.maxFiles){P({path:C,size:0,type:"file",reason:"file-count"});continue}let ht,Es;try{[ht,Es]=await Promise.all([oe.realpath(le),oe.lstat(le)])}catch{P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Es.isSymbolicLink()||!Es.isDirectory()||!$(c,ht)||Kt(u,ht)){P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let fn=await by(n,ht);if(fn.dirty){P({path:C,size:null,type:"directory",reason:"gitlink-dirty"});continue}await De({path:C,hash:fn.hash,size:0,type:"file"},{kind:"gitlink",target:le,realTarget:ht,stat:Es,hash:fn.hash})}catch(fn){if(Un(fn))throw fn;P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let me;try{me=await oe.lstat(le)}catch(ht){if(be(ht)&&ft.tracked.has(C)){y.set(C,le);continue}if(!ke(ht)&&!be(ht))throw ht;P({path:C,size:null,type:"file",reason:be(ht)?"changed-during-read":"unreadable"});continue}if(me.isSymbolicLink()){await Zt(le,C,me);continue}if(!me.isFile()){ft.nestedRepositories.has(C)||P({path:C,size:null,type:"other",reason:"changed-during-read"});continue}let Ge=ft.trackedObjectIds.get(C),Me=Ge?A.get(C):void 0;if(I&&Me?.gitObjectId!==void 0&&Me.gitObjectId===Ge&&!V.has(C)&&!G.has(C)){if(h.length>=i.maxFiles){P({path:C,size:Me.size,type:"file",reason:"file-count"});continue}if(Me.size>i.maxFileBytes){P({path:C,size:Me.size,type:"file",reason:"file-size"});continue}if(b+Me.size>i.maxTotalBytes){P({path:C,size:Me.size,type:"file",reason:"total-size"});continue}h.push({...Me}),b+=Me.size,B.add(C);continue}let sm=ae&&!V.has(C)&&!G.has(C)?Ge:void 0;await Z(le,C,me,sm),sm!==void 0&&pe.add(C)}if(await Dt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await jy(n,e,a,ft,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&pe.size>0){let C=await dl(n,s,["ls-files","--modified","-z"],ch),le=new Set;for(let me of C.toString("utf8").split("\0")){let Ge=Kn(me);Ge!==null&&le.add(Ge)}for(let me of B){if(!le.has(me))continue;let Ge=h.find(Me=>Me.path===me);ce(me,{path:me,size:Ge?.size??null,type:"file",reason:"changed-during-read"})}for(let me of pe){if(!le.has(me))continue;let Ge=h.find(Me=>Me.path===me);Ge&&delete Ge.gitObjectId}}for(let C of ft.omissions)P(C);ft.overflow&&D(ft.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let zS=ft===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...ft.evidence?{gitSelection:ft.evidence}:{}},om=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:zS,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:E,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),Hu=om();for(;ph(Hu)>i.maxManifestBytes;){if(m.filter(A=>!lh(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))E+=1,O(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Hu=om()}return Hu}async function mh(e,t,i={}){let n=(await Ne(e.projectRoot))?.native.snapshot??Of;return gl(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function vh(e,t,i){let r=My(e,t);await T(j(e,r),r),await te(r,Ei(i))}async function Xn(e,t){let i=My(e,t),r=j(e,i);await T(r,i);try{let n=await il({root:r,file:i,maxBytes:hT,label:"Native baseline snapshot manifest"});return Ei(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as NI}from"crypto";import bI from"path";var vt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as pI}from"node:crypto";import{constants as yl,promises as Ye}from"node:fs";import gt from"node:path";import{TextDecoder as mI}from"node:util";import uI from"path";var oI=hn(Lr(),1);var $1=4*1024*1024;var sI=null;function cI(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Fy(e,t){return(...i)=>{let r=sI;if(r===null)return t(...i);let n=cI(`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 F1=Fy("hookWritePolicy",async e=>(await _f(e))?.hook??{allow_paths:[]});var Ly=(e,t)=>{let i=e[t];return i==null?null:String(i)};function $o(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function jo(e,t){let i=$o(e,t);if(uI.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function dI(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function By(e){if(!e.run_id)return null;let t=$o(e,"run_id"),i=$o(e,"skill"),r=$o(e,"skill_version"),n=$o(e,"skill_hash"),a=jo(e,"pending_ref"),o=jo(e,"trajectory_ref"),s=jo(e,"context_ref"),c=jo(e,"artifacts_ref"),l=jo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Ly(e,"current_step"),iteration:u,pending:Ly(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:dI(e)}}var jq=256*1024;var fI=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function hI(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=By(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function wl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!fI.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return hI(t)}var Ve={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Ho(e,t){let i=gt.relative(e,t);return i===""||!gt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gt.sep}`)}function Vy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Oo(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function vI(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function fr(e,t,i){let r=vt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=gt.resolve(e),a=gt.resolve(n,...r.slice(8).split("/"));if(!Ho(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function qy(e){let t=await Ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function gh(e,t){let i=gt.resolve(e),r=gt.resolve(t);if(!Ho(i,r))throw new Error("Native Run path is outside its change");let n=[await qy(i)],a=i;for(let o of gt.relative(i,r).split(gt.sep).filter(Boolean)){a=gt.join(a,o);let s;try{s=await qy(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ho(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Nl(e){for(let t of e){let i=await Ye.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!vI(t,i)||await Ye.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function gI(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 Yr(e,t,i,r,n){let a=await gh(e,gt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Ye.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Vy(o),c=await Ye.realpath(t);if(!Ho(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?yl.O_RDONLY:yl.O_RDONLY|yl.O_NOFOLLOW|yl.O_NONBLOCK,u;try{u=await Ye.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Nl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Oo(s,d)||!Oo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await gI(u,i,r);await n?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Nl(a),!m.isFile()||m.isSymbolicLink()||N!==c||!Oo(s,h)||!Oo(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new mI("utf-8",{fatal:!0}).decode(v)}catch(E){throw new Error(`${r} is not valid UTF-8`,{cause:E})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function wI(e,t,i){let r=await gh(e,gt.dirname(t));if(!r)return{exists:!1};let n;try{n=await Ye.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Ye.realpath(t);if(!Ho(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Nl(r),{exists:!0,identity:Vy(n),realPath:a}}async function yI(e,t,i,r){let n=await gh(e,gt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await Ye.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Oo(i.identity,a)||await Ye.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Nl(n)}async function bl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await wI(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ue(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await yI(e.changeDir,e.file,i,e.label)}});let r=await Yr(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Wy(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function zy(e){return`${JSON.stringify(e,null,2)} +`}function hr(e){return wl(e)}async function Ie(e,t){let i=fr(e,"stateRef"),r=await Yr(e,i,Ve.runStateBytes,"Native Run state",t);return r?wl(Wy(r.text,"Native Run state")):null}async function Xr(e,t,i){let r=wl(t);await bl({changeDir:e,file:fr(e,"stateRef"),content:zy(r),maxBytes:Ve.runStateBytes,label:"Native Run state",hooks:i})}async function Xe(e,t,i){let r=fr(e,"trajectoryRef",t),n=await Yr(e,r,Ve.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ve.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ve.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Jy(e,t,i){return(await Yr(e,fr(e,"trajectoryRef",t),Ve.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Gy(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=fr(e,"trajectoryRef",t),o=await Yr(e,a,Ve.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(pI("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await bl({changeDir:e,file:a,content:i,maxBytes:Ve.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function Uy(e,t,i,r){let n=fr(e,"trajectoryRef",t),a=`${JSON.stringify(i)} +`;if(Buffer.byteLength(a,"utf8")>Ve.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ve.trajectoryEventBytes} bytes`);let o=await Yr(e,n,Ve.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ve.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ve.trajectoryEvents} events`);await bl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Ve.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Qn(e,t,i){let r=await Yr(e,fr(e,"checkpointRef",t),Ve.checkpointBytes,"Native Run checkpoint",i);return r?Wy(r.text,"Native Run checkpoint"):null}async function Ky(e,t,i,r){await bl({changeDir:e,file:fr(e,"checkpointRef",t),content:zy(i),maxBytes:Ve.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var kI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kl=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function wh(e){return NI("sha256").update(e).digest("hex")}function SI(e,t){if(!kI.test(t))throw new Error(`Invalid Native change name: ${t}`);return bI.join(H(e,t),"trajectory.jsonl")}function EI(e){let t=e.split(/\n/u),i=0;for(let r=0;r=Math.max(0,t.length-1)}function RI(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=EI(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(` +`)])}catch(d){if(!PI(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:wh(t),targetHash:wh(l),tailHash:wh(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Yy(e,t){let i=SI(e,t);await T(j(e,i),i);let r=H(e,t),n=await Jy(r,vt.trajectoryRef);return n===null?{status:"clean",file:i}:RI(i,Buffer.from(n))}async function Zn(e,t){let i=await Yy(e,t);return"inspection"in i?i.inspection:i}async function Sl(e,t){let i=await Zn(e,t);if(i.status!=="clean")throw new kl(i)}async function Xy(e,t,i){return he(e,`repair trajectory tail for ${t}`,async()=>{let r=await Yy(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new kl(r)}try{await Gy(H(e,t),vt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await Zn(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as CI}from"node:crypto";import{promises as El}from"node:fs";import Pi from"node:path";var Do=/^[a-f0-9]{64}$/u,Qy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,AI=16*1024,Nh=process.platform,_I=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ea(e){return _I.has(e)}function tN(e,t){let i=Pi.relative(e,t);return Pi.isAbsolute(i)||i===".."||i.startsWith(`..${Pi.sep}`)?null:i.replaceAll("\\","/")||"."}function iN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function rN(e,t){if(e.length===0||iN(e)||e.includes("\\")||Pi.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=Pi.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function bh(e,t){return CI("sha256").update(`${e} +${t}`).digest("hex")}async function Zy(e,t){let i=await El.realpath(t),r=await El.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nh==="win32"?Pi.normalize(i).toLowerCase():i;return bh(e,`${n} ${r.dev} ${r.ino} -${r.birthtimeMs}`)}async function Zy(e,t){let i=await El.realpath(t),r=await El.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nh==="win32"?Pi.normalize(i).toLowerCase():i;return bh(e,n)}function TI(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 yh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||tN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function rN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(yh(e.changeBranch,"Native workspace change branch"),yh(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 II(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"||!Xy.test(t.baseCommit)||typeof t.targetCommit!="string"||!Xy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");yh(t.targetBranch,"Native workspace Git target branch")}function Mo(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"||!Do.test(String(t.projectRootId))||!Do.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");TI(t.capturedAt),iN(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&&!Do.test(String(t.projectRootPathId))||a&&!Do.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Do.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&II(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(rN(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 ta(e,t){return Pi.join(H(e,t),"workspace.json")}function jI(e,t){let i=ta(e,t),r=j(e,i),n=eN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:iN(n,"Native workspace file ref")}}async function nN(e,t){try{let i=jI(e,t),r=await Q({root:i.root,ref:i.ref,maxBytes:AI});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function aN(e,t){let i=Ae(e.projectRoot),r={projectRoot:Pi.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await wt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await ia({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function kh(e,t){let i=await nN(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Mo(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function oN(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=eN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ae(e.paths.projectRoot),r=i.isGitWorktree?Nf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Nf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Qy("comet.native.workspace-project-root.v2",e.paths.projectRoot),Qy("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Zy("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Zy("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&rN(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:bh("comet.native.workspace-session.v2",`${s} +${r.birthtimeMs}`)}async function eN(e,t){let i=await El.realpath(t),r=await El.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nh==="win32"?Pi.normalize(i).toLowerCase():i;return bh(e,n)}function TI(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 yh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||iN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function nN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(yh(e.changeBranch,"Native workspace change branch"),yh(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 II(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"||!Qy.test(t.baseCommit)||typeof t.targetCommit!="string"||!Qy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");yh(t.targetBranch,"Native workspace Git target branch")}function Mo(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"||!Do.test(String(t.projectRootId))||!Do.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");TI(t.capturedAt),rN(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&&!Do.test(String(t.projectRootPathId))||a&&!Do.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Do.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&II(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(nN(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 ta(e,t){return Pi.join(H(e,t),"workspace.json")}function jI(e,t){let i=ta(e,t),r=j(e,i),n=tN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:rN(n,"Native workspace file ref")}}async function aN(e,t){try{let i=jI(e,t),r=await Q({root:i.root,ref:i.ref,maxBytes:AI});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function oN(e,t){let i=Ae(e.projectRoot),r={projectRoot:Pi.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await wt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await ia({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function kh(e,t){let i=await aN(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Mo(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function sN(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=tN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ae(e.paths.projectRoot),r=i.isGitWorktree?Nf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Nf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Zy("comet.native.workspace-project-root.v2",e.paths.projectRoot),Zy("comet.native.workspace-native-root.v2",e.paths.nativeRoot),eN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),eN("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&nN(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:bh("comet.native.workspace-session.v2",`${s} ${c} -${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Mo(p),p}async function Pl(e){let t=await oN(e),i=ta(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await te(i,t,{containedRoot:r}),t}async function wt(e,t){let i=await nN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Mo(i),i)}async function sN(e){return await kh(e.paths,e.name)?Pl(e):null}async function Fo(e){Mo(e.identity);let t=await oN({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Nh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function ia(e){if(Mo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Fo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ae(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function cN(e,t){let i=await wt(e,t);if(i===null)return null;let r=await ia({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var uN=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],$I=new Set(uN),dN=new Set([...uN,"minimum_runtime_version","revision"]),OI=new Set([...dN,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),HI=new Set(["capability","operation","source","base_hash"]),DI=new Set(["shape","build","verify","archive"]),MI=new Set(["implicit","confirmed"]),FI=new Set(["pending","pass","fail"]),Re="comet-state.yaml",Eh=/^[a-f0-9]{64}$/u,fN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Lo=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"},Zr=class extends Error{constructor(i,r){super(i!==ge||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"},Bo=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"},qo=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"},ra=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"},PV=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function Wo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hN(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 xl(e){if(!fN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function BI(e){if(!fN.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function pN(e,t){if(e.length===0||li.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function qI(e,t){let i=Wo(e,`spec_changes[${t}]`);if(hN(i,HI,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(BI(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"&&pN(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"||!Eh.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"||!Eh.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 VI(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 Ph(e,t){if(hN(e,t,Re),typeof e.name!="string")throw new Error("Native change name is required");if(xl(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"||!DI.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&&!MI.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(qI),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"||!FI.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"&&pN(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!VI(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 Gr(e){let t=Wo(e,Re);if(t.schema!==Ke)throw new Error(`Expected ${Ke}`);return{schema:Ke,...Ph(t,$I)}}function Vo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Sh(e,t,i){if(e===null)return null;let r=typeof e=="string"?LI.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function WI(e){if(e==null)return null;if(typeof e!="string"||!Eh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function zI(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 ai(e){let t=Wo(e,Re);if(t.schema!==we)throw new Error(`Expected ${we}`);if(Vo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${we} minimum_runtime_version must be 2`);return{schema:we,minimum_runtime_version:2,revision:Vo(t.revision,"Native v2 revision"),...Ph(t,dN)}}function st(e){let t=Wo(e,Re);if(t.schema!==ge){if(t.schema===Ke||t.schema===we){let o=t.schema===Ke?Gr(t):ai(t);throw new Lo(o.name,o.schema)}throw new Zr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Vo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Zr(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Vo(t.revision,"Native revision"),n=Ph(t,OI),a=WI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ge,minimum_runtime_version:3,revision:r,verification_protocol:zI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Sh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Sh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Sh(t.partial_allowance,"Native partial_allowance","allowances")}}function mN(e){let t=Wo(e,Re);if(t.schema===Ke){let n=Gr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema===we){let n=ai(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema!==ge){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 Zr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Vo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Zr(t.schema,i).message};let r=st(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Qr(e){let t=st(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Cl(e){let t=ai(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function re(e,t){xl(t);let i=li.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function na(e,t){let i=H(e,t),r=li.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await lN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function aa(e,t){let i=H(e,t),r=li.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await lN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var JI=256*1024;async function Al(e,t=li.dirname(e)){let i=li.relative(t,e).split(li.sep).join("/"),r=await Q({root:t,ref:i,maxBytes:JI}),n=(0,Rl.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 ui(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=mN(await Al(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await na(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await GI(e,r.state),r)}async function _l(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=mN(await Al(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function GI(e,t){if(await Xn(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function $e(e,t){let i=await ui(e,t);if(i.status==="migration-required")throw new Lo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Zr(i.schema,i.minimumRuntimeVersion);return await cN(e,t),i.state}async function vN(e,t,i){let r={...t,schema:ge,minimum_runtime_version:3,revision:i+1},n=await my({expectedRevision:i,next:r,read:async()=>{let a=st(await Al(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ue(e,(0,Rl.stringify)(Qr(a))),equals:(a,o)=>JSON.stringify(Qr(a))===JSON.stringify(Qr(o)),conflict:a=>new Bo(t.name,i,a)});return Object.assign(t,n),n}async function Tl(e,t,i,r){if(await $n(e.projectRoot),await na(e,t.name))throw new Lo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await aa(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await $e(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Sl(e,t.name);let a=li.join(re(e,t.name),Re);return await T(e.nativeRoot,a),vN(a,t,i)}async function gN(e,t){return vN(e,t,t.revision)}async function wN(e){return st(await Al(e))}var NN=["Outcome","Scope","Non-goals","Acceptance examples"],UI=[...NN,"Constraints and invariants","Decisions","Open questions","Verification expectations"],KI=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],bN={maxFileBytes:lo};function kN(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(` -`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function YI(e,t){let i=yN.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await Rh.realpath(e),n=await Rh.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Rh.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function zo(e){return{valid:e.length===0,findings:e}}async function xh(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:bN.maxFileBytes})).text}catch(o){return zo([{code:"brief-missing",message:o.message,path:t}])}let n=kN(r);for(let o of UI)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of NN)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),zo(i)}async function Ch(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:bN.maxFileBytes})).text}catch(a){return zo([{code:"verification-missing",message:a.message,path:t}])}let n=kN(r);for(let a of KI)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return zo(i)}function Il(e,t){return yN.join(e.specsDir,t,"spec.md")}async function SN(e,t){let i=[],r=re(e,t.name);for(let n of t.spec_changes){let a=Il(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await Gt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await YI(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return zo(i)}import{promises as i0}from"node:fs";import ok from"node:path";import EN from"node:path";var XI="comet.native.archive-preflight.v1",QI="comet.native.archive-preflight.v1",ZI="comet.native.archive-operation.v1",ej=/^[a-f0-9]{64}$/u,PN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function jl(e,t){return et?1:0}function ij(e,t){if(typeof e!="string"||!ej.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ri(e,t){return e===null?null:ij(e,t)}function rj(e,t){let i=EN.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||EN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function nj(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function aj(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function oj(e,t){if(!PN.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Ri(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Ri(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Ri(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function sj(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Ri(e.contractHash,"Native archive contract hash"),acceptanceHash:Ri(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ri(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ri(e.reportHash,"Native archive report hash"),envelopeHash:Ri(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ri(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function cj(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!tj.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(jl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function lj(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(jl)}function RN(e){if(!PN.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(oj).sort((l,u)=>jl(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:M(ZI,l)})),r=sj(e.evidence),n=aj(e.workspace),a=[...new Set([...cj(e.findingCodes??[]),...lj({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(jl),o=nj(e.revision),s=rj(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:XI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:M(QI,c)}}import{createHash as uj}from"node:crypto";import xN from"node:path";var dj="comet.native.conflict-radar.v1",ct=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}),fj="comet.native.conflict-radar.v1",hj="comet.native.conflict-radar-signals.v1",pj=/^[a-f0-9]{64}$/u,_N=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mj=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),vj=new Set(["capability","operation","baseHash"]),gj=new Set(["path","kind"]);function oa(e,t){return et?1:0}function Ah(e){return Buffer.byteLength(e,"utf8")}function _h(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Th(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Ah(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function wj(e,t){let i=Th(e,t,ct.maxArtifactPathBytes),r=xN.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||xN.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function TN(e,t){if(typeof e!="string"||!pj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yj(e,t){let i=_h(e,vj,t),r=Th(i.capability,`${t} capability`,ct.maxCapabilityBytes);if(!_N.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:TN(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function Nj(e,t){let i=_h(e,gj,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:wj(i.path,`${t} path`),kind:i.kind}}function bj(e,t){let i=_h(e,mj,`Conflict radar change ${t}`),r=Th(i.name,`Conflict radar change ${t} name`,ct.maxNameBytes);if(!_N.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ct.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ct.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>yj(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>oa(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>Nj(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>oa(c.path,l.path)||oa(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:TN(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function kj(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ct.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(bj).sort((n,a)=>oa(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ct.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ct.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function Sj(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function Ej(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function Pj(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function Rj(e,t){let i=[],r=uj("sha256").update(`${hj} -[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(ko(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(Sj(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Ej(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:Pj(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function CN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function xj(e,t){return CN(e.classification)-CN(t.classification)||oa(e.left,t.left)||oa(e.right,t.right)}function AN(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:dj,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function IN(e){let t=kj(e),i=[];for(let s=0;s({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=M(fj,{changes:t,relationships:r}),a=i.slice(0,ct.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=AN(t,i,a,n);for(;a.length>0&&Ah(JSON.stringify(o))>ct.maxSerializedBytes;)a=a.slice(0,-1),o=AN(t,i,a,n);if(Ah(JSON.stringify(o))>ct.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as M$}from"node:crypto";import{promises as Xt}from"node:fs";import hi from"node:path";import{createHash as LN}from"node:crypto";import jN from"path";var Ih="comet.native.implementation-scope.v2",BN="comet.native.content-snapshot-projection.v1",Jo="comet.native.content-snapshot-projection.v1",qN="comet.native.implementation-scope.v2",Cj="comet.native.unresolved-scope-id.v1",Aj="comet.native.scope-detail-overflow.v1",_j="comet.native.snapshot-projection-overflow.v2",Hh=/^[a-f0-9]{64}$/u,tn=1024*1024,Tj=128,Ij=128;function We(e,t){return et?1:0}function jh(e){if(!Hh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function jj(e,t){return e===t?0:e===null?-1:t===null?1:We(e,t)}function mr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=jN.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||jN.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function VN(e,t){return e==="."?e:mr(e,t)}function sa(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function $j(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:mr(e.path,`${t} path`),hash:e.hash,size:sa(e.size,`${t} size`),type:"file"}}function Oj(e,t){return{path:VN(e.path,`${t} path`),size:e.size===null?null:sa(e.size,`${t} size`),type:e.type,reason:e.reason}}function Hj(e,t){return We(e.path,t.path)||We(e.hash,t.hash)||e.size-t.size}function Dj(e,t){return We(e.path,t.path)||We(e.reason,t.reason)||We(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Uo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` +${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Mo(p),p}async function Pl(e){let t=await sN(e),i=ta(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await te(i,t,{containedRoot:r}),t}async function wt(e,t){let i=await aN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Mo(i),i)}async function cN(e){return await kh(e.paths,e.name)?Pl(e):null}async function Fo(e){Mo(e.identity);let t=await sN({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Nh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function ia(e){if(Mo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Fo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ae(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function lN(e,t){let i=await wt(e,t);if(i===null)return null;let r=await ia({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var dN=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],$I=new Set(dN),fN=new Set([...dN,"minimum_runtime_version","revision"]),OI=new Set([...fN,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),HI=new Set(["capability","operation","source","base_hash"]),DI=new Set(["shape","build","verify","archive"]),MI=new Set(["implicit","confirmed"]),FI=new Set(["pending","pass","fail"]),Re="comet-state.yaml",Eh=/^[a-f0-9]{64}$/u,hN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Lo=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"},Zr=class extends Error{constructor(i,r){super(i!==ge||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"},Bo=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"},qo=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"},ra=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"},RV=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function Wo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function pN(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 xl(e){if(!hN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function BI(e){if(!hN.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function mN(e,t){if(e.length===0||li.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function qI(e,t){let i=Wo(e,`spec_changes[${t}]`);if(pN(i,HI,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(BI(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"&&mN(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"||!Eh.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"||!Eh.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 VI(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 Ph(e,t){if(pN(e,t,Re),typeof e.name!="string")throw new Error("Native change name is required");if(xl(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"||!DI.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&&!MI.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(qI),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"||!FI.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"&&mN(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!VI(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 Gr(e){let t=Wo(e,Re);if(t.schema!==Ke)throw new Error(`Expected ${Ke}`);return{schema:Ke,...Ph(t,$I)}}function Vo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Sh(e,t,i){if(e===null)return null;let r=typeof e=="string"?LI.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function WI(e){if(e==null)return null;if(typeof e!="string"||!Eh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function zI(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 ai(e){let t=Wo(e,Re);if(t.schema!==we)throw new Error(`Expected ${we}`);if(Vo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${we} minimum_runtime_version must be 2`);return{schema:we,minimum_runtime_version:2,revision:Vo(t.revision,"Native v2 revision"),...Ph(t,fN)}}function st(e){let t=Wo(e,Re);if(t.schema!==ge){if(t.schema===Ke||t.schema===we){let o=t.schema===Ke?Gr(t):ai(t);throw new Lo(o.name,o.schema)}throw new Zr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Vo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Zr(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Vo(t.revision,"Native revision"),n=Ph(t,OI),a=WI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ge,minimum_runtime_version:3,revision:r,verification_protocol:zI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Sh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Sh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Sh(t.partial_allowance,"Native partial_allowance","allowances")}}function vN(e){let t=Wo(e,Re);if(t.schema===Ke){let n=Gr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema===we){let n=ai(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema!==ge){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 Zr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Vo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Zr(t.schema,i).message};let r=st(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Qr(e){let t=st(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Cl(e){let t=ai(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function re(e,t){xl(t);let i=li.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function na(e,t){let i=H(e,t),r=li.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await uN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function aa(e,t){let i=H(e,t),r=li.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await uN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var JI=256*1024;async function Al(e,t=li.dirname(e)){let i=li.relative(t,e).split(li.sep).join("/"),r=await Q({root:t,ref:i,maxBytes:JI}),n=(0,Rl.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 ui(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=vN(await Al(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await na(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await GI(e,r.state),r)}async function _l(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=vN(await Al(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function GI(e,t){if(await Xn(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function $e(e,t){let i=await ui(e,t);if(i.status==="migration-required")throw new Lo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Zr(i.schema,i.minimumRuntimeVersion);return await lN(e,t),i.state}async function gN(e,t,i){let r={...t,schema:ge,minimum_runtime_version:3,revision:i+1},n=await vy({expectedRevision:i,next:r,read:async()=>{let a=st(await Al(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ue(e,(0,Rl.stringify)(Qr(a))),equals:(a,o)=>JSON.stringify(Qr(a))===JSON.stringify(Qr(o)),conflict:a=>new Bo(t.name,i,a)});return Object.assign(t,n),n}async function Tl(e,t,i,r){if(await $n(e.projectRoot),await na(e,t.name))throw new Lo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await aa(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await $e(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Sl(e,t.name);let a=li.join(re(e,t.name),Re);return await T(e.nativeRoot,a),gN(a,t,i)}async function wN(e,t){return gN(e,t,t.revision)}async function yN(e){return st(await Al(e))}var bN=["Outcome","Scope","Non-goals","Acceptance examples"],UI=[...bN,"Constraints and invariants","Decisions","Open questions","Verification expectations"],KI=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],kN={maxFileBytes:lo};function SN(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(` +`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function YI(e,t){let i=NN.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await Rh.realpath(e),n=await Rh.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Rh.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function zo(e){return{valid:e.length===0,findings:e}}async function xh(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:kN.maxFileBytes})).text}catch(o){return zo([{code:"brief-missing",message:o.message,path:t}])}let n=SN(r);for(let o of UI)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of bN)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),zo(i)}async function Ch(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:kN.maxFileBytes})).text}catch(a){return zo([{code:"verification-missing",message:a.message,path:t}])}let n=SN(r);for(let a of KI)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return zo(i)}function Il(e,t){return NN.join(e.specsDir,t,"spec.md")}async function EN(e,t){let i=[],r=re(e,t.name);for(let n of t.spec_changes){let a=Il(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await Gt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await YI(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return zo(i)}import{promises as i0}from"node:fs";import sk from"node:path";import PN from"node:path";var XI="comet.native.archive-preflight.v1",QI="comet.native.archive-preflight.v1",ZI="comet.native.archive-operation.v1",ej=/^[a-f0-9]{64}$/u,RN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function jl(e,t){return et?1:0}function ij(e,t){if(typeof e!="string"||!ej.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ri(e,t){return e===null?null:ij(e,t)}function rj(e,t){let i=PN.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||PN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function nj(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function aj(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function oj(e,t){if(!RN.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Ri(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Ri(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Ri(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function sj(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Ri(e.contractHash,"Native archive contract hash"),acceptanceHash:Ri(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ri(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ri(e.reportHash,"Native archive report hash"),envelopeHash:Ri(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ri(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function cj(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!tj.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(jl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function lj(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(jl)}function xN(e){if(!RN.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(oj).sort((l,u)=>jl(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:M(ZI,l)})),r=sj(e.evidence),n=aj(e.workspace),a=[...new Set([...cj(e.findingCodes??[]),...lj({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(jl),o=nj(e.revision),s=rj(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:XI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:M(QI,c)}}import{createHash as uj}from"node:crypto";import CN from"node:path";var dj="comet.native.conflict-radar.v1",ct=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}),fj="comet.native.conflict-radar.v1",hj="comet.native.conflict-radar-signals.v1",pj=/^[a-f0-9]{64}$/u,TN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mj=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),vj=new Set(["capability","operation","baseHash"]),gj=new Set(["path","kind"]);function oa(e,t){return et?1:0}function Ah(e){return Buffer.byteLength(e,"utf8")}function _h(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Th(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Ah(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function wj(e,t){let i=Th(e,t,ct.maxArtifactPathBytes),r=CN.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||CN.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function IN(e,t){if(typeof e!="string"||!pj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yj(e,t){let i=_h(e,vj,t),r=Th(i.capability,`${t} capability`,ct.maxCapabilityBytes);if(!TN.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:IN(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function Nj(e,t){let i=_h(e,gj,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:wj(i.path,`${t} path`),kind:i.kind}}function bj(e,t){let i=_h(e,mj,`Conflict radar change ${t}`),r=Th(i.name,`Conflict radar change ${t} name`,ct.maxNameBytes);if(!TN.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ct.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ct.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>yj(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>oa(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>Nj(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>oa(c.path,l.path)||oa(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:IN(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function kj(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ct.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(bj).sort((n,a)=>oa(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ct.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ct.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function Sj(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function Ej(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function Pj(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function Rj(e,t){let i=[],r=uj("sha256").update(`${hj} +[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(ko(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(Sj(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Ej(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:Pj(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function AN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function xj(e,t){return AN(e.classification)-AN(t.classification)||oa(e.left,t.left)||oa(e.right,t.right)}function _N(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:dj,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function jN(e){let t=kj(e),i=[];for(let s=0;s({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=M(fj,{changes:t,relationships:r}),a=i.slice(0,ct.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=_N(t,i,a,n);for(;a.length>0&&Ah(JSON.stringify(o))>ct.maxSerializedBytes;)a=a.slice(0,-1),o=_N(t,i,a,n);if(Ah(JSON.stringify(o))>ct.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as M$}from"node:crypto";import{promises as Xt}from"node:fs";import hi from"node:path";import{createHash as BN}from"node:crypto";import $N from"path";var Ih="comet.native.implementation-scope.v2",qN="comet.native.content-snapshot-projection.v1",Jo="comet.native.content-snapshot-projection.v1",VN="comet.native.implementation-scope.v2",Cj="comet.native.unresolved-scope-id.v1",Aj="comet.native.scope-detail-overflow.v1",_j="comet.native.snapshot-projection-overflow.v2",Hh=/^[a-f0-9]{64}$/u,tn=1024*1024,Tj=128,Ij=128;function We(e,t){return et?1:0}function jh(e){if(!Hh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function jj(e,t){return e===t?0:e===null?-1:t===null?1:We(e,t)}function mr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=$N.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||$N.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function WN(e,t){return e==="."?e:mr(e,t)}function sa(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function $j(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:mr(e.path,`${t} path`),hash:e.hash,size:sa(e.size,`${t} size`),type:"file"}}function Oj(e,t){return{path:WN(e.path,`${t} path`),size:e.size===null?null:sa(e.size,`${t} size`),type:e.type,reason:e.reason}}function Hj(e,t){return We(e.path,t.path)||We(e.hash,t.hash)||e.size-t.size}function Dj(e,t){return We(e.path,t.path)||We(e.reason,t.reason)||We(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Uo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` `,"utf8")}function pr(e,t,i){let r=`${t} -${ko(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function Mj(e){if(Uo(e)<=tn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=LN("sha256");a.update(`${_j} -`),e.omissionOverflow&&pr(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,pr(a,"omission",f)},s=f=>{r+=1,n+=1,pr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Uo(u)>tn;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function $h(e){let t=Ei(e),i=t.entries.map((n,a)=>$j(n,`Snapshot entry ${a}`));if(i.sort(Hj),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>Oj(n,`Snapshot omission ${a}`));return r.sort(Dj),Mj({schema:BN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Ko(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:mr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>We(i.path,r.path)||We(i.kind,r.kind))}function Yo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function $N(e){return e?{hash:e.hash,size:e.size}:null}function Dh(e,t,i){let r=0,n=0;for(;r=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:$N(c),after:$N(l)})}}function WN(e,t){return{...e,attributedTo:t.filter(i=>Yo(i,e.path))}}function Mh(e){let t=Ko(e.declaredArtifacts),i=[];return Dh(e.baseline,e.current,r=>{i.push(WN(r,t))}),i}function xi(e,t){return{id:`scope:${M(Cj,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function Fj(e,t){let i=t.omitted.map(r=>xi({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(xi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(xi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function ON(e,t){return Fj(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Oh(e,t){return We(e.kind,t.kind)||We(e.source,t.source)||jj(e.path,t.path)||We(e.id,t.id)}function Lj(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Oh)}function zN(e){return[...new Set(e.map((t,i)=>mr(t,`Git path ${i}`)))].sort(We)}function HN(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function Bj(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function JN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=zN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:HN(e.baseCommit,"Native external drift base commit"),targetBranch:Bj(e.targetBranch,"Native external drift target branch"),targetCommit:HN(e.targetCommit,"Native external drift target commit"),paths:t}}function GN(e){if(typeof e.contractHash!="string"||!Hh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Ko(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:zN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:JN(e.externalDrift)}}}function qj(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Dh(e,t,p=>{let v=i.some(h=>Yo(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length{if(i>=e.detailedChangeCount){pr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Yo(o,n.path)&&(a+=1,pr(t,"change-attribution",o));pr(t,"change-end",{attributionCount:a}),a===0&&pr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&pr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function KN(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=qj(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(P=>!w.has(P)||n.some(D=>Yo(D,P)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=M(Jo,e),c=M(Jo,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=Ij)break;l.push(xi({kind:"snapshot-omission",source:R,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${R} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...ON("baseline",e),...ON("current",t),...o.totalChanges===0&&a===null?[xi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>R.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!R.has(w))}},v=R=>{let w=o.candidates.slice(0,R.detailedChangeCount),g=w.filter(Dt=>Dt.attributedTo.length===0&&!u.has(Dt.path)),P=o.totalChanges-w.length,D=o.totalUnattributed-g.length,O=d-R.detailedOmissionCount,De=D+O,ce=[...g.map(Dt=>xi({kind:"unattributed-change",source:"implementation-scope",path:Dt.path,evidence:{after:Dt.after,before:Dt.before,changeKind:Dt.kind}},`Changed path is not covered by a declared artifact: ${Dt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...De>0?[UN(R.overflowHash,{changes:P,unattributed:D,unresolved:De})]:[]],Z=Lj(ce),Zt=R.includeGitAdvisory?p():void 0;return{schema:Ih,contractHash:r,baselineProjectionRef:jh(s),baselineProjectionHash:s,currentProjectionRef:jh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:Z,noCodeReason:a,...Zt?{gitAdvisory:Zt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,N=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:y});if(Uo({...R,scopeHash:y})<=tn)break;if(N){N=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>h||d>m?Wj({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,k=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:S}),b={...k,scopeHash:M(qN,k)};if(Uo(b)>tn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Fh(e){let t=$h(e.baseline),i=$h(e.current),r=GN(e);return{authority:r,baseline:t,current:i,scope:KN(t,i,r)}}var zj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function en(e,t){if(typeof e!="string"||!Hh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function DN(e,t,i){let r=jh(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ca(e,t){let i=di(e,"Native snapshot projection");if(fi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==BN)throw new Error("Native snapshot projection schema is invalid");let r=Ei({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=$h(r);if(M(Jo,i)!==M(Jo,n))throw new Error("Native snapshot projection is not canonical");let a=M(Jo,n);if(t!==void 0&&en(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Lh(e,t){let i=di(e,`Declared artifact ${t}`);if(fi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:mr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function MN(e,t){if(e===null)return null;let i=di(e,t);return fi(i,["hash","size"],[],t),{hash:en(i.hash,`${t} hash`),size:sa(i.size,`${t} size`)}}function FN(e,t){let i=di(e,`Implementation change ${t}`);if(fi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Lh),n=Ko(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=MN(i.before,`Implementation change ${t} before`),o=MN(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:mr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function Jj(e,t){let i=di(e,`Unresolved scope ${t}`);fi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?VN(i.path,`Unresolved scope ${t} path`):mr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Go(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>mr(n,`${t} ${a}`)),r=[...new Set(i)].sort(We);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function YN(e){let t=di(e,"Native implementation external drift");if(fi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Go(t.paths,"Native external drift paths");return JN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function la(e){let t=di(e,"Native implementation scope"),i=[...zj].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(fi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Ih)throw new Error("Native implementation scope schema is invalid");let r=en(t.contractHash,"Implementation scope contractHash"),n=en(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=DN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=en(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=DN(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Lh);if(JSON.stringify(c)!==JSON.stringify(Ko(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(FN),u=[...l].sort((g,P)=>We(g.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(g=>g.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(g=>`${g.kind}:${g.path}`));if(l.some(g=>g.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(P=>Yo(P,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(FN),p=t.externalDrift===void 0?void 0:YN(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(Jj),N=m.filter(g=>g.kind==="scope-detail-overflow");if(N.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=N[0]===void 0?null:Vj(N[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,S=[...h.map(g=>xi({kind:"unattributed-change",source:"implementation-scope",path:g.path,evidence:{after:g.after,before:g.before,changeKind:g.kind}},`Changed path is not covered by a declared artifact: ${g.path}`)),...l.length+(y?.changes??0)===0&&E===null?[xi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Oh))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(S.sort(Oh))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let g=di(t.gitAdvisory,"Implementation scope Git advisory");if(fi(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=Go(g.changedPaths,"Git changed paths"),D=Go(g.pathsPresentInSnapshotChanges,"Git present paths"),O=Go(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),De=[...D,...O].sort(We);if(JSON.stringify(De)!==JSON.stringify(P)||O.some(ce=>l.some(Z=>Z.path===ce)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:D,pathsAbsentFromSnapshotChanges:O}}let R={schema:Ih,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:E,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},w=en(t.scopeHash,"Implementation scope scopeHash");if(M(qN,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function Gj(e){let t=di(e,"Native implementation scope authority");if(fi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Lh);if(JSON.stringify(i)!==JSON.stringify(Ko(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Go(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:YN(t.externalDrift),a=GN({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Xo(e){let t=di(e,"Native implementation scope bundle");fi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Gj(t.authority),r=ca(t.baseline),n=ca(t.current),a=la(t.scope),o=KN(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function XN(e){let t=la(e.scope);return Xo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import QN from"node:path";var Uj=/\b(Bearer|Basic)\s+[^\s"']+/giu,Kj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Yj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Xj=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,Qj=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,Zj=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,e$=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function At(e){return e.replace(Uj,"$1 [REDACTED]").replace(Kj,"[REDACTED PRIVATE KEY]").replace(Yj,"$1[REDACTED]@").replace(Xj,"[REDACTED TOKEN]").replace(Qj,'$1"[REDACTED]"').replace(Zj,"$1$2$1$3$4[REDACTED]$4").replace(e$,"$1$2[REDACTED]")}var eb=/^[a-f0-9]{64}$/u;var t$="comet.native.acceptance-trace.v2",i$="comet.native.partial-allowance.v1",r$="comet.native.verification-evidence.v2";function Ci(e,t){if(!eb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function ib(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Bh(e,t,i=2e3){let r=At(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Qo(e,t){let i=QN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||QN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function n$(e,t,i){let r=Qo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ii(r),a=r.toLowerCase(),o=i?Qo(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function qh(e){let t=Qo(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function ua(e,t){return et?1:0}function $l(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ol(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function rb(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function ZN(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function a$(e){let t=$l(e,"Native acceptance trace");if(Ol(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!eb.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Qo(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=$l(o,`Native acceptance trace entry ${s}`);if(Ol(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>qh(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ua))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Qo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Bh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>ua(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Ci(t.traceHash,"Native acceptance trace hash");if(M(t$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Hl(e){let t=$l(e,"Native partial allowance");if(Ol(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(ua))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:ib(t.change),scopeHash:Ci(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Bh(t.reason,"Partial allowance reason"),confirmedSummary:Bh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:tb(t.sourceRevision),confirmedAt:rb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Ci(t.allowanceHash,"Native partial allowance hash");if(M(i$,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Zo(e){let t=$l(e,"Native verification evidence");if(Ol(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Ci(t.implementationScopeHash,"Native verification implementation scope hash"),r=a$(t.acceptanceTrace),n=Ci(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Ci(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>qh(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ua)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(ua);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>qh(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ua)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:ib(t.change),sourceRevision:tb(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ci(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:ZN(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:n$(t.reportRef,"Native verification report ref"),reportHash:Ci(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:ZN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:rb(t.createdAt,"Native verification timestamp")},d=Ci(t.envelopeHash,"Native verification envelope hash");if(M(r$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import nb from"node:path";var ab="comet.native.check-receipt.v1",o$="comet.native.check-receipt.v1",da="scoped-text-safety",Vh=1,lt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),s$=/^[a-f0-9]{64}$/u,c$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,l$="comet.native.checker-policy.v1",u$="comet.native.check-input.v1",d$=2048,ob=M(l$,{policy:da,version:Vh,limits:lt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),f$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),sb=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],lb=["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"],h$=new Set(lb);function vr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Ai(e,t){if(typeof e!="string"||!s$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ub(e,t){let i=yt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function cb(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function p$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>d$||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=nb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||nb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function m$(e){let t=vr(e,"Native check receipt checker");gr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=vr(t.limits,"Native check receipt limits");if(gr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==da||t.version!==Vh||t.hash!==ob||i.maxFiles!==lt.maxFiles||i.maxFileBytes!==lt.maxFileBytes||i.maxTotalBytes!==lt.maxTotalBytes||i.maxIssues!==lt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:da,version:Vh,hash:ob,limits:{...lt}}}function v$(e){let t=vr(e,"Native check receipt contract");return gr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Ai(t.expectedHash,"Native check expected contract hash"),beforeHash:Ai(t.beforeHash,"Native check before contract hash"),afterHash:Ai(t.afterHash,"Native check after contract hash")}}function g$(e){let t=vr(e,"Native check receipt implementation");return gr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Ai(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Ai(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Ai(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Ai(t.afterSnapshotHash,"Native check after snapshot hash")}}function w$(e,t){let i=vr(e,`Native check batch ${t}`);gr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:yt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:yt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:yt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:yt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:yt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:yt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>lt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>lt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function y$(e){let t=vr(e,"Native check receipt counts");gr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:yt(t.filesSelected,"Native check filesSelected"),filesScanned:yt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:yt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:yt(t.bytesScanned,"Native check bytesScanned"),issueCount:yt(t.issueCount,"Native check issueCount"),recordedIssueCount:yt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(w$):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>lt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>lt.maxFiles||i.bytesScanned>lt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function N$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||sb.indexOf(e.kind)-sb.indexOf(t.kind)}function b$(e){if(!Array.isArray(e)||e.length>lt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=vr(r,`Native check issue ${n}`);if(gr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!f$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:p$(a.path,`Native check issue ${n} path`),line:ub(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(N$);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function k$(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!h$.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=lb.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function S$(e){return M(u$,e)}function Dl(e){let t=vr(e,"Native check receipt");if(gr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==ab)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!c$.test(t.change))throw new Error("Native check receipt change name is invalid");let i=ub(t.sourceRevision,"Native check source revision"),r=m$(t.checker),n=v$(t.contract),a=g$(t.implementation),o=S$({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Ai(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=cb(t.startedAt,"Native check receipt startedAt"),c=cb(t.endedAt,"Native check receipt endedAt");if(cu.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=k$(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>lt.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>lt.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:ab,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Ai(t.receiptHash,"Native check receipt content hash");if(M(o$,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var zh="comet.native.verification-receipt.v3",E$=zh,P$="comet.native.declared-artifacts.v1",R$=/^[a-f0-9]{64}$/u,x$=/^acceptance-[a-f0-9]{64}$/u,C$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,_$=4096,T$=256,I$=1024;function fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function wr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function _i(e,t){if(typeof e!="string"||!R$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=At(e).trim();if(!i||i.length>_$||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Wh(e,t){let i=Yt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function es(e,t,i=Yt,r=!1,n=T$){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function j$(e,t){if(typeof e!="string"||!x$.test(e))throw new Error(`${t} is invalid`);return e}function $$(e){let t=fa(e,"Native verification receipt bindings");if(wr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!C$.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:_i(t.contractHash,"Native verification receipt contract hash"),scopeHash:_i(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:_i(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:_i(t.artifactHash,"Native verification receipt artifact hash")}}function O$(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=A$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function H$(e,t,i,r){let n=fa(t,`Native ${e} evidence`);if(e==="automated-check"){if(wr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Wh(n.startedAt,"Native automated-check start time"),o=Wh(n.endedAt,"Native automated-check end time");if(Date.parse(o)({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var pb=/^[a-f0-9]{64}$/u,yr=tn,mW=3*yr;function Gh(e,t){let i=hi.relative(e,t);return i===""||!hi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${hi.sep}`)}function F$(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function db(e){let t=await Xt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Xt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function L$(e,t){let i=hi.resolve(e),r=hi.resolve(t);if(!Gh(i,r))throw new Error("Native evidence path is outside its change");let n=[await db(i)],a=i;for(let o of hi.relative(i,r).split(hi.sep).filter(Boolean)){a=hi.join(a,o);let s=await db(a);if(!Gh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function fb(e){for(let t of e){let i=await Xt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!F$(t,i)||await Xt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function B$(e,t,i={}){let r=await L$(t,hi.dirname(e));await i.afterParentChainCaptured?.();let n=await Xt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Xt.realpath(e);if(!Gh(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Xt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await fb(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fl(s,n)||!Fl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>yr)throw new Error(`Native evidence document exceeds ${yr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=yr+1-d,N=await o.read(f,0,Math.min(f.length,m),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>yr)throw new Error(`Native evidence document exceeds ${yr} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await fb(r),!v.isFile()||v.isSymbolicLink()||h!==a||!Fl(s,p)||!Fl(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function pa(e,t){if(!pb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function mb(e){return pa("reports",e)}async function q$(e,t,i,r,n){if(!pb.test(i))throw new Error("Native report evidence hash is invalid");let a=await rn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||M$("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function ha(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function V$(e,t,i,r,n){let a=pa(i,r);return n?hi.join(n,...a.split("/")):Qi(H(e,t),a)}async function rn(e){let t=V$(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),B$(t,i,e.hooks)}function hb(e,t){return ca(e,t)}function W$(e,t){let i=la(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function z$(e,t,i){let r=Hl(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function J$(e,t,i){let r=Zo(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function G$(e,t,i,r=!1,n){let a=await Ll(e,t,i.implementationScopeRef,void 0,n);if(r&&await q$(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await vb(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function ts(e,t,i,r,n){let a=ha(i,"scopes"),o=W$(await rn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=ha(o.baselineProjectionRef,"snapshots"),c=ha(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([rn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>hb(d,s)),rn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>hb(d,c))]);return XN({baseline:l,current:u,scope:o})}async function Ll(e,t,i,r,n){return(await ts(e,t,i,r,n)).scope}async function vb(e,t,i,r,n){let a=ha(i,"allowances");return z$(await rn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function is(e,t,i,r,n){let a=ha(i,"receipts"),o=Ml(await rn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function ma(e,t,i,r,n){let a=ha(i,"verifications"),o=J$(await rn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await G$(e,t,o,!1,n),o}var U$=4096;async function K$(e,t=ct.maxChanges){try{let i=await pt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function gb(e,t){let i=await $e(e,t),[r,n]=await Promise.all([i.implementation_scope?Ll(e,t,i.implementation_scope):null,wt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Bl(e,t,i={}){let n=(await K$(e,U$)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await gb(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await gb(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=IN([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as fO}from"fs";import hO from"path";import{isDeepStrictEqual as Vl}from"util";var va={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var Y$=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function X$(e,t){return et?1:0}function Q$(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!Y$.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(X$)}function Uh(e=[]){return Q$(e,"Native repair failed check IDs",va.maxFailedCheckIds,!0)}function wb(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function Z$(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:wb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&wb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length=0;n-=1){let a=t[n];if(Z$(r,a))break;i+=1,r=a}return i}function Yh(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var yb="repairStagnation",Nt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},tO=/^[a-f0-9]{64}$/u;var iO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),rO=["data","runId","sequence","timestamp","type"],Nb=["disposition","overrideSummaryHash","signatureHash"],nO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],bb=12;function Qh(e,t){return et?1:0}function kb(e,t,i){let r=Object.keys(e).sort(Qh);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function ql(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function rs(e,t){if(typeof e!="string"||!tO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function aO(e){if(!Array.isArray(e)||e.length>va.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Qh)}function Sb(e){if(typeof e!="string"||e.length===0||e.length>Nt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Xh(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Nt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Nt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Nt.maxTextCharacters&&(!n||e.length>Nt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Nt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Xh(s,t+1,i,`${r}[${c}]`));return}let a=ql(e,r),o=Object.keys(a);if(o.length>Nt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Nt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Xh(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function oO(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function sO(e,t,i){let r=ql(e,`Native repair trajectory event ${t+1}`);if(kb(r,rO,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(oO(r.timestamp),typeof r.type!="string"||!iO.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Sb(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Xh(r.data,0,n,"Native trajectory event data"),ql(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Zh(e){let t=ql(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Qh),r=i.length===Nb.length&&i.every((l,u)=>l===Nb[u]);r||kb(t,nO,"Native repair trajectory projection");let n=rs(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:rs(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=rs(t.contractHash,"Native repair trajectory contract hash"),s=aO(t.failedAcceptanceIds),c=Uh(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function cO(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function lO(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??bb;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Kh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":aa.kind==="failure"),n=i?.maxVerifyFailures??bb;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Eb(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Nt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Sb(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;lNt.maxTotalDataNodes||c>Nt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?rs(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?rs(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,yb)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Zh(f[yb]);if(cO(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),lO(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");uO(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>va.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Pb(e){return Eb(e).history}function Rb(e){let t=Eb(e).latestProjection;return t?{...t}:null}var pi={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:[]},ns=F("comet-native-runtime:v3:scope-reopen"),dO=[{skillVersion:"3",skillHash:F("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function xb(e){return e.skillVersion===pi.definition.metadata.version&&e.skillHash===ns||dO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var ep={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Nr(e){let i={sequence:(await Xe(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Gy(e.changeDir,e.run.trajectoryRef,i),i}async function nn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Uy(e.changeDir,e.run.checkpointRef,t),t}function Cb(e){return F(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Hb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],pO=new Set(Hb),Db=new Set([...Hb,"minimum_runtime_version","revision"]),mO=new Set([...Db,"operation"]),vO=512*1024,tp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),gO=new Set([...tp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),as=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ze(e,t){return hO.join(H(e,t),"transition.json")}function wO(e){return`transition-${e}`}async function yO(e,t,i){let r=wO(t);return er(e,r,i)}async function an(e,t,i,r){let n=await yO(e,t,i);try{return await r()}finally{await tr(n)}}function zl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function rp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Wl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){return Vl(e,t)}function ip(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!gO.has(u)),a=[...tp].find(u=>!Object.hasOwn(i,u)),o=tp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Yh(i.summary,"Native transition journal event summary"),At(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Yh(i.noCodeReason,"Native transition journal event no-code reason"),At(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Zh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function NO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return ip({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return ip(e,t)}function np(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?NO(e.eventData,e.evidenceHash):ip(e.eventData,e.evidenceHash),n=hr(e.nextRun),a=e.previousRun===null?null:hr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Ab(e,t,i=!1){if(e.skill!==pi.definition.metadata.name||(i?!xb(e):e.skillVersion!==pi.definition.metadata.version||e.skillHash!==ns)||e.orchestration!==pi.definition.orchestration.mode||e.pendingRef!==vt.pendingRef||e.trajectoryRef!==vt.trajectoryRef||e.contextRef!==vt.contextRef||e.artifactsRef!==vt.artifactsRef||e.checkpointRef!==vt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function _b(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Tb(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function ap(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Ab(o,"next Run",r||a!==null),Tb(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Ab(a,"previous Run",!0),Tb(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Vl(_b(a),_b(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function bO(e,t,i){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Mb(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Ib(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function op(e,t,i,r,n=!1){let a=i.eventData,o=Ib(e),s=Ib(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Vl(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Vl(e.spec_changes,t.spec_changes),l=Cb({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=bO(e.name,a.summary,t.spec_changes),l=F(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function sp(e,t){let i=zl(e);if(rp(i,mO),i.schema!==rr)throw new Error(`Expected Native transition schema ${rr}`);let r=Wl(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${rr} minimum_runtime_version must be ${3}`);let n=Wl(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=np(i,t),o=st(i.previousState),s=st(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(op(o,s,a,i.operation),ap(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:rr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function kO(e,t){let i=zl(e);if(rp(i,pO),i.schema!==Jr)throw new Error(`Expected Native transition schema ${Jr}`);let r=np(i,t,!0),n=Gr(i.previousState),a=Gr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return op(n,a,r,Mb(n,a,r.eventData),!0),ap(n,a,r,!0),{schema:Jr,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function cp(e,t){let i=zl(e);if(rp(i,Db),i.schema!==Si)throw new Error(`Expected Native transition schema ${Si}`);if(Wl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Si} minimum_runtime_version must be 2`);let n=Wl(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=np(i,t,!0),o=ai(i.previousState),s=ai(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(op(o,s,a,Mb(o,s,a.eventData),!0),ap(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Si,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function SO(e,t){let i=zl(e);if(i.schema===rr)return{status:"current",journal:sp(i,t)};if(i.schema===Jr)return{status:"migration-required",journal:kO(i,t)};if(i.schema===Si)return{status:"migration-required",journal:cp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function lp(e,t){let i=ze(e,t),r=j(e,i);await T(r,i);try{let n=await ie({root:r,file:i,maxBytes:vO,label:`Native transition journal ${t}`});return SO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ti(e,t){let i=await lp(e,t);if(!i)return null;if(i.status==="migration-required")throw new as(t);return i.journal}function jb(e,t){if(mi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(mi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function $b(e,t){if(mi(e,t.nextState))return"next";if(mi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function EO(e){let{journal:t}=e;return Fb({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Fb(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Ob(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=EO({sequence:a.index+1,journal:t,type:a.event.type});if(!mi(Fb(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function Jl(e,t,i){if(await na(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Sl(e,t);let r=await Ti(e,t);if(!r)return null;let n=H(e,t),a=Ob(await Xe(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Ie(n),$e(e,t)]),c=jb(o,r),l=$b(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Xr(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!mi(await Ie(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let m=await Tl(e,r.nextState,r.previousState.revision);if(!mi(m,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!mi(await $e(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Ti(e,t);if(!u||!mi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Ob(await Xe(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Nr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await Nr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await nn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[p,v]=await Promise.all([Ie(n),$e(e,t)]);jb(p,{...r,previousRun:r.nextRun}),$b(v,{...r,previousState:r.nextState});let h=await Ti(e,t);if(!h||!mi(h,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await fO.rm(ze(e,t),{force:!0}),r.nextState}async function Lb(e,t,i){return he(e,`continue transition ${t}`,()=>an(e,t,`continue transition ${t}`,()=>Jl(e,t,i)))}import Bb from"node:path";var PO="comet.native.contract.v1",RO="comet.native.acceptance-set.v1",qb=/^[a-f0-9]{64}$/u,os={maxAcceptanceCriteria:Eo.maxCriteria};function Vb(e,t){let i=Bb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Bb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Wb(e){return M("comet.native.contract-content.v1",e.replace(/\r\n?/gu,` -`))}function xO(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(qb))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(qb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Vb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Wb(e.markdown)},markdown:e.markdown}}function CO(e,t){return zb(e.id,t.id)}function zb(e,t){return et?1:0}function Jb(e){let t=Vb(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(xO).sort((d,f)=>zb(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Vc(e.briefMarkdown,t,os.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Wc(f,d.source,os.maxAcceptanceCriteria-a.length)),a.push(...zc(f,d.source,os.maxAcceptanceCriteria-a.length)));if(a.sort(CO),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>os.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${os.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Wb(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=M(RO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(PO,u)}}var Gl={maxSpecs:64,maxFileBytes:lo,maxTotalBytes:4*1024*1024};async function ga(e){if(e.specChanges.length>Gl.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Q({root:e.changeDir,ref:e.briefRef,maxBytes:Gl.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Q({root:e.changeDir,ref:n.source,maxBytes:Gl.maxFileBytes});if(i+=a.size,i>Gl.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Jb({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as GO}from"node:child_process";import{promisify as UO}from"node:util";var g2=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as OO}from"fs";import wa from"path";var kr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},ya=/^[a-f0-9]{64}$/u;function Ul(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kl(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function br(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Gb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function up(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||wa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=wa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function dp(e,t){return wa.join(H(e,t),"checkpoints","progress.json")}function Sr(e,t){return wa.join(H(e,t),"checkpoint-journal.json")}function fp(e,t,i){if(!ya.test(i))throw new Error("Native checkpoint manifest hash is invalid");return wa.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function _O(e){if(!ya.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function hp(e,t,i){let r=await ie({root:e,file:t,maxBytes:kr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function TO(e,t){let i=Ul(e,`checkpoint manifest artifact ${t}`);Kl(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=AO(br(i.path,`checkpoint artifact ${t} path`,4096)),n=ii(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!ya.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:up(i.size,`checkpoint artifact ${t} size`)}}function Yl(e,t){let i=Ul(e,"Native checkpoint manifest");if(Kl(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>kr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(TO),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=up(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>kr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function pp(e){return F(JSON.stringify(Yl(e,e.change)))}function mp(e,t){let i=Ul(e,"Native progress checkpoint");if(Kl(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Gb(i.previousRevision,"Native checkpoint previousRevision"),a=Gb(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=br(i.manifestHash,"Native checkpoint manifestHash",64);if(!ya.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=_O(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=br(i.inputHash,"Native checkpoint inputHash",64);if(!ya.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=br(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=up(i.artifactCount,"Native checkpoint artifactCount");if(u>kr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=br(i.summary,"Native checkpoint summary"),f=br(i.nextAction,"Native checkpoint nextAction");if(At(d)!==d||At(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:br(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function IO(e,t){let i=Ul(e,"Native checkpoint journal");if(Kl(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=st(i.previousState),n=st(i.nextState),a=mp(i.checkpoint,t),o=Yl(i.manifest,t),s=br(i.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!ya.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==pp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function jO(e,t,i){let r=wa.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=kf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ie({root:e.projectRoot,file:r,maxBytes:kr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function $O(e,t){let i=dp(e,t),r=j(e,i);await T(r,i);try{return mp(await hp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function vp(e,t,i){let r=fp(e,t,i),n=j(e,r);await T(n,r);let a=await hp(n,r,"Native checkpoint manifest"),o=Yl(a,t);if(gp(e,o),pp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Er(e,t){let i=Sr(e,t),r=j(e,i);await T(r,i);try{let n=IO(await hp(r,i,"Native checkpoint journal"),t);return gp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ub(e,t,i,r){let n=Yl(i,t);gp(e,n);let a=pp(n),o=fp(e,t,a),s=j(e,o);await T(s,o);try{let c=await vp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await te(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function gp(e,t){for(let i of t.artifacts){let r=kf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Kb(e,t){let i=mp(t,t.change),r=await vp(e,i.change,i.manifestHash),n=F(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=dp(e,t.change),o=j(e,a);await T(o,a),await te(a,i,{containedRoot:o})}async function Yb(e){let t;try{t=await $O(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:dp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await vp(e.paths,e.name,t.manifestHash);let a=F(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await jO(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:fp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Xb(e,t,i){let r=await Er(e,t);if(!r)return null;if(await Ub(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Tl(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Kb(e,r.checkpoint),await i?.afterProgressWritten?.(r),await OO.rm(Sr(e,t),{force:!0}),r}async function Qb(e,t,i){return he(e,`continue checkpoint ${t}`,()=>an(e,t,`continue checkpoint ${t}`,async()=>(await Jl(e,t),Xb(e,t,i))))}import{constants as wp,promises as _t}from"node:fs";import Na from"node:path";var HO=/^[a-f0-9]{64}$/u,DO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ss=512*1024;function MO(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function FO(e,t){let i=Na.resolve(e),r=Na.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Na.relative(i,r).split(Na.sep).filter(Boolean)]){o&&(a=Na.join(a,o));let s=await _t.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await _t.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Zb(e){for(let t of e){let i=await _t.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!MO(t,i)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function LO(e){if(!HO.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function BO(e){let t=DO.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function qO(e,t,i){return Qi(H(e,t),LO(i))}async function VO(e,t,i){let r=await FO(i,Na.dirname(e)),n=await _t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>ss)throw new Error(`Native check receipt exceeds ${ss} bytes`);let[a,o]=await Promise.all([_t.realpath(t),_t.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":wp.O_RDONLY|wp.O_NOFOLLOW|wp.O_NONBLOCK,c=await _t.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await Zb(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Xl(n,l)||!Xl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=ss+1-p,E=await c.read(v,0,Math.min(v.length,y),null);if(E.bytesRead===0)break;if(p+=E.bytesRead,p>ss)throw new Error(`Native check receipt exceeds ${ss} bytes`);f.push(Buffer.from(v.subarray(0,E.bytesRead)))}let[h,m,N]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await Zb(r),!m.isFile()||m.isSymbolicLink()||N!==o||!$(a,N)||!Xl(l,h)||!Xl(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ek(e,t,i){let r=BO(i),n=H(e,t),a=qO(e,t,r),o=j(e,a);await T(o,a);let s=Dl(await VO(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var cs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var fz=64*1024;var hz=3600*1e3;var pz=UO(GO);var KO=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function tk(e,t){let i=[];for(let r of KO){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function ik(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ek(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Pr=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}};function YO(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function XO(e){let t=YO(e.bundle.baseline),i=await mh(e.paths,t,{origin:"explicit",now:e.now});return Fh({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function nk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ts(e.paths,e.state.name,e.state.implementation_scope),i=await ga({changeDir:re(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await XO({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function ak(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await nk(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function QO(e){let t=await Q({root:re(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Fw(t.text)}}function ZO(e){let{receipt:t,implementationScope:i}=e,r=[],n=Mh({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function e0(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Jh(e.implementationScope.scope.declaredArtifacts)}}async function rk(e){let t=await is(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=tk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Pr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await ik({paths:e.paths,state:e.state,receipt:t});if(n){let a=ZO({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function t0(e){let t=e0({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await rk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Pr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await rk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Pr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Pr(i)}function yp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ql(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:yp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([nk(e),ma(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:yp(e.state.verification_result,"stale"),envelope:null};let r=await QO({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await t0({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:yp(e.state.verification_result,"invalid"),envelope:null}}}function r0(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function sk(e){try{return await i0.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function n0(e,t){try{return(await Q({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function a0(e,t,i){let r=Il(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=ok.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await n0(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Q({root:re(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function o0(e,t){return sk(ze(e,t))}async function Zl(e){let t=e.now??new Date,i=await $e(e.paths,e.name),r=await wt(e.paths,e.name),n=await Ne(e.paths.projectRoot),a=r0(i.name,t),o=ok.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>a0(e.paths,i.name,v))),Ql({paths:e.paths,state:i,now:t}),Bl(e.paths,i.name),na(e.paths,i.name),aa(e.paths,i.name),o0(e.paths,i.name),sk(o)]);return RN({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Np}from"node:fs";import Ii from"node:path";var s0="comet.native.archive-tree.v1",c0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function uk(e){let t={...c0,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function ck(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function lk(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function dk(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await pt({root:e,directory:t,label:`Native Archive content directory ${Ii.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=ck(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ii.join(t,u.name),f=Ii.relative(e,d).replaceAll("\\","/"),p=await Np.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){lk(i,{ref:f,kind:"directory"},r,n),await dk(e,d,i,r,n,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await ie({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);lk(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await pt({root:e,directory:t,label:`Native Archive content directory ${Ii.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(ck(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ii.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function fk(e,t={}){let i=uk(t);e=Ii.resolve(e);let r=await Np.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await dk(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return F(`${s0}\0${o}`)}async function Qt(e,t={}){let i=uk(t);e=Ii.resolve(e);let r;try{r=await Np.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ie({root:Ii.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ii.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await fk(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Qe}from"node:fs";import Pe from"node:path";var kp=16*1024*1024,l0=256*1024,u0=16*1024,ls="comet.native.archive-cas.v1";function d0(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Pe.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Oe(e,t){let i=d0(e,t);return T(j(e,i),i)}function Rr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function ba(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ut(e){let t=await Qt(e.target);if(!Rr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ba(t)}`);return t}async function Sp(e,t){let i=await si(e,t),r=await ie({root:e.runtimeDir,file:i.journal,maxBytes:l0,label:`Native Archive transaction journal ${t}`}),n=sl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function eu(e,t,i){let r=sl({...t,status:i}),n=await si(e,r.id);return await te(n.journal,r,{containedRoot:e.runtimeDir}),r}function tu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function hk(e){return{...tu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function xr(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function f0(e,t){return xr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ee(e){try{return await Qe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vi(e){let t=await Qe.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=hk(t),r=await ie({root:j(e.paths,e.file),file:e.file,maxBytes:kp,label:e.label}),n=await Qe.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!f0(i,hk(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:tu(n),size:r.size}}function h0(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==ls||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:ls,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function gi(e,t,i,r){let n=await si(e,t.id),a=Pe.join(n.backups,".cas"),o=`.${Pe.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Pe.join(a,`${i.id}.original.json`),postRecord:Pe.join(a,`${i.id}.post.json`),candidate:Pe.join(a,`${i.id}.candidate`),originalQuarantine:Pe.join(Pe.dirname(r),`${o}.original`),rollbackQuarantine:Pe.join(Pe.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Tt(e){if(!await ee(e.file))return null;let t=await ie({root:e.paths.runtimeDir,file:e.file,maxBytes:u0,label:`Archive CAS ${e.operation.id} ${e.role} record`});return h0(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function iu(e){let t=await Tt(e);if(t){if(!xr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await oi({root:e.paths.runtimeDir,directory:Pe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ls,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await te(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Tt(e);if(!r||!xr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Se(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!xr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function p0(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await iu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Se({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function m0(e){if(!await ee(e.quarantine)||await ee(e.target))return;let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Qe.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Qe.lstat(e.quarantine),Qe.lstat(e.target)]);if(!xr(tu(i),tu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Qe.unlink(e.quarantine),await t.verify()}async function gk(e){if(await ee(e.quarantine)){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Qe.rename(e.target,e.quarantine),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await m0(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function on(e){if(!await ee(e.file))return;await Se(e);let t=await Jt({root:j(e.paths,e.file),directory:Pe.dirname(e.file),label:e.label});await t.verify(),await Se(e),await Qe.unlink(e.file),await t.verify()}async function pk(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Oe(e,t.target),n=await Oe(e,t.backup),a=await Qt(n);if(a!==null){if(!Rr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ut({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await sr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:kp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ut({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function wk(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ee(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Se({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await pk(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ee(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await p0({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await pk(e.paths,e.operation,e.hooks),await gk({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function mk(e){let t=await gi(e.paths,e.journal,e.operation,e.target);return await ee(t.candidate)?(await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await oi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await sr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:kp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function v0(e){let t=e.operation.stagedHash,i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ee(e.target))return await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ee(i.candidate)&&await on({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ee(e.target)){let c=await mk(e),l=await vi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await iu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await on({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await mk(e),a=await vi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await oi({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Se({paths:e.paths,file:n,operation:e.operation,record:{schema:ls,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Qe.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await iu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await on({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function g0(e,t,i,r){let n=await Oe(e,i.target),a=await Oe(e,i.staged);if(await ut({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await gi(e,t,i,n);(!await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ee(n))&&await wk({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Qt(n);if(o!==null&&!Rr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${ba(o)}`)}await v0({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ut({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function w0(e,t,i,r){let n=await Oe(e,i.target);await wk({paths:e,journal:t,operation:i,target:n,hooks:r}),await ut({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function y0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(n===null&&Rr(a,t.expectedSourceHash,"directory"))){if(!Rr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ba(n)}, target=${ba(a)}`);await Qe.mkdir(Pe.dirname(r),{recursive:!0}),await Qe.rename(i,r),await ut({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function N0(e,t,i,r){return i.type==="write"?g0(e,t,i,r):i.type==="remove"?w0(e,t,i,r):y0(e,i)}function b0(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function k0(e,t,i,r){let n=await Oe(e,i.target);if(i.type==="write"){let a=await Oe(e,i.staged);await ut({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await gi(e,t,i,n),s=await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Se({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ut({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Tt({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ee(o.originalQuarantine))await Se({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ut({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ut({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await gi(e,t,i,n),o=await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ee(a.originalQuarantine))await Se({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ut({target:await Oe(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ut({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function yk(e,t,i){let r=t.status==="prepared"?await eu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await lr(e,r.id),a=b0({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await k0(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Rt(e,r.id,"operation-started",l.id),await N0(e,r,l,i),await Rt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Sp(e,r.id),r}async function S0(e){try{return await Se(e),!0}catch{return!1}}async function E0(e){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Qe.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function bp(e){if(e.operation.type!=="write")return;let t=await gi(e.paths,e.journal,e.operation,e.target);if(!await ee(t.candidate))return;let i=await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await on({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ls,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function P0(e,t,i,r){let n=await Oe(e,i.target),a=await gi(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Tt({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ee(a.candidate)&&await ee(n)){let l=await vi({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await vi({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});xr(l.identity,u.identity)&&(c=await iu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ee(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Se({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ee(n)&&!(s!==null&&await S0({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Qt(n);if(Rr(u,o)){await bp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await gk({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ee(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ee(n)){if(!s||!await ee(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await E0({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ee(a.originalQuarantine)&&await on({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ee(a.rollbackQuarantine)&&await on({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await bp({paths:e,journal:t,operation:i,target:n}),await ut({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function R0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(Rr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Rr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ba(n)}, target=${ba(a)}`);await Qe.mkdir(Pe.dirname(i),{recursive:!0}),await Qe.rename(r,i)}}async function Nk(e,t,i){let r=await lr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await eu(e,t,"rolling-back");await Rt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await R0(e,o):await P0(e,n,o,i));return await Rt(e,n.id,"rollback-completed"),n=await eu(e,n,"rolled-back"),n}async function vk(e,t,i){let r=await Oe(e,i.target);if(i.type==="write"){let n=await gi(e,t,i,r),a=await Tt({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Se({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ut({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function x0(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Oe(e,i.target),n=await gi(e,t,i,r);if(await ee(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await vk(e,t,i),i.expectedTargetHash!==null){let a=await Tt({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ee(n.originalQuarantine)&&await on({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await bp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await vk(e,t,i)}async function ru(e,t,i){return i==="commit"&&await x0(e,t),await Rt(e,t.id,i),i==="commit"?eu(e,t,"committed"):t}var sJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as C0}from"fs";import A0 from"path";var Ep="comet.selection.v2",_0=16*1024;function nu(e){return A0.join(e,".comet","current-change.json")}function T0(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function bk(e){return e===null||typeof e=="string"}function I0(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(!T0(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&&!bk(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ep,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ep)throw new Error(`current change selection schema must be ${Ep}`);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(!bk(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 Pp(e){let t;try{let r=nu(e),{bytes:n}=await qr(r,_0,{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",...I0(t)}}async function kk(e){await C0.rm(nu(e),{force:!0})}async function Sk(e,t,i){let r=await Pp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await kk(e),!0)}import{promises as fs}from"node:fs";import _r from"node:path";var _p=hn(Lr(),1);import{promises as Ak}from"node:fs";import It from"node:path";import{execFileSync as j0}from"node:child_process";var $0=3e4,O0=8*1024*1024,Rp=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 H0(e,t){try{return j0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$0,maxBuffer:O0,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Rp(e,t,r)}}function xp(e,t){return H0(e,t).trim()}var Ek="children.yaml",Cp="comet.native.children.v1",D0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,M0=new Set(["schema","children"]),F0=new Set(["name","depends_on","covers"]);function Pk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Rk(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 xk(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 Ap(e,t){let i=It.normalize(It.resolve(e)),r=It.normalize(It.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function L0(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 B0(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function q0(e,t){let i=(0,_p.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Pk(i.toJS({mapAsMap:!1}),"Native children contract");if(Rk(r,M0,"Native children contract"),r.schema!==Cp)throw new Error(`Native children schema must be ${Cp}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Pk(s,`Native child ${c}`);if(Rk(l,F0,`Native child ${c}`),typeof l.name!="string"||!D0.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:xk(l.depends_on,`Native child ${l.name} depends_on`),covers:xk(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return L0(n),t&&B0(n,t),{schema:Cp,children:n}}async function Tp(e){let t=It.join(e.changeDir,Ek);try{await Ak.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await Q({root:e.changeDir,ref:Ek});return{contract:q0(i.text,e.acceptanceIds),size:i.size}}function Ip(e){return M("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function V0(e){let t=Rn(e.projectRoot);t.some(r=>Ap(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>It.resolve(n)))]){let n=await Ne(r);n&&i.push({projectRoot:r,paths:await Be(r,n.native.artifact_root),parent:Ap(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function W0(e,t){let i=It.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ue(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function z0(e,t){let i;try{i=await Ak.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=It.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ue(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function J0(e,t,i){let r=It.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${It.sep}`))return null;let n=r.split(It.sep).join("/");try{let a=(0,_p.parseDocument)(xp(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:nt(a.toJS({mapAsMap:!1}))}catch{return null}}function G0(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Ck(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function us(e){let t=It.join(e.paths.changesDir,e.state.name),i=await Tp({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=Ip({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await V0(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:h})=>h)),c=new Map,l=new Map;for(let h of a){let m=h.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await z0(h,s)){let y={...N,source:h,committedState:J0(h,N.file,m)};c.set(N.state.name,[...c.get(N.state.name)??[],y])}for(let N of s){let y=await W0(h,N);y&&l.set(N,[...l.get(N)??[],{source:h,state:y}])}}let u=new Map;for(let h of i.contract.children){let m=(c.get(h.name)??[]).find(({source:E,committedState:S})=>E.parent&&S?.name===h.name&&Ck(S,o));if(m){u.set(h.name,{kind:"done",phase:m.state.phase,projectRoot:m.source.projectRoot,message:null});continue}let N=c.get(h.name)?.[0];if(N){u.set(h.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=l.get(h.name)??[];y.length>1?u.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&u.set(h.name,G0(y[0].state,y[0].source,o))}let d=new Map(i.contract.children.map(h=>[h.name,h])),f=new Map,p=h=>{let m=f.get(h);if(m)return m;let N=d.get(h),E=N.depends_on.map(p).every(({status:g})=>g==="done"),S=u.get(h),k=S?.kind==="active"&&E?N.depends_on.filter(g=>!(c.get(g)??[]).some(({source:P,committedState:D})=>Ap(P.projectRoot,S.projectRoot)&&D?.name===g&&Ck(D,o))):[],b,R=S?.message??null;S?.kind==="done"?(b=E?"done":"blocked",E||(R=`Native child ${h} was merged before its dependencies`)):S?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(R=`Native child ${h} does not include merged dependencies: ${k.join(", ")}`):R=`Native child ${h} started before its dependencies merged`):S?.kind==="blocked"?b="blocked":(b=n&&E?"ready":"pending",n||(R="Parent Shape confirmation is required"));let w={name:h,dependsOn:[...N.depends_on],covers:[...N.covers],status:b,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:R};return f.set(h,w),w},v=i.contract.children.map(({name:h})=>p(h));return{contractHash:r,confirmed:n,parentBranch:o,children:v,readyChildren:v.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:v.every(({status:h})=>h==="done")}}var au="skill-coordinated";function K0(e){return e.state_version+1}function Y0(e){return e.map(t=>({...t,result:"pending",reason:null}))}function X0(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:ir(e.summary),completed_at:e.completedAt}}function jp(e){let t=nt(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=Ln(t,X0({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return nt({...r,phase:"build",status:"active",state_version:K0(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:Y0(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 Tk}from"node:fs";import ds from"node:path";function ou(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function su(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 wi(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 _k(e,t){return e===null?null:wi(e,t)}function lu(e,t,i=0){if(!Number.isSafeInteger(e)||ewi(l,`${i}.argv[${u}]`,!0)),a=cu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=$p(r.startedAt,`${i}.startedAt`),s=$p(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=lu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:wi(r.id,`${i}.id`),name:wi(r.name,`${i}.name`),operationId:wi(r.operationId,`${i}.operationId`),status:a,repeatable:Z0(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:lu(r.executionCount,`${i}.executionCount`),argv:n,cwd:Op(r.cwd,`${i}.cwd`),exitCode:Q0(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:wi(r.log,`${i}.log`)}}function Hp(e){let t="Native local execution state",i=ou(e,t);if(su(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Po)throw new Error(`Native local execution schema must be ${Po}`);let r=ou(i.workspace,"Native local workspace");su(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=ou(i.execution,"Native local execution");su(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=$p(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:wi(o.operationId,"Native local execution.operationId"),stage:cu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:cu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:_k(o.executionId,"Native local execution.executionId"),status:cu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:lu(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(eH);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:Po,change:wi(i.change,"Native local change"),basedOnStateVersion:lu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Op(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Op(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:_k(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function sn(e){return Hp({schema:Po,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:ds.resolve(e.projectRoot),worktreeRoot:ds.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function uu(e){let t;try{t=await Tk.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 Hp(i)}async function Cr(e,t,i={}){let r=Hp(t);await Tk.mkdir(ds.dirname(e),{recursive:!0}),await te(e,r,i)}import{promises as tH}from"node:fs";function Ar(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` +${ko(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function Mj(e){if(Uo(e)<=tn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=BN("sha256");a.update(`${_j} +`),e.omissionOverflow&&pr(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,pr(a,"omission",f)},s=f=>{r+=1,n+=1,pr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Uo(u)>tn;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function $h(e){let t=Ei(e),i=t.entries.map((n,a)=>$j(n,`Snapshot entry ${a}`));if(i.sort(Hj),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>Oj(n,`Snapshot omission ${a}`));return r.sort(Dj),Mj({schema:qN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Ko(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:mr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>We(i.path,r.path)||We(i.kind,r.kind))}function Yo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function ON(e){return e?{hash:e.hash,size:e.size}:null}function Dh(e,t,i){let r=0,n=0;for(;r=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:ON(c),after:ON(l)})}}function zN(e,t){return{...e,attributedTo:t.filter(i=>Yo(i,e.path))}}function Mh(e){let t=Ko(e.declaredArtifacts),i=[];return Dh(e.baseline,e.current,r=>{i.push(zN(r,t))}),i}function xi(e,t){return{id:`scope:${M(Cj,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function Fj(e,t){let i=t.omitted.map(r=>xi({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(xi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(xi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function HN(e,t){return Fj(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Oh(e,t){return We(e.kind,t.kind)||We(e.source,t.source)||jj(e.path,t.path)||We(e.id,t.id)}function Lj(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Oh)}function JN(e){return[...new Set(e.map((t,i)=>mr(t,`Git path ${i}`)))].sort(We)}function DN(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function Bj(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function GN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=JN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:DN(e.baseCommit,"Native external drift base commit"),targetBranch:Bj(e.targetBranch,"Native external drift target branch"),targetCommit:DN(e.targetCommit,"Native external drift target commit"),paths:t}}function UN(e){if(typeof e.contractHash!="string"||!Hh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Ko(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:JN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:GN(e.externalDrift)}}}function qj(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Dh(e,t,p=>{let v=i.some(h=>Yo(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length{if(i>=e.detailedChangeCount){pr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Yo(o,n.path)&&(a+=1,pr(t,"change-attribution",o));pr(t,"change-end",{attributionCount:a}),a===0&&pr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&pr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function YN(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=qj(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(P=>!w.has(P)||n.some(D=>Yo(D,P)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=M(Jo,e),c=M(Jo,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=Ij)break;l.push(xi({kind:"snapshot-omission",source:R,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${R} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...HN("baseline",e),...HN("current",t),...o.totalChanges===0&&a===null?[xi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>R.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!R.has(w))}},v=R=>{let w=o.candidates.slice(0,R.detailedChangeCount),g=w.filter(Dt=>Dt.attributedTo.length===0&&!u.has(Dt.path)),P=o.totalChanges-w.length,D=o.totalUnattributed-g.length,O=d-R.detailedOmissionCount,De=D+O,ce=[...g.map(Dt=>xi({kind:"unattributed-change",source:"implementation-scope",path:Dt.path,evidence:{after:Dt.after,before:Dt.before,changeKind:Dt.kind}},`Changed path is not covered by a declared artifact: ${Dt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...De>0?[KN(R.overflowHash,{changes:P,unattributed:D,unresolved:De})]:[]],Z=Lj(ce),Zt=R.includeGitAdvisory?p():void 0;return{schema:Ih,contractHash:r,baselineProjectionRef:jh(s),baselineProjectionHash:s,currentProjectionRef:jh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:Z,noCodeReason:a,...Zt?{gitAdvisory:Zt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,N=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:y});if(Uo({...R,scopeHash:y})<=tn)break;if(N){N=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>h||d>m?Wj({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,k=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:S}),b={...k,scopeHash:M(VN,k)};if(Uo(b)>tn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Fh(e){let t=$h(e.baseline),i=$h(e.current),r=UN(e);return{authority:r,baseline:t,current:i,scope:YN(t,i,r)}}var zj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function en(e,t){if(typeof e!="string"||!Hh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MN(e,t,i){let r=jh(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ca(e,t){let i=di(e,"Native snapshot projection");if(fi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==qN)throw new Error("Native snapshot projection schema is invalid");let r=Ei({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=$h(r);if(M(Jo,i)!==M(Jo,n))throw new Error("Native snapshot projection is not canonical");let a=M(Jo,n);if(t!==void 0&&en(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Lh(e,t){let i=di(e,`Declared artifact ${t}`);if(fi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:mr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function FN(e,t){if(e===null)return null;let i=di(e,t);return fi(i,["hash","size"],[],t),{hash:en(i.hash,`${t} hash`),size:sa(i.size,`${t} size`)}}function LN(e,t){let i=di(e,`Implementation change ${t}`);if(fi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Lh),n=Ko(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=FN(i.before,`Implementation change ${t} before`),o=FN(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:mr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function Jj(e,t){let i=di(e,`Unresolved scope ${t}`);fi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?WN(i.path,`Unresolved scope ${t} path`):mr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Go(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>mr(n,`${t} ${a}`)),r=[...new Set(i)].sort(We);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function XN(e){let t=di(e,"Native implementation external drift");if(fi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Go(t.paths,"Native external drift paths");return GN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function la(e){let t=di(e,"Native implementation scope"),i=[...zj].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(fi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Ih)throw new Error("Native implementation scope schema is invalid");let r=en(t.contractHash,"Implementation scope contractHash"),n=en(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=MN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=en(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=MN(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Lh);if(JSON.stringify(c)!==JSON.stringify(Ko(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(LN),u=[...l].sort((g,P)=>We(g.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(g=>g.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(g=>`${g.kind}:${g.path}`));if(l.some(g=>g.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(P=>Yo(P,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(LN),p=t.externalDrift===void 0?void 0:XN(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(Jj),N=m.filter(g=>g.kind==="scope-detail-overflow");if(N.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=N[0]===void 0?null:Vj(N[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,S=[...h.map(g=>xi({kind:"unattributed-change",source:"implementation-scope",path:g.path,evidence:{after:g.after,before:g.before,changeKind:g.kind}},`Changed path is not covered by a declared artifact: ${g.path}`)),...l.length+(y?.changes??0)===0&&E===null?[xi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Oh))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(S.sort(Oh))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let g=di(t.gitAdvisory,"Implementation scope Git advisory");if(fi(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=Go(g.changedPaths,"Git changed paths"),D=Go(g.pathsPresentInSnapshotChanges,"Git present paths"),O=Go(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),De=[...D,...O].sort(We);if(JSON.stringify(De)!==JSON.stringify(P)||O.some(ce=>l.some(Z=>Z.path===ce)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:D,pathsAbsentFromSnapshotChanges:O}}let R={schema:Ih,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:E,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},w=en(t.scopeHash,"Implementation scope scopeHash");if(M(VN,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function Gj(e){let t=di(e,"Native implementation scope authority");if(fi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Lh);if(JSON.stringify(i)!==JSON.stringify(Ko(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Go(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:XN(t.externalDrift),a=UN({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Xo(e){let t=di(e,"Native implementation scope bundle");fi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Gj(t.authority),r=ca(t.baseline),n=ca(t.current),a=la(t.scope),o=YN(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function QN(e){let t=la(e.scope);return Xo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import ZN from"node:path";var Uj=/\b(Bearer|Basic)\s+[^\s"']+/giu,Kj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Yj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Xj=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,Qj=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,Zj=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,e$=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function At(e){return e.replace(Uj,"$1 [REDACTED]").replace(Kj,"[REDACTED PRIVATE KEY]").replace(Yj,"$1[REDACTED]@").replace(Xj,"[REDACTED TOKEN]").replace(Qj,'$1"[REDACTED]"').replace(Zj,"$1$2$1$3$4[REDACTED]$4").replace(e$,"$1$2[REDACTED]")}var tb=/^[a-f0-9]{64}$/u;var t$="comet.native.acceptance-trace.v2",i$="comet.native.partial-allowance.v1",r$="comet.native.verification-evidence.v2";function Ci(e,t){if(!tb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ib(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function rb(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Bh(e,t,i=2e3){let r=At(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Qo(e,t){let i=ZN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||ZN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function n$(e,t,i){let r=Qo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ii(r),a=r.toLowerCase(),o=i?Qo(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function qh(e){let t=Qo(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function ua(e,t){return et?1:0}function $l(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ol(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function nb(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function eb(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function a$(e){let t=$l(e,"Native acceptance trace");if(Ol(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!tb.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Qo(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=$l(o,`Native acceptance trace entry ${s}`);if(Ol(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>qh(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ua))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Qo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Bh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>ua(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Ci(t.traceHash,"Native acceptance trace hash");if(M(t$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Hl(e){let t=$l(e,"Native partial allowance");if(Ol(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(ua))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:rb(t.change),scopeHash:Ci(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Bh(t.reason,"Partial allowance reason"),confirmedSummary:Bh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:ib(t.sourceRevision),confirmedAt:nb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Ci(t.allowanceHash,"Native partial allowance hash");if(M(i$,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Zo(e){let t=$l(e,"Native verification evidence");if(Ol(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Ci(t.implementationScopeHash,"Native verification implementation scope hash"),r=a$(t.acceptanceTrace),n=Ci(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Ci(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>qh(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ua)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(ua);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>qh(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ua)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:rb(t.change),sourceRevision:ib(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ci(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:eb(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:n$(t.reportRef,"Native verification report ref"),reportHash:Ci(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:eb(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:nb(t.createdAt,"Native verification timestamp")},d=Ci(t.envelopeHash,"Native verification envelope hash");if(M(r$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import ab from"node:path";var ob="comet.native.check-receipt.v1",o$="comet.native.check-receipt.v1",da="scoped-text-safety",Vh=1,lt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),s$=/^[a-f0-9]{64}$/u,c$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,l$="comet.native.checker-policy.v1",u$="comet.native.check-input.v1",d$=2048,sb=M(l$,{policy:da,version:Vh,limits:lt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),f$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),cb=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],ub=["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"],h$=new Set(ub);function vr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Ai(e,t){if(typeof e!="string"||!s$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function db(e,t){let i=yt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function lb(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function p$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>d$||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=ab.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||ab.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function m$(e){let t=vr(e,"Native check receipt checker");gr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=vr(t.limits,"Native check receipt limits");if(gr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==da||t.version!==Vh||t.hash!==sb||i.maxFiles!==lt.maxFiles||i.maxFileBytes!==lt.maxFileBytes||i.maxTotalBytes!==lt.maxTotalBytes||i.maxIssues!==lt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:da,version:Vh,hash:sb,limits:{...lt}}}function v$(e){let t=vr(e,"Native check receipt contract");return gr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Ai(t.expectedHash,"Native check expected contract hash"),beforeHash:Ai(t.beforeHash,"Native check before contract hash"),afterHash:Ai(t.afterHash,"Native check after contract hash")}}function g$(e){let t=vr(e,"Native check receipt implementation");return gr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Ai(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Ai(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Ai(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Ai(t.afterSnapshotHash,"Native check after snapshot hash")}}function w$(e,t){let i=vr(e,`Native check batch ${t}`);gr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:yt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:yt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:yt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:yt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:yt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:yt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>lt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>lt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function y$(e){let t=vr(e,"Native check receipt counts");gr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:yt(t.filesSelected,"Native check filesSelected"),filesScanned:yt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:yt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:yt(t.bytesScanned,"Native check bytesScanned"),issueCount:yt(t.issueCount,"Native check issueCount"),recordedIssueCount:yt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(w$):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>lt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>lt.maxFiles||i.bytesScanned>lt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function N$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||cb.indexOf(e.kind)-cb.indexOf(t.kind)}function b$(e){if(!Array.isArray(e)||e.length>lt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=vr(r,`Native check issue ${n}`);if(gr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!f$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:p$(a.path,`Native check issue ${n} path`),line:db(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(N$);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function k$(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!h$.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=ub.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function S$(e){return M(u$,e)}function Dl(e){let t=vr(e,"Native check receipt");if(gr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==ob)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!c$.test(t.change))throw new Error("Native check receipt change name is invalid");let i=db(t.sourceRevision,"Native check source revision"),r=m$(t.checker),n=v$(t.contract),a=g$(t.implementation),o=S$({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Ai(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=lb(t.startedAt,"Native check receipt startedAt"),c=lb(t.endedAt,"Native check receipt endedAt");if(cu.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=k$(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>lt.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>lt.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:ob,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Ai(t.receiptHash,"Native check receipt content hash");if(M(o$,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var zh="comet.native.verification-receipt.v3",E$=zh,P$="comet.native.declared-artifacts.v1",R$=/^[a-f0-9]{64}$/u,x$=/^acceptance-[a-f0-9]{64}$/u,C$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,_$=4096,T$=256,I$=1024;function fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function wr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function _i(e,t){if(typeof e!="string"||!R$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=At(e).trim();if(!i||i.length>_$||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Wh(e,t){let i=Yt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function es(e,t,i=Yt,r=!1,n=T$){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function j$(e,t){if(typeof e!="string"||!x$.test(e))throw new Error(`${t} is invalid`);return e}function $$(e){let t=fa(e,"Native verification receipt bindings");if(wr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!C$.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:_i(t.contractHash,"Native verification receipt contract hash"),scopeHash:_i(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:_i(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:_i(t.artifactHash,"Native verification receipt artifact hash")}}function O$(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=A$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function H$(e,t,i,r){let n=fa(t,`Native ${e} evidence`);if(e==="automated-check"){if(wr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Wh(n.startedAt,"Native automated-check start time"),o=Wh(n.endedAt,"Native automated-check end time");if(Date.parse(o)({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var mb=/^[a-f0-9]{64}$/u,yr=tn,vW=3*yr;function Gh(e,t){let i=hi.relative(e,t);return i===""||!hi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${hi.sep}`)}function F$(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function fb(e){let t=await Xt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Xt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function L$(e,t){let i=hi.resolve(e),r=hi.resolve(t);if(!Gh(i,r))throw new Error("Native evidence path is outside its change");let n=[await fb(i)],a=i;for(let o of hi.relative(i,r).split(hi.sep).filter(Boolean)){a=hi.join(a,o);let s=await fb(a);if(!Gh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function hb(e){for(let t of e){let i=await Xt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!F$(t,i)||await Xt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function B$(e,t,i={}){let r=await L$(t,hi.dirname(e));await i.afterParentChainCaptured?.();let n=await Xt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Xt.realpath(e);if(!Gh(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Xt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await hb(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fl(s,n)||!Fl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>yr)throw new Error(`Native evidence document exceeds ${yr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=yr+1-d,N=await o.read(f,0,Math.min(f.length,m),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>yr)throw new Error(`Native evidence document exceeds ${yr} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await hb(r),!v.isFile()||v.isSymbolicLink()||h!==a||!Fl(s,p)||!Fl(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function pa(e,t){if(!mb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function vb(e){return pa("reports",e)}async function q$(e,t,i,r,n){if(!mb.test(i))throw new Error("Native report evidence hash is invalid");let a=await rn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||M$("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function ha(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function V$(e,t,i,r,n){let a=pa(i,r);return n?hi.join(n,...a.split("/")):Qi(H(e,t),a)}async function rn(e){let t=V$(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),B$(t,i,e.hooks)}function pb(e,t){return ca(e,t)}function W$(e,t){let i=la(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function z$(e,t,i){let r=Hl(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function J$(e,t,i){let r=Zo(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function G$(e,t,i,r=!1,n){let a=await Ll(e,t,i.implementationScopeRef,void 0,n);if(r&&await q$(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await gb(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function ts(e,t,i,r,n){let a=ha(i,"scopes"),o=W$(await rn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=ha(o.baselineProjectionRef,"snapshots"),c=ha(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([rn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>pb(d,s)),rn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>pb(d,c))]);return QN({baseline:l,current:u,scope:o})}async function Ll(e,t,i,r,n){return(await ts(e,t,i,r,n)).scope}async function gb(e,t,i,r,n){let a=ha(i,"allowances");return z$(await rn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function is(e,t,i,r,n){let a=ha(i,"receipts"),o=Ml(await rn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function ma(e,t,i,r,n){let a=ha(i,"verifications"),o=J$(await rn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await G$(e,t,o,!1,n),o}var U$=4096;async function K$(e,t=ct.maxChanges){try{let i=await pt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function wb(e,t){let i=await $e(e,t),[r,n]=await Promise.all([i.implementation_scope?Ll(e,t,i.implementation_scope):null,wt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Bl(e,t,i={}){let n=(await K$(e,U$)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await wb(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await wb(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=jN([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as fO}from"fs";import hO from"path";import{isDeepStrictEqual as Vl}from"util";var va={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var Y$=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function X$(e,t){return et?1:0}function Q$(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!Y$.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(X$)}function Uh(e=[]){return Q$(e,"Native repair failed check IDs",va.maxFailedCheckIds,!0)}function yb(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function Z$(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:yb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&yb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length=0;n-=1){let a=t[n];if(Z$(r,a))break;i+=1,r=a}return i}function Yh(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var Nb="repairStagnation",Nt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},tO=/^[a-f0-9]{64}$/u;var iO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),rO=["data","runId","sequence","timestamp","type"],bb=["disposition","overrideSummaryHash","signatureHash"],nO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],kb=12;function Qh(e,t){return et?1:0}function Sb(e,t,i){let r=Object.keys(e).sort(Qh);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function ql(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function rs(e,t){if(typeof e!="string"||!tO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function aO(e){if(!Array.isArray(e)||e.length>va.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Qh)}function Eb(e){if(typeof e!="string"||e.length===0||e.length>Nt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Xh(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Nt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Nt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Nt.maxTextCharacters&&(!n||e.length>Nt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Nt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Xh(s,t+1,i,`${r}[${c}]`));return}let a=ql(e,r),o=Object.keys(a);if(o.length>Nt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Nt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Xh(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function oO(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function sO(e,t,i){let r=ql(e,`Native repair trajectory event ${t+1}`);if(Sb(r,rO,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(oO(r.timestamp),typeof r.type!="string"||!iO.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Eb(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Xh(r.data,0,n,"Native trajectory event data"),ql(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Zh(e){let t=ql(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Qh),r=i.length===bb.length&&i.every((l,u)=>l===bb[u]);r||Sb(t,nO,"Native repair trajectory projection");let n=rs(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:rs(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=rs(t.contractHash,"Native repair trajectory contract hash"),s=aO(t.failedAcceptanceIds),c=Uh(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function cO(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function lO(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??kb;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Kh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":aa.kind==="failure"),n=i?.maxVerifyFailures??kb;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Pb(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Nt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Eb(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;lNt.maxTotalDataNodes||c>Nt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?rs(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?rs(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Nb)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Zh(f[Nb]);if(cO(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),lO(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");uO(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>va.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Rb(e){return Pb(e).history}function xb(e){let t=Pb(e).latestProjection;return t?{...t}:null}var pi={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:[]},ns=F("comet-native-runtime:v3:scope-reopen"),dO=[{skillVersion:"3",skillHash:F("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function Cb(e){return e.skillVersion===pi.definition.metadata.version&&e.skillHash===ns||dO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var ep={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Nr(e){let i={sequence:(await Xe(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Uy(e.changeDir,e.run.trajectoryRef,i),i}async function nn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Ky(e.changeDir,e.run.checkpointRef,t),t}function Ab(e){return F(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Db=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],pO=new Set(Db),Mb=new Set([...Db,"minimum_runtime_version","revision"]),mO=new Set([...Mb,"operation"]),vO=512*1024,tp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),gO=new Set([...tp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),as=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ze(e,t){return hO.join(H(e,t),"transition.json")}function wO(e){return`transition-${e}`}async function yO(e,t,i){let r=wO(t);return er(e,r,i)}async function an(e,t,i,r){let n=await yO(e,t,i);try{return await r()}finally{await tr(n)}}function zl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function rp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Wl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){return Vl(e,t)}function ip(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!gO.has(u)),a=[...tp].find(u=>!Object.hasOwn(i,u)),o=tp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Yh(i.summary,"Native transition journal event summary"),At(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Yh(i.noCodeReason,"Native transition journal event no-code reason"),At(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Zh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function NO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return ip({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return ip(e,t)}function np(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?NO(e.eventData,e.evidenceHash):ip(e.eventData,e.evidenceHash),n=hr(e.nextRun),a=e.previousRun===null?null:hr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function _b(e,t,i=!1){if(e.skill!==pi.definition.metadata.name||(i?!Cb(e):e.skillVersion!==pi.definition.metadata.version||e.skillHash!==ns)||e.orchestration!==pi.definition.orchestration.mode||e.pendingRef!==vt.pendingRef||e.trajectoryRef!==vt.trajectoryRef||e.contextRef!==vt.contextRef||e.artifactsRef!==vt.artifactsRef||e.checkpointRef!==vt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Tb(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ib(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function ap(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(_b(o,"next Run",r||a!==null),Ib(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(_b(a,"previous Run",!0),Ib(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Vl(Tb(a),Tb(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function bO(e,t,i){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Fb(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function jb(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function op(e,t,i,r,n=!1){let a=i.eventData,o=jb(e),s=jb(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Vl(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Vl(e.spec_changes,t.spec_changes),l=Ab({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=bO(e.name,a.summary,t.spec_changes),l=F(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function sp(e,t){let i=zl(e);if(rp(i,mO),i.schema!==rr)throw new Error(`Expected Native transition schema ${rr}`);let r=Wl(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${rr} minimum_runtime_version must be ${3}`);let n=Wl(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=np(i,t),o=st(i.previousState),s=st(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(op(o,s,a,i.operation),ap(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:rr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function kO(e,t){let i=zl(e);if(rp(i,pO),i.schema!==Jr)throw new Error(`Expected Native transition schema ${Jr}`);let r=np(i,t,!0),n=Gr(i.previousState),a=Gr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return op(n,a,r,Fb(n,a,r.eventData),!0),ap(n,a,r,!0),{schema:Jr,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function cp(e,t){let i=zl(e);if(rp(i,Mb),i.schema!==Si)throw new Error(`Expected Native transition schema ${Si}`);if(Wl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Si} minimum_runtime_version must be 2`);let n=Wl(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=np(i,t,!0),o=ai(i.previousState),s=ai(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(op(o,s,a,Fb(o,s,a.eventData),!0),ap(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Si,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function SO(e,t){let i=zl(e);if(i.schema===rr)return{status:"current",journal:sp(i,t)};if(i.schema===Jr)return{status:"migration-required",journal:kO(i,t)};if(i.schema===Si)return{status:"migration-required",journal:cp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function lp(e,t){let i=ze(e,t),r=j(e,i);await T(r,i);try{let n=await ie({root:r,file:i,maxBytes:vO,label:`Native transition journal ${t}`});return SO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ti(e,t){let i=await lp(e,t);if(!i)return null;if(i.status==="migration-required")throw new as(t);return i.journal}function $b(e,t){if(mi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(mi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Ob(e,t){if(mi(e,t.nextState))return"next";if(mi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function EO(e){let{journal:t}=e;return Lb({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Lb(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Hb(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=EO({sequence:a.index+1,journal:t,type:a.event.type});if(!mi(Lb(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function Jl(e,t,i){if(await na(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Sl(e,t);let r=await Ti(e,t);if(!r)return null;let n=H(e,t),a=Hb(await Xe(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Ie(n),$e(e,t)]),c=$b(o,r),l=Ob(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Xr(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!mi(await Ie(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let m=await Tl(e,r.nextState,r.previousState.revision);if(!mi(m,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!mi(await $e(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Ti(e,t);if(!u||!mi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Hb(await Xe(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Nr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await Nr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await nn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[p,v]=await Promise.all([Ie(n),$e(e,t)]);$b(p,{...r,previousRun:r.nextRun}),Ob(v,{...r,previousState:r.nextState});let h=await Ti(e,t);if(!h||!mi(h,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await fO.rm(ze(e,t),{force:!0}),r.nextState}async function Bb(e,t,i){return he(e,`continue transition ${t}`,()=>an(e,t,`continue transition ${t}`,()=>Jl(e,t,i)))}import qb from"node:path";var PO="comet.native.contract.v1",RO="comet.native.acceptance-set.v1",Vb=/^[a-f0-9]{64}$/u,os={maxAcceptanceCriteria:Eo.maxCriteria};function Wb(e,t){let i=qb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||qb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function zb(e){return M("comet.native.contract-content.v1",e.replace(/\r\n?/gu,` +`))}function xO(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Vb))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Vb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Wb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:zb(e.markdown)},markdown:e.markdown}}function CO(e,t){return Jb(e.id,t.id)}function Jb(e,t){return et?1:0}function Gb(e){let t=Wb(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(xO).sort((d,f)=>Jb(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Vc(e.briefMarkdown,t,os.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Wc(f,d.source,os.maxAcceptanceCriteria-a.length)),a.push(...zc(f,d.source,os.maxAcceptanceCriteria-a.length)));if(a.sort(CO),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>os.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${os.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:zb(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=M(RO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(PO,u)}}var Gl={maxSpecs:64,maxFileBytes:lo,maxTotalBytes:4*1024*1024};async function ga(e){if(e.specChanges.length>Gl.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Q({root:e.changeDir,ref:e.briefRef,maxBytes:Gl.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Q({root:e.changeDir,ref:n.source,maxBytes:Gl.maxFileBytes});if(i+=a.size,i>Gl.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Gb({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as GO}from"node:child_process";import{promisify as UO}from"node:util";var w2=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as OO}from"fs";import wa from"path";var kr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},ya=/^[a-f0-9]{64}$/u;function Ul(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kl(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function br(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Ub(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function up(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||wa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=wa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function dp(e,t){return wa.join(H(e,t),"checkpoints","progress.json")}function Sr(e,t){return wa.join(H(e,t),"checkpoint-journal.json")}function fp(e,t,i){if(!ya.test(i))throw new Error("Native checkpoint manifest hash is invalid");return wa.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function _O(e){if(!ya.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function hp(e,t,i){let r=await ie({root:e,file:t,maxBytes:kr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function TO(e,t){let i=Ul(e,`checkpoint manifest artifact ${t}`);Kl(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=AO(br(i.path,`checkpoint artifact ${t} path`,4096)),n=ii(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!ya.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:up(i.size,`checkpoint artifact ${t} size`)}}function Yl(e,t){let i=Ul(e,"Native checkpoint manifest");if(Kl(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>kr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(TO),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=up(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>kr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function pp(e){return F(JSON.stringify(Yl(e,e.change)))}function mp(e,t){let i=Ul(e,"Native progress checkpoint");if(Kl(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Ub(i.previousRevision,"Native checkpoint previousRevision"),a=Ub(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=br(i.manifestHash,"Native checkpoint manifestHash",64);if(!ya.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=_O(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=br(i.inputHash,"Native checkpoint inputHash",64);if(!ya.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=br(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=up(i.artifactCount,"Native checkpoint artifactCount");if(u>kr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=br(i.summary,"Native checkpoint summary"),f=br(i.nextAction,"Native checkpoint nextAction");if(At(d)!==d||At(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:br(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function IO(e,t){let i=Ul(e,"Native checkpoint journal");if(Kl(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=st(i.previousState),n=st(i.nextState),a=mp(i.checkpoint,t),o=Yl(i.manifest,t),s=br(i.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!ya.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==pp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function jO(e,t,i){let r=wa.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=kf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ie({root:e.projectRoot,file:r,maxBytes:kr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function $O(e,t){let i=dp(e,t),r=j(e,i);await T(r,i);try{return mp(await hp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function vp(e,t,i){let r=fp(e,t,i),n=j(e,r);await T(n,r);let a=await hp(n,r,"Native checkpoint manifest"),o=Yl(a,t);if(gp(e,o),pp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Er(e,t){let i=Sr(e,t),r=j(e,i);await T(r,i);try{let n=IO(await hp(r,i,"Native checkpoint journal"),t);return gp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Kb(e,t,i,r){let n=Yl(i,t);gp(e,n);let a=pp(n),o=fp(e,t,a),s=j(e,o);await T(s,o);try{let c=await vp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await te(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function gp(e,t){for(let i of t.artifacts){let r=kf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Yb(e,t){let i=mp(t,t.change),r=await vp(e,i.change,i.manifestHash),n=F(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=dp(e,t.change),o=j(e,a);await T(o,a),await te(a,i,{containedRoot:o})}async function Xb(e){let t;try{t=await $O(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:dp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await vp(e.paths,e.name,t.manifestHash);let a=F(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await jO(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:fp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Qb(e,t,i){let r=await Er(e,t);if(!r)return null;if(await Kb(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Tl(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Yb(e,r.checkpoint),await i?.afterProgressWritten?.(r),await OO.rm(Sr(e,t),{force:!0}),r}async function Zb(e,t,i){return he(e,`continue checkpoint ${t}`,()=>an(e,t,`continue checkpoint ${t}`,async()=>(await Jl(e,t),Qb(e,t,i))))}import{constants as wp,promises as _t}from"node:fs";import Na from"node:path";var HO=/^[a-f0-9]{64}$/u,DO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ss=512*1024;function MO(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function FO(e,t){let i=Na.resolve(e),r=Na.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Na.relative(i,r).split(Na.sep).filter(Boolean)]){o&&(a=Na.join(a,o));let s=await _t.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await _t.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function ek(e){for(let t of e){let i=await _t.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!MO(t,i)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function LO(e){if(!HO.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function BO(e){let t=DO.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function qO(e,t,i){return Qi(H(e,t),LO(i))}async function VO(e,t,i){let r=await FO(i,Na.dirname(e)),n=await _t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>ss)throw new Error(`Native check receipt exceeds ${ss} bytes`);let[a,o]=await Promise.all([_t.realpath(t),_t.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":wp.O_RDONLY|wp.O_NOFOLLOW|wp.O_NONBLOCK,c=await _t.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await ek(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Xl(n,l)||!Xl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=ss+1-p,E=await c.read(v,0,Math.min(v.length,y),null);if(E.bytesRead===0)break;if(p+=E.bytesRead,p>ss)throw new Error(`Native check receipt exceeds ${ss} bytes`);f.push(Buffer.from(v.subarray(0,E.bytesRead)))}let[h,m,N]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await ek(r),!m.isFile()||m.isSymbolicLink()||N!==o||!$(a,N)||!Xl(l,h)||!Xl(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function tk(e,t,i){let r=BO(i),n=H(e,t),a=qO(e,t,r),o=j(e,a);await T(o,a);let s=Dl(await VO(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var cs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var hz=64*1024;var pz=3600*1e3;var mz=UO(GO);var KO=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ik(e,t){let i=[];for(let r of KO){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function rk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await tk(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Pr=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}};function YO(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function XO(e){let t=YO(e.bundle.baseline),i=await mh(e.paths,t,{origin:"explicit",now:e.now});return Fh({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function ak(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ts(e.paths,e.state.name,e.state.implementation_scope),i=await ga({changeDir:re(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await XO({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function ok(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await ak(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function QO(e){let t=await Q({root:re(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Lw(t.text)}}function ZO(e){let{receipt:t,implementationScope:i}=e,r=[],n=Mh({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function e0(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Jh(e.implementationScope.scope.declaredArtifacts)}}async function nk(e){let t=await is(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=ik(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Pr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await rk({paths:e.paths,state:e.state,receipt:t});if(n){let a=ZO({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function t0(e){let t=e0({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await nk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Pr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await nk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Pr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Pr(i)}function yp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ql(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:yp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([ak(e),ma(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:yp(e.state.verification_result,"stale"),envelope:null};let r=await QO({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await t0({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:yp(e.state.verification_result,"invalid"),envelope:null}}}function r0(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function ck(e){try{return await i0.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function n0(e,t){try{return(await Q({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function a0(e,t,i){let r=Il(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=sk.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await n0(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Q({root:re(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function o0(e,t){return ck(ze(e,t))}async function Zl(e){let t=e.now??new Date,i=await $e(e.paths,e.name),r=await wt(e.paths,e.name),n=await Ne(e.paths.projectRoot),a=r0(i.name,t),o=sk.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>a0(e.paths,i.name,v))),Ql({paths:e.paths,state:i,now:t}),Bl(e.paths,i.name),na(e.paths,i.name),aa(e.paths,i.name),o0(e.paths,i.name),ck(o)]);return xN({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Np}from"node:fs";import Ii from"node:path";var s0="comet.native.archive-tree.v1",c0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function dk(e){let t={...c0,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function lk(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function uk(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function fk(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await pt({root:e,directory:t,label:`Native Archive content directory ${Ii.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=lk(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ii.join(t,u.name),f=Ii.relative(e,d).replaceAll("\\","/"),p=await Np.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){uk(i,{ref:f,kind:"directory"},r,n),await fk(e,d,i,r,n,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await ie({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);uk(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await pt({root:e,directory:t,label:`Native Archive content directory ${Ii.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(lk(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ii.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function hk(e,t={}){let i=dk(t);e=Ii.resolve(e);let r=await Np.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await fk(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return F(`${s0}\0${o}`)}async function Qt(e,t={}){let i=dk(t);e=Ii.resolve(e);let r;try{r=await Np.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ie({root:Ii.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ii.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await hk(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Qe}from"node:fs";import Pe from"node:path";var kp=16*1024*1024,l0=256*1024,u0=16*1024,ls="comet.native.archive-cas.v1";function d0(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Pe.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Oe(e,t){let i=d0(e,t);return T(j(e,i),i)}function Rr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function ba(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ut(e){let t=await Qt(e.target);if(!Rr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ba(t)}`);return t}async function Sp(e,t){let i=await si(e,t),r=await ie({root:e.runtimeDir,file:i.journal,maxBytes:l0,label:`Native Archive transaction journal ${t}`}),n=sl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function eu(e,t,i){let r=sl({...t,status:i}),n=await si(e,r.id);return await te(n.journal,r,{containedRoot:e.runtimeDir}),r}function tu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function pk(e){return{...tu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function xr(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function f0(e,t){return xr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ee(e){try{return await Qe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vi(e){let t=await Qe.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=pk(t),r=await ie({root:j(e.paths,e.file),file:e.file,maxBytes:kp,label:e.label}),n=await Qe.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!f0(i,pk(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:tu(n),size:r.size}}function h0(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==ls||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:ls,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function gi(e,t,i,r){let n=await si(e,t.id),a=Pe.join(n.backups,".cas"),o=`.${Pe.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Pe.join(a,`${i.id}.original.json`),postRecord:Pe.join(a,`${i.id}.post.json`),candidate:Pe.join(a,`${i.id}.candidate`),originalQuarantine:Pe.join(Pe.dirname(r),`${o}.original`),rollbackQuarantine:Pe.join(Pe.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Tt(e){if(!await ee(e.file))return null;let t=await ie({root:e.paths.runtimeDir,file:e.file,maxBytes:u0,label:`Archive CAS ${e.operation.id} ${e.role} record`});return h0(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function iu(e){let t=await Tt(e);if(t){if(!xr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await oi({root:e.paths.runtimeDir,directory:Pe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ls,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await te(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Tt(e);if(!r||!xr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Se(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!xr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function p0(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await iu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Se({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function m0(e){if(!await ee(e.quarantine)||await ee(e.target))return;let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Qe.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Qe.lstat(e.quarantine),Qe.lstat(e.target)]);if(!xr(tu(i),tu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Qe.unlink(e.quarantine),await t.verify()}async function wk(e){if(await ee(e.quarantine)){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Qe.rename(e.target,e.quarantine),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await m0(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function on(e){if(!await ee(e.file))return;await Se(e);let t=await Jt({root:j(e.paths,e.file),directory:Pe.dirname(e.file),label:e.label});await t.verify(),await Se(e),await Qe.unlink(e.file),await t.verify()}async function mk(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Oe(e,t.target),n=await Oe(e,t.backup),a=await Qt(n);if(a!==null){if(!Rr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ut({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await sr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:kp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ut({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function yk(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ee(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Se({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await mk(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ee(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await p0({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await mk(e.paths,e.operation,e.hooks),await wk({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function vk(e){let t=await gi(e.paths,e.journal,e.operation,e.target);return await ee(t.candidate)?(await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await oi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await sr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:kp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function v0(e){let t=e.operation.stagedHash,i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ee(e.target))return await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ee(i.candidate)&&await on({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ee(e.target)){let c=await vk(e),l=await vi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await iu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await on({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await vk(e),a=await vi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await oi({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Se({paths:e.paths,file:n,operation:e.operation,record:{schema:ls,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Qe.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await iu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await on({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function g0(e,t,i,r){let n=await Oe(e,i.target),a=await Oe(e,i.staged);if(await ut({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await gi(e,t,i,n);(!await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ee(n))&&await yk({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Qt(n);if(o!==null&&!Rr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${ba(o)}`)}await v0({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ut({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function w0(e,t,i,r){let n=await Oe(e,i.target);await yk({paths:e,journal:t,operation:i,target:n,hooks:r}),await ut({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function y0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(n===null&&Rr(a,t.expectedSourceHash,"directory"))){if(!Rr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ba(n)}, target=${ba(a)}`);await Qe.mkdir(Pe.dirname(r),{recursive:!0}),await Qe.rename(i,r),await ut({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function N0(e,t,i,r){return i.type==="write"?g0(e,t,i,r):i.type==="remove"?w0(e,t,i,r):y0(e,i)}function b0(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function k0(e,t,i,r){let n=await Oe(e,i.target);if(i.type==="write"){let a=await Oe(e,i.staged);await ut({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await gi(e,t,i,n),s=await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Se({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ut({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Tt({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ee(o.originalQuarantine))await Se({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ut({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ut({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await gi(e,t,i,n),o=await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ee(a.originalQuarantine))await Se({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ut({target:await Oe(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ut({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function Nk(e,t,i){let r=t.status==="prepared"?await eu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await lr(e,r.id),a=b0({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await k0(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Rt(e,r.id,"operation-started",l.id),await N0(e,r,l,i),await Rt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Sp(e,r.id),r}async function S0(e){try{return await Se(e),!0}catch{return!1}}async function E0(e){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Qe.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function bp(e){if(e.operation.type!=="write")return;let t=await gi(e.paths,e.journal,e.operation,e.target);if(!await ee(t.candidate))return;let i=await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await on({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ls,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function P0(e,t,i,r){let n=await Oe(e,i.target),a=await gi(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Tt({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ee(a.candidate)&&await ee(n)){let l=await vi({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await vi({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});xr(l.identity,u.identity)&&(c=await iu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ee(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Se({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ee(n)&&!(s!==null&&await S0({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Qt(n);if(Rr(u,o)){await bp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await wk({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ee(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ee(n)){if(!s||!await ee(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await E0({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ee(a.originalQuarantine)&&await on({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ee(a.rollbackQuarantine)&&await on({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await bp({paths:e,journal:t,operation:i,target:n}),await ut({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function R0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(Rr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Rr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ba(n)}, target=${ba(a)}`);await Qe.mkdir(Pe.dirname(i),{recursive:!0}),await Qe.rename(r,i)}}async function bk(e,t,i){let r=await lr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await eu(e,t,"rolling-back");await Rt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await R0(e,o):await P0(e,n,o,i));return await Rt(e,n.id,"rollback-completed"),n=await eu(e,n,"rolled-back"),n}async function gk(e,t,i){let r=await Oe(e,i.target);if(i.type==="write"){let n=await gi(e,t,i,r),a=await Tt({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Se({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ut({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function x0(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Oe(e,i.target),n=await gi(e,t,i,r);if(await ee(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await gk(e,t,i),i.expectedTargetHash!==null){let a=await Tt({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ee(n.originalQuarantine)&&await on({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await bp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await gk(e,t,i)}async function ru(e,t,i){return i==="commit"&&await x0(e,t),await Rt(e,t.id,i),i==="commit"?eu(e,t,"committed"):t}var cJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as C0}from"fs";import A0 from"path";var Ep="comet.selection.v2",_0=16*1024;function nu(e){return A0.join(e,".comet","current-change.json")}function T0(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function kk(e){return e===null||typeof e=="string"}function I0(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(!T0(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&&!kk(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ep,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ep)throw new Error(`current change selection schema must be ${Ep}`);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(!kk(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 Pp(e){let t;try{let r=nu(e),{bytes:n}=await qr(r,_0,{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",...I0(t)}}async function Sk(e){await C0.rm(nu(e),{force:!0})}async function Ek(e,t,i){let r=await Pp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await Sk(e),!0)}import{promises as fs}from"node:fs";import _r from"node:path";var _p=hn(Lr(),1);import{promises as _k}from"node:fs";import It from"node:path";import{execFileSync as j0}from"node:child_process";var $0=3e4,O0=8*1024*1024,Rp=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 H0(e,t){try{return j0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$0,maxBuffer:O0,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Rp(e,t,r)}}function xp(e,t){return H0(e,t).trim()}var Pk="children.yaml",Cp="comet.native.children.v1",D0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,M0=new Set(["schema","children"]),F0=new Set(["name","depends_on","covers"]);function Rk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xk(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 Ck(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 Ap(e,t){let i=It.normalize(It.resolve(e)),r=It.normalize(It.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function L0(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 B0(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function q0(e,t){let i=(0,_p.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Rk(i.toJS({mapAsMap:!1}),"Native children contract");if(xk(r,M0,"Native children contract"),r.schema!==Cp)throw new Error(`Native children schema must be ${Cp}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Rk(s,`Native child ${c}`);if(xk(l,F0,`Native child ${c}`),typeof l.name!="string"||!D0.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:Ck(l.depends_on,`Native child ${l.name} depends_on`),covers:Ck(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return L0(n),t&&B0(n,t),{schema:Cp,children:n}}async function Tp(e){let t=It.join(e.changeDir,Pk);try{await _k.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await Q({root:e.changeDir,ref:Pk});return{contract:q0(i.text,e.acceptanceIds),size:i.size}}function Ip(e){return M("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function V0(e){let t=Rn(e.projectRoot);t.some(r=>Ap(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>It.resolve(n)))]){let n=await Ne(r);n&&i.push({projectRoot:r,paths:await Be(r,n.native.artifact_root),parent:Ap(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function W0(e,t){let i=It.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ue(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function z0(e,t){let i;try{i=await _k.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=It.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ue(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function J0(e,t,i){let r=It.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${It.sep}`))return null;let n=r.split(It.sep).join("/");try{let a=(0,_p.parseDocument)(xp(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:nt(a.toJS({mapAsMap:!1}))}catch{return null}}function G0(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Ak(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function us(e){let t=It.join(e.paths.changesDir,e.state.name),i=await Tp({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=Ip({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await V0(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:h})=>h)),c=new Map,l=new Map;for(let h of a){let m=h.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await z0(h,s)){let y={...N,source:h,committedState:J0(h,N.file,m)};c.set(N.state.name,[...c.get(N.state.name)??[],y])}for(let N of s){let y=await W0(h,N);y&&l.set(N,[...l.get(N)??[],{source:h,state:y}])}}let u=new Map;for(let h of i.contract.children){let m=(c.get(h.name)??[]).find(({source:E,committedState:S})=>E.parent&&S?.name===h.name&&Ak(S,o));if(m){u.set(h.name,{kind:"done",phase:m.state.phase,projectRoot:m.source.projectRoot,message:null});continue}let N=c.get(h.name)?.[0];if(N){u.set(h.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=l.get(h.name)??[];y.length>1?u.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&u.set(h.name,G0(y[0].state,y[0].source,o))}let d=new Map(i.contract.children.map(h=>[h.name,h])),f=new Map,p=h=>{let m=f.get(h);if(m)return m;let N=d.get(h),E=N.depends_on.map(p).every(({status:g})=>g==="done"),S=u.get(h),k=S?.kind==="active"&&E?N.depends_on.filter(g=>!(c.get(g)??[]).some(({source:P,committedState:D})=>Ap(P.projectRoot,S.projectRoot)&&D?.name===g&&Ak(D,o))):[],b,R=S?.message??null;S?.kind==="done"?(b=E?"done":"blocked",E||(R=`Native child ${h} was merged before its dependencies`)):S?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(R=`Native child ${h} does not include merged dependencies: ${k.join(", ")}`):R=`Native child ${h} started before its dependencies merged`):S?.kind==="blocked"?b="blocked":(b=n&&E?"ready":"pending",n||(R="Parent Shape confirmation is required"));let w={name:h,dependsOn:[...N.depends_on],covers:[...N.covers],status:b,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:R};return f.set(h,w),w},v=i.contract.children.map(({name:h})=>p(h));return{contractHash:r,confirmed:n,parentBranch:o,children:v,readyChildren:v.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:v.every(({status:h})=>h==="done")}}var au="skill-coordinated";function K0(e){return e.state_version+1}function Y0(e){return e.map(t=>({...t,result:"pending",reason:null}))}function X0(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:ir(e.summary),completed_at:e.completedAt}}function jp(e){let t=nt(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=Ln(t,X0({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return nt({...r,phase:"build",status:"active",state_version:K0(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:Y0(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 Ik}from"node:fs";import ds from"node:path";function ou(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function su(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 wi(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 Tk(e,t){return e===null?null:wi(e,t)}function lu(e,t,i=0){if(!Number.isSafeInteger(e)||ewi(l,`${i}.argv[${u}]`,!0)),a=cu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=$p(r.startedAt,`${i}.startedAt`),s=$p(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=lu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:wi(r.id,`${i}.id`),name:wi(r.name,`${i}.name`),operationId:wi(r.operationId,`${i}.operationId`),status:a,repeatable:Z0(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:lu(r.executionCount,`${i}.executionCount`),argv:n,cwd:Op(r.cwd,`${i}.cwd`),exitCode:Q0(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:wi(r.log,`${i}.log`)}}function Hp(e){let t="Native local execution state",i=ou(e,t);if(su(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Po)throw new Error(`Native local execution schema must be ${Po}`);let r=ou(i.workspace,"Native local workspace");su(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=ou(i.execution,"Native local execution");su(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=$p(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:wi(o.operationId,"Native local execution.operationId"),stage:cu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:cu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Tk(o.executionId,"Native local execution.executionId"),status:cu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:lu(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(eH);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:Po,change:wi(i.change,"Native local change"),basedOnStateVersion:lu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Op(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Op(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Tk(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function sn(e){return Hp({schema:Po,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:ds.resolve(e.projectRoot),worktreeRoot:ds.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function uu(e){let t;try{t=await Ik.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 Hp(i)}async function Cr(e,t,i={}){let r=Hp(t);await Ik.mkdir(ds.dirname(e),{recursive:!0}),await te(e,r,i)}import{promises as tH}from"node:fs";function Ar(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function ji(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"
")}function iH(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 rH(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===au?au:"host-attested")}function nH(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${ji(o.id)} | ${ji(o.result)} | ${ji(o.source)} | ${ji(o.text)} | ${ji(Ar(o.reason))} |`).join(` `),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(Ar).join(" ");return`| ${ji(Ar(o.name))} | ${ji(s||"—")} | ${ji(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(` `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${Ar(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(` @@ -244,20 +244,20 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ `:""}## Conclusion ${Ar(e.verification.summary)} -`}function aH(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 du(e){let t;try{t=await tH.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=aH(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function fu(e){await ue(e.file,nH(e.state))}var Ik=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oH="comet-state.yaml",sH="state.json";function jt(e,t){if(!Ik.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=_r.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function bt(e,t){return _r.join(jt(e,t),oH)}function cn(e,t){return _r.join(rt(e,t),sH)}async function Tr(e,t){try{let i=await fs.readFile(bt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function cH(e){return Ae(e).currentBranch}async function ka(e,t){return Ue(bt(e,t))}async function lH(e){let t=await zr({file:bt(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=_r.join(jt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await fs.rm(i,{force:!0})}return t}async function uH(e){let t=jt(e.paths,e.state.name),i=_r.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await fs.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(!Ik.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=_r.join(t,...s.split("/")),l=await fs.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=_r.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await fs.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function dH(e){let t=jt(e.paths,e.state.name),i=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Jc({briefMarkdown:i.text,specs:r})}async function jk(e){let t=await uH(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 dH({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Vw(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Tp({changeDir:jt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Ip({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 $k(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Ln(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ir(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 lH({paths:e.paths,previous:t,next:r});return await Cr(cn(e.paths,t.name),sn({portableState:n,projectRoot:e.paths.projectRoot,branch:cH(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function hu(e){if(e.state.verification===null)return"not-applicable";let t=_r.join(jt(e.paths,e.state.name),"verification.md");return await du({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await fu({file:t,state:e.state}),"rebuilt")}async function Ok(e){let t=await ka(e.paths,e.name),i=cn(e.paths,e.name);try{let r=await uu(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var qG=16*1024;async function pu(e){let t=await Pp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(xl(t.selection.change),t.selection)}function Hk(e){return nu(e.projectRoot)}async function hs(e,t){return await $n(e.projectRoot),Sk(e.projectRoot,"native",t)}var gU=16*1024*1024,mu=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"},ps=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"};function Mk(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Sa.resolve(e.nativeRoot,...i.target.split("/"))}async function Fk(e,t,i){let r=await lr(e,t.id);if(r.some(m=>m.type==="archive-finalized"))return;let n=r.some(m=>m.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let m=t.operations.find(y=>y.id==="archive-change");if(!m||m.type!=="move"||!m.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let N=await Qt(Mk(e,t));if(N?.kind!=="directory"||N.hash!==m.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Mk(e,t),o=Sa.join(a,Re),s=await wN(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await Ie(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let m=dm(pi,l,new Set,ep,void 0);if(!m.action)throw new Error(m.reason??"Native archive produced no action");u=fm(pi,m.state,{actionId:m.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},ep,void 0)}let d=F(`archive:${t.id}:${s.name}`),f=await Xe(c,u.trajectoryRef),p=f.filter(m=>m.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(m=>m.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=p.find(m=>m.type==="state_transitioned"),h={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!fH(v.data,h)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||p.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await ru(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await zn(e,t,"archive-finalization-started")),!s.archived){let m={...s,archived:!0};await gN(o,m)}v||(v=await Nr({changeDir:c,run:u,type:"state_transitioned",data:h,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await nn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Xr(c,u),await hs(e,s.name),t.schema==="comet.native.transaction.v2"?await ru(e,t,"archive-finalized"):await zn(e,t,"archive-finalized")}async function Dp(e,t){let i=rt(e,t);try{let r=await Dk.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await Dk.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function hH(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await lr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Zl({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new ps(c,"Native Archive facts changed before the first transaction operation")}let o=await yk(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await $e(e,t.change),u=await Ql({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await Fk(e,o,i);let s=await ru(e,o,"commit");return{journal:s,runtimeCleanupWarning:await Dp(e,s.change)}}let r=await hy(e,t);await Fk(e,r,i);let n=await zn(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await Dp(e,n.change):null}}function pH(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Sa.resolve(t.projectRoot)!==Sa.resolve(e.projectRoot)||Sa.resolve(t.nativeRoot)!==Sa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Lk(e){return he(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await er(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await mt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Sp(e.paths,e.transactionId):i;return pH(e.paths,r),r.status==="committed"?(r.change&&await Dp(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await hH(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?Nk(e.paths,r):ll(e.paths,r)}finally{await tr(t)}},{allowedTransactionId:e.transactionId})}import{promises as AH}from"fs";async function Bk(e,t){let i=[],r=H(e,t.name),n=Qi(r,vt.stateRef),a;try{a=await Ie(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Qi(r,a.trajectoryRef),s=await Zn(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Xe(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Qi(r,a.checkpointRef);try{let u=await Qn(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var mH=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function vH(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function gH(e){return e?e.map(vH).join(" "):null}function wH(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function $t(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function yH(e){return e.map(t=>$t(t,[],null))}function NH(e){let t=["comet","native","next",e.name,"--summary",""],i=[$t("summary",["--summary"],"")];if(e.phase==="shape")return t.push("--confirmed"),i.push($t("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact",""),i.push($t("artifact-or-no-code-reason",["--artifact"],"",{repeatable:!0,alternativeGroup:"build-evidence"}),$t("artifact-or-no-code-reason",["--no-code-reason"],"",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push($t("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","","--report",""),i.push($t("verification-result",["--result"],"",{choices:["pass","fail"]}),$t("verification-report",["--report"],"")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Je(e,t){let i=t.commandArgs===void 0?wH(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?gH(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??yH(t.requiredInputs??[])}}function vu(e){let i=(e.findings??[]).filter(d=>!ea(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||mH.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Je(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Je(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[$t("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Je(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Je(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Je(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary",""],requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"")]});if(n)return Je(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary",""];return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Je(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Je(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[$t("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Je(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Je(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=NH(e.state);return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import ms from"path";var qk=8,bH={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function kH(e){let t=bH[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ea(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function SH(e,t,i){if(!i.path)return null;let r;if(ms.isAbsolute(i.path)?r=ms.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=ms.resolve(re(e,t.name),...i.path.split(/[\\/]/u)):r=ms.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=ms.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function EH(e,t,i){return e==="next"?`comet native next ${t.name} --summary ""${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Mp(e){return e.findings.map(t=>{let i=kH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:SH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:EH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Fp(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,qk),truncated:t.length>qk}}var Vk=240,Wk=8,gu=50;function zk(e){let t=Array.from(e);return t.length<=Vk?e:`${t.slice(0,Vk-1).join("")}…`}function PH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function RH(e){let t=[...new Set(e.map(PH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Wk),reasonCount:e.length,codesTruncated:t.length>Wk};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,gu),reasonsTruncated:e.length>gu}}}async function Jk(e){let t=null;try{let s=await Er(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Sr(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Sr(e.paths,e.state.name)}}let i=await Yb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=RH(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:kr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:zk(i.checkpoint.summary),nextAction:zk(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:kr.maxArtifacts}}async function xH(e,t){let i=H(e,t.name),r=await Ie(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Qn(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Xe(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function CH(e,t){let i=await xH(e,t);return{committed:i,latest:Rb(i),history:Pb(i)}}async function Gk(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await CH(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var _H=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ea=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Lp(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function TH(e){return(await pu(e))?.change??null}function IH(e,t,i=!1,r){return vu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function jH(e,t){let i=re(e,t.name),r=[...(await xh(i,t.brief)).findings,...(await SN(e,t)).findings,...await Bk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Xn(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await vl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await ga({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ti(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Ch(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Bp(e,t,i){let r=await TH(e)===t,n=await No(e,t),a=await aN(e,t),o;try{let g=await ui(e,t);if(g.status==="migration-required"&&g.state)return{name:t,phase:g.state.phase,revision:"revision"in g.state?g.state.revision:null,approval:g.state.approval,verificationResult:g.state.verification_result,specChanges:g.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,migrationRequired:!0,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message};if(g.status!=="current"||!g.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${t} is incompatible`};o=g.state}catch(g){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:g.message}}if(n.status!=="available"){let g={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Mp({paths:e,state:o,findings:[g]}),D=vu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:D.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Fp(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:D,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await Jk({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Gk(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let g=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:g,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let g=await ga({changeDir:re(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let De=await ma(e,o.name,o.verification_evidence);for(let ce of De.acceptanceTrace.entries)P.set(ce.acceptanceId,ce.status==="failed"?"failed":ce.status==="missing"?"missing":"satisfied")}let D=Dw({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),O=D.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",D.nextCursor,"--project-root",e.projectRoot]:null;u={...D,...O?{nextPageCommand:Lp(O),nextPageArgs:O}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Bl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await wt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let P=await ia({paths:e,identity:g});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Fo({paths:e,identity:g});f.push(...P.findingCodes.map(D=>({code:D,message:`Native workspace advisory changed: ${D} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let g=await ak({paths:e,state:o});v=g.freshness!=="fresh",p.push(...g.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Zl({paths:e,name:o.name}),m.push(...h.findingCodes.map(g=>({code:g,message:`Native Archive is blocked: ${g}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let N=[...await jH(e,o),...s.findings,...d,...f,...p,...l,...m].filter((g,P,D)=>D.findIndex(O=>O.code===g.code&&O.path===g.path)===P),y=Mp({paths:e,state:o,findings:N}),E=y.filter(g=>!ea(g.code)),S=o.phase==="archive"&&h?.ready===!0&&E.length===0,k=v||o.phase==="archive"&&(h?.findingCodes??[]).some(g=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(g)),b=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",w=y.find(g=>g.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||R?null:IH(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:Fp(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:vu({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:gu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...w?{error:w.message}:{}}}async function $H(e){let t;try{t=await Jt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await AH.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ea.maxChanges))throw new Error(`Native status exceeds ${Ea.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function wu(e,t){let i=t.toString(36),r=M("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function OH(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=_H.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=M("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function HH(e,t){let i=await $H(e),r=M("comet.native.status-names.v1",i),n=OH({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ea.maxItems).map(u=>Bp(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,p={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:fEa.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Kk(e){return JSON.stringify(e,null,2)+` -`}function Jp(e){return e.schema===we?Cl(e):Qr(e)}function Vp(e,t){return{...e,schema:we,minimum_runtime_version:2,revision:t}}function qH(e){return{...e,schema:Si,minimum_runtime_version:2,revision:1,previousState:Vp(e.previousState,1),nextState:Vp(e.nextState,2)}}function Nu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:ge,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function VH(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?F(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:rr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Nu(e.previousState),nextState:{...Nu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:pi.definition.metadata.version,skillHash:ns}:e.nextRun}}function Yk(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Pa(e,t){return JSON.stringify(Cl(e))===JSON.stringify(Cl(t))}function Xk(e,t){return JSON.stringify(Qr(e))===JSON.stringify(Qr(t))}function $i(e,t){return zp(e,t)}function WH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(yu(n,LH,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!ln.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!ln.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=hr(n.previousRun),o=hr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!$i(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==Uk.size||u.some(f=>!Uk.has(f))||l.fromSchema!==we||l.toSchema!==ge||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function vs(e,t){return Wp.join(H(e,t),"schema-migration.json")}function zH(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");yu(e,MH,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===Ke&&i.toSchema===we,n=i.fromSchema===we&&i.toSchema===ge;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!ln.test(i.sourceHash)||typeof i.targetHash!="string"||!ln.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?ai(i.nextState):st(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(F((0,bu.stringify)(Jp(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");yu(i.transition,FH,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!ln.test(l.sourceHash)||typeof l.targetHash!="string"||!ln.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?cp(l.nextJournal,t):sp(l.nextJournal,t);if(F(JSON.stringify(l.nextJournal,null,2)+` -`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===we?Pa(a,u.previousState)||Pa(a,u.nextState):a.schema===ge&&(Xk(a,u.previousState)||Xk(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==ge)throw new Error("Schema migration transition supersede target schema is invalid");s=WH(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");yu(i.runRetreat,BH,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=hr(l.previousRun),d=hr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!ln.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==ge||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function gs(e,t){let i=vs(e,t),r=j(e,i);await T(r,i);try{let n=await il({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return zH(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function JH(e,t,i){let r=await Xn(e,t),n=r?await vl(e,r):await gl(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=hh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ra(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await vh(e,t,n)}async function Zk(e){try{return await Gt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function GH(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function eS(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await Xe(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!zp(o.event,GH(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function UH(e,t,i){if(!t.transitionSupersede)return;let r=ze(e,t.change),n=await Zk(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await Ie(a),s=await eS(e,t),c=await Qn(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!$i(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==F(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function KH(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await Ie(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!$i(a,r.nextRun)){if(!$i(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Xr(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!$i(await Ie(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await eS(e,t);if(o.sequence===null){let l=await Nr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await nn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=ze(e,t.change),c=await Zk(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await Qk.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function YH(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await Ie(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!$i(n,t.runRetreat.nextRun)){if(!$i(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Xr(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await Xe(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Nr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await nn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function XH(e,t,i){let r=await gs(e,t);if(!r)return null;if(await aa(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Wp.join(re(e,t),Re),a=await Gt(n);if(await UH(e,r,a===r.targetHash),await JH(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await ue(n,(0,bu.stringify)(Jp(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=ze(e,t),s=await Gt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await te(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await KH(e,r,i),await YH(e,r,i),await Qk.rm(vs(e,t),{force:!0}),r.nextState}async function QH(e){let t=H(e.paths,e.state.name),i=await Ie(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:we,toSchema:ge,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function ZH(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Pa(i,t.previousState),a=Pa(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await Ie(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&$i(s,t.previousRun),l=$i(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await Xe(o,t.nextRun.trajectoryRef)).map((N,y)=>({event:N,index:y})).filter(({event:N})=>N.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let N={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!zp(f.event,N)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Nu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,m=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await Gt(ze(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:h,evidenceHash:m,eventData:{fromSchema:we,toSchema:ge,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function eD(e){let t,i,r,n;if(e.state.schema===Ke){if(t=Vp(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Jr)throw new Error("Native v1 change has a transition from another schema generation");let s=qH(e.pendingTransition.journal);if(Yk(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(Yk(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=ze(e.paths,e.name);i={sourceHash:await Gt(c),targetHash:F(Kk(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Si)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await ZH({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=VH(s);if(Pa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Pa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=ze(e.paths,e.name);i={sourceHash:await Gt(u),targetHash:F(Kk(l)),nextJournal:l}}}else t=Nu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await QH({paths:e.paths,state:e.state,migrationId:e.id}));let a=Wp.join(re(e.paths,e.name),Re),o=(0,bu.stringify)(Jp(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Ke?we:ge,sourceHash:await Gt(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function tS(e){return he(e.paths,`migrate schema for ${e.name}`,()=>an(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await XH(e.paths,e.name,e.hooks);if(i?.schema===ge)return i;let r=await ui(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await aa(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==Ke&&n.schema!==we)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await lp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await eD({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??DH()}),s=vs(e.paths,e.name),c=j(e.paths,s);await T(c,s),await te(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Oi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),rD=512*1024,un=/^([a-f0-9]{64})\.json$/u,nD=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,aD=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,ku=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Kp(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yi(e,t){return Kp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function oS(e,t){return Kp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ra(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ze(e,t){return et?1:0}function oD(e,t){let i=se.relative(e.projectRoot,t);if(i.length===0||se.isAbsolute(i)||i===".."||i.startsWith(`..${se.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(se.sep).join("/")}function sS(e,t){return se.join(H(e,t),"evidence")}function Su(e,t){return oD(e,sS(e,t))}async function Eu(e,t){let i=se.resolve(e),r=se.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=se.relative(i,r).split(se.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=se.join(o,s));let c=await X.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await X.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ra(c)})}return a}async function Ot(e){for(let t of e){let i=await X.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kp(t,i)||await X.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function cS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:pa(e,t)}function iS(e){return e!==null&&aD.test(e)?[e]:[]}function sD(e,t,i,r){if(e==="snapshots")return{canonical:ca(i,t),dependencies:[]};if(e==="scopes"){let a=la(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Hl(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[pa("scopes",a.scopeHash)]}}if(e==="verifications"){let a=Zo(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(iS));return{canonical:a,dependencies:[a.implementationScopeRef,mb(a.reportHash),...iS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||tD("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Ml(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=Dl(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Ir(e){let t=await X.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?rD:yr;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await X.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Gp.O_RDONLY|Gp.O_NOFOLLOW|Gp.O_NONBLOCK,a=await X.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!yi(Ra(t),o)||!yi(Ra(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,E=await a.read(u,0,Math.min(u.length,y),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,p,v]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!p.isFile()||p.isSymbolicLink()||v!==r||!yi(Ra(o),f)||!yi(Ra(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),m;try{m=JSON.parse(h)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let N=sD(e.kind,e.hash,m,e.name);if(h!==JSON.stringify(N.canonical,null,2)+` -`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ra(f),directoryChain:e.directoryChain,dependencies:[...new Set(N.dependencies)].sort(Ze)}}finally{await a.close()}}async function rS(e){try{return await X.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function cD(e){let t=H(e.paths,e.name),i=t,r=sS(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Eu(t,r);n=await X.readdir(r,{withFileTypes:!0}),await Ot(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of ku){if(!n.some(f=>f.name===s))continue;let c=se.join(r,s),l=await Eu(t,c),u=(await X.readdir(c,{withFileTypes:!0})).sort((f,p)=>Ze(f.name,p.name)),d=new Map;for(let f of u){let p=nD.exec(f.name);if(!p)continue;let v=d.get(p[1])??[];v.push(f),d.set(p[1],v)}for(let[f,p]of[...d.entries()].sort(([v],[h])=>Ze(v,h))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=p[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let h=se.join(c,f),m=un.exec(f)?.[1];if(!m)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let N=cS(s,m),y=se.join(c,v.name),E=await Ir({changeRoot:i,file:y,ref:N,kind:s,hash:m,name:e.name,directoryChain:l}),S=await rS(h),k=S?null:await Ir({changeRoot:i,file:h,ref:N,kind:s,hash:m,name:e.name,directoryChain:l});a.push({ref:N,original:h,quarantine:y,document:E,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Ze);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:xa(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Pu(o)}`),path:Su(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Ze(c.ref,l.ref))){if(await Ot(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Ir({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Ir({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!yi(s.originalDocument.identity,d.identity)||!yi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain);continue}if(!await rS(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await X.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!yi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await X.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Ir({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Ir({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!oS(s.document.identity,l.identity)||!yi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:xa(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Pu(o)}`),path:Su(e.paths,e.name)}]}}async function lD(e,t){let i=H(e,t),r=i,n=se.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Eu(i,n);a=await X.readdir(n,{withFileTypes:!0}),await Ot(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!ku.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Ze);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Pu(o)}`);let s=[],c=0;for(let l of ku){if(!a.some(p=>p.name===l))continue;let u=se.join(n,l),d=await Eu(r,u),f=(await X.readdir(u,{withFileTypes:!0})).sort((p,v)=>Ze(p.name,v.name));await Ot(d);for(let p of f){if(s.length>=Oi.maxDocuments)throw new Error(`Native evidence store exceeds ${Oi.maxDocuments} documents`);let v=un.exec(p.name);if(!v||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let h=cS(l,v[1]),m=se.join(u,p.name);await T(j(e,m),m);let N=await Ir({changeRoot:r,file:m,ref:h,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=N.size,c>Oi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Oi.maxScannedBytes} scanned bytes`);s.push(N)}await Ot(d)}return s}function nS(e,t){let i=new Set,r=[...e].sort(Ze).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Ze).reverse())i.has(o)||r.push(o)}return i}function uD(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ze),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Ze))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function dD(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=nS(t,r),a=new Set(n);for(let c of e)i-c.mtimeMsu.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ze(u.ref,d.ref)).slice(0,Oi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=nS(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Oi.minimumAgeMs).sort((c,l)=>Ze(c.ref,l.ref));return{candidates:uD(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Pu(e){let t=e.slice(0,Oi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function xa(e){let t=Oi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Up(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Ze);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:xa(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Pu(n)}`),path:r}}async function aS(e,t){try{await X.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await X.rename(e,t)}catch{}}async function fD(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ot(e.directoryChain);let i=await Ir({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:un.exec(se.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await X.lstat(e.file),n=await X.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!yi(e.identity,r)||!yi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=se.join(se.dirname(e.file),`.${se.basename(e.file)}.${iD()}.gc`);await X.rename(e.file,a);try{let[o,s]=await Promise.all([X.lstat(a),X.realpath(a)]);if(await Ot(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!oS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await aS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await X.rm(a),await Ot(e.directoryChain)}catch(o){throw await aS(a,e.file),o}}async function hD(e){if((await Ne(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await X.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await mt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function pD(e,t){if(t)return[t];let i;try{i=await X.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Ze)}async function mD(e,t){let i=await ui(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Ti(e,t),gs(e,t),Er(e,t)]);return r!==null||n!==null||a!==null}async function vD(e){if(await mD(e.paths,e.name))return[];let t=await ui(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await cD({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await lD(e.paths,e.name),a=dD(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Su(e.paths,e.name);if(!e.repair)return[...i.findings,Up(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await fD(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Up(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:xa(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Up(e.name,a,!0,o)]}async function lS(e){if(e.deferAll||await hD(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await pD(e.paths,e.name))try{a.push(...await vD({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:xa(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Su(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await he(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:xa(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as gD,randomUUID as YK}from"crypto";import{promises as Ns}from"fs";import ne from"path";var Xp=64*1024*1024,wD=256*1024,hS=16*1024*1024;async function et(e){try{return await Ns.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function yD(e){let t;try{t=await Ns.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await wt(e,i.name);if(r){await Pl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function ys(e,t){let i=[];async function r(n){let a=await pt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(n,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await Ns.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ie({root:e,file:c,maxBytes:Xp,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function ND(e,t,i,r){await oi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await pt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await Ns.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await oi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await sr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Xp,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Ca(e,t,i,r){let n=await ys(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await ys(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ne.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function bD(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function kD(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function SD(e){return`${e}.removing`}function uS(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function pS(e,t,i){return ne.join(cl(e,t).directory,`root-move-cleanup-${i}.json`)}function ED(e){return JSON.stringify(e,null,2)+` -`}function PD(e){return gD("sha256").update(e).digest("hex")}function RD(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function xD(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(RD);for(let a=0;a0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function CD(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=ED(t);if(Buffer.byteLength(i,"utf8")>hS)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await ue(pS(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),PD(i)}async function AD(e){let t=await ie({root:e.paths.runtimeDir,file:pS(e.paths,e.id,e.cleanup.kind),maxBytes:hS,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return xD(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Yp(e){let t=await ys(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function dS(e){return e.ref.split("/").length}async function _D(e){let i=[...await Yp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>dS(a)-dS(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ne.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await rl({root:e.projectRoot,file:a,maxBytes:Xp,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Xf({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Yp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Xf({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function mS(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function TD(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function ID(e,t,i,r){for(let a of[e,t])try{let o=await mt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ne.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ie({root:i,file:n,maxBytes:wD,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function fS(e){let t=mS(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Zi(e.projectRoot,t),t}async function ws(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=mS(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Zi(e.projectRoot,i),i}async function Ru(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await et(e.target),a=await et(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await CD({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await ys(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await AD({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await et(e.target),a=await et(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await ty({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return ws({projectRoot:e.projectRoot,config:t,id:e.id})}return await Yp({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await _D({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),ws({projectRoot:e.projectRoot,config:t,id:e.id})}async function jD(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await et(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=SD(e.staging);t=await Ru({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await ys(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await ND(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ca(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await fS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await et(e.destinationPaths.nativeRoot)){if(await et(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ca(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await et(e.staging))throw new Error("Native move staging tree is missing");await Ca(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ns.rename(e.staging,e.destinationPaths.nativeRoot)}t=await fS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await et(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=kD(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await et(e.sourcePaths.nativeRoot)&&await Ca(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Ru({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await yD(e.destinationPaths);let n=await mt(e.destinationPaths,e.pending.id);await zn(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Zi(e.projectRoot,o),o}async function vS(e){let t=await Ne(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await Be(e.projectRoot,i.fromArtifactRoot),n=await Be(e.projectRoot,i.toArtifactRoot),a=bD(n,i.id),o=await et(r.nativeRoot)?r:n,s=await er(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await ID(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await et(r.nativeRoot))throw v;let h=TD({id:i.id,paths:r,now:new Date});await dy(r,h),c={journal:h,paths:r}}if(e.strategy==="continue"){let v=await jD({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await et(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=uS(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await et(n.nativeRoot)&&await Ca(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Ru({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=uS(a,i.id);!t.native.pending_root_move?.cleanup&&await et(a)&&await Ca(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Ru({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await mt(r,i.id);await ll(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Zi(e.projectRoot,p),{activeNativeRoot:r.nativeRoot,config:p}}finally{await tr(s)}}var Aa=4096,$D=4096,OD=1024;async function jr(e,t,i){try{let r=await pt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Cu(e,t){let i=new Map(e.map(r=>[xe.resolve(r.file),{...r,file:xe.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await bo(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Ff(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function HD(e,t){let i=Hk(e),r;try{await T(e.projectRoot,i);let n=await pu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await Tr(e,r.change)?[]:(await $e(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await xu.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function DD(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function MD(e,t){let i=[],r=[];for(let n of await jr(e,e.transactionsDir,$D)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await mt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:xe.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await On([e],`doctor archive recovery ${a.id}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,"archive.lock")}],i)?(await Lk({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function FD(e,t,i){let r=[];for(let n of await jr(e,e.locksDir,OD)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=xe.join(e.locksDir,n.name);try{let o=await bo(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await Ff(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function LD(e,t,i=5){let r=[],n=t?await qp(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await qp(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:xe.join(e.changesDir,a.name,Re)});continue}let o=await Bp(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:xe.join(e.projectRoot,s.path)}:{}})}return r}async function BD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await Zn(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Yy(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:xe.join(H(e,n),"trajectory.jsonl")})}return i}async function qD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await No(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=Vr(e,n),s=rt(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await On([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Jt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await xu.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Jt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await xu.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await xu.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function VD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await kh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:ta(e,n),repair:"migrate"});continue}let a=await $e(e,n);await sN({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:ta(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:ta(e,n)})}return i}async function WD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=vs(e,n);try{let o=await gs(e,n),s=await ui(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:xe.join(e.changesDir,n,Re)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:xe.join(e.changesDir,n,Re),repair:"migrate"});continue}await tS({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:xe.join(e.changesDir,n,Re)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function zD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Ti(e,n)}catch(o){if(o instanceof as)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:ze(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await On([e],`doctor transition recovery ${n}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Lb(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:ze(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:ze(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:ze(e,n),repair:"continue"})}}return i}async function JD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Sr(e,n),o;try{o=await Er(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await On([e],`doctor checkpoint recovery ${n}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Qb(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function bs(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Ne(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([Be(r.projectRoot,c.fromArtifactRoot),Be(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Cu([{paths:l,file:xe.join(l.locksDir,"root-move.lock")},{paths:u,file:xe.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await vS({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await Be(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await DD(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await MD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await qD(r,{name:e.name,repair:t})),i.push(...await WD(r,{name:e.name,repair:t})),i.push(...await VD(r,{name:e.name,repair:t})),i.push(...await BD(r,{name:e.name,repair:t})),i.push(...await zD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await JD(r,{name:e.name,repair:t})),i.push(...await lS({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await FD(r,t,s.unfinished)),i.push(...await HD(r,t)),e.projectOnly||i.push(...await LD(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as GD}from"node:crypto";import{promises as He}from"node:fs";import dt from"node:path";var Qp=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 gS(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function wS(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=dt.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function Au(e){try{return await He.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function yS(e,t){let i=dt.normalize(dt.resolve(e)),r=dt.normalize(dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function UD(e,t){let i;try{i=await He.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=dt.join(e.archiveDir,n.name);try{let o=await Ue(dt.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 KD(e,t){let i=await el(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function dn(e,t){await He.mkdir(e.transactionsDir,{recursive:!0}),await te(nr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function YD(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Rn(e.paths.projectRoot);i.some(a=>yS(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Ne(a);if(!o)continue;let s=await Be(a,o.native.artifact_root);r.some(c=>yS(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 He.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 Ue(dt.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 _l(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 XD(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 QD(e){let t=dt.join(e.paths.specsDir,e.change.capability),i=dt.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await He.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 He.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([He.realpath(e.paths.specsDir),He.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await He.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await He.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await He.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=dt.join(jt(e.paths,e.state.name),e.change.source);await ue(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await He.mkdir(t,{recursive:!0}),await ue(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function NS(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 ZD(e,t){let i=jt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Q({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function eM(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(NS(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Zp(e){return he(e.paths,`archive portable change ${e.name}`,async()=>{let t=XD(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await KD(e.paths,e.name),r=jt(e.paths,e.name),n=await Au(r),a=n?null:await UD(e.paths,e.name),o;if(n)o=await ka(e.paths,e.name);else if(i)o=await Ue(dt.join(wS(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 jk({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await $k({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=wS(e.paths,i?.archive_ref??gS(o)),c=await Au(s);if(i&&eM(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 hs(e.paths,o.name),await He.rm(rt(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)NS(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await YD({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new Qp(l);i={schema:Zc,id:GD(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:gS(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await ZD(e.paths,o),created_at:new Date().toISOString()},await dn(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await dn(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({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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 tM}from"node:crypto";import{promises as _a}from"node:fs";import xS from"node:path";var CS=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function iM(e){try{return await _a.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function em(e,t){let i=re(e,t),r=[nr(e,{kind:"migration",change:t}),Vr(e,t),...CS.map(n=>xS.join(i,n))];return(await Promise.all(r.map(iM))).some(Boolean)}async function rM(e,t){let i=await el(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function bS(e,t){await _a.mkdir(e.transactionsDir,{recursive:!0}),await te(nr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function kS(e,t){await Promise.all([_a.rm(rt(e,t),{recursive:!0,force:!0}),_a.rm(Vr(e,t),{recursive:!0,force:!0}),...CS.map(i=>_a.rm(xS.join(re(e,t),i),{force:!0}))])}async function SS(e,t){await Cr(cn(e,t.name),sn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ES(e,t){try{let i=await wt(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 PS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=Ae(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 nM(e){let t=re(e.paths,e.state.name),i=await Q({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 Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Jc({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function RS(e,t){let i=await _l(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function ks(e){return he(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await rM(e.paths,e.name),i=await Tr(e.paths,e.name)?await Ue(bt(e.paths,e.name)):null;if(!t&&i)return await kS(e.paths,e.name),await SS(e.paths,i),i;let r=null,n=null;for(t||(r=await RS(e.paths,e.name),n=await ES(e.paths,e.name),PS(e.paths,n),t={schema:Qc,id:tM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await bS(e.paths,t));;){let a=Jw(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await RS(e.paths,e.name),n??=await ES(e.paths,e.name),PS(e.paths,n),i=zw({state:r,acceptance:await nM({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Xc(bt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await kS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ue(bt(e.paths,e.name)),await SS(e.paths,i)),t={...t,status:a.nextStatus},await bS(e.paths,t)}return await _a.rm(nr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ue(bt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as AS}from"node:fs";import _S from"node:path";function aM(e,t){let i=Ae(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 oM(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function sM(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Ln(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ir(t),completed_at:i});return nt({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:oM(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 cM(e){try{let t=await uu(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 TS(e){return he(e.paths,`recover portable change ${e.name}`,async()=>{let t=await ka(e.paths,e.name);if(t.status==="done")return await hu({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=aM(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=cn(e.paths,e.name),n=await cM(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(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Cr(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await hu({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(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=jp({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await zr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await AS.rm(_S.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=sn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Cr(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 f=sM(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 zr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=sn({portableState:t,projectRoot:e.paths.projectRoot,branch:Ae(e.paths.projectRoot).currentBranch});return await AS.mkdir(_S.dirname(cn(e.paths,t.name)),{recursive:!0}),await Cr(r,d,{containedRoot:e.paths.runtimeDir}),await hu({paths:e.paths,state:t}),{state:t,local:d,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{promises as IS}from"node:fs";function lM(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function uM(e,t){let i=Ae(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function Ta(e){let t=await Ok(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=uM(e.paths,t.state),n=await us({paths:e.paths,state:t.state}),a=_u(t.state,n),o=r.bindingState==="mismatch"?{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...a.runnerAction,kind:"none"}}:a;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:lM(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{children:n.children,readyChildren:n.readyChildren}:{},continuation:o,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function jS(e){let t;try{t=await IS.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await IS.readFile(`${jt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import rm from"path";var Tu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var $S=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],im=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:$S,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] +`}function aH(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 du(e){let t;try{t=await tH.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=aH(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function fu(e){await ue(e.file,nH(e.state))}var jk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oH="comet-state.yaml",sH="state.json";function jt(e,t){if(!jk.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=_r.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function bt(e,t){return _r.join(jt(e,t),oH)}function cn(e,t){return _r.join(rt(e,t),sH)}async function Tr(e,t){try{let i=await fs.readFile(bt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function cH(e){return Ae(e).currentBranch}async function ka(e,t){return Ue(bt(e,t))}async function lH(e){let t=await zr({file:bt(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=_r.join(jt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await fs.rm(i,{force:!0})}return t}async function uH(e){let t=jt(e.paths,e.state.name),i=_r.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await fs.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(!jk.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=_r.join(t,...s.split("/")),l=await fs.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=_r.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await fs.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function dH(e){let t=jt(e.paths,e.state.name),i=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Jc({briefMarkdown:i.text,specs:r})}async function $k(e){let t=await uH(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 dH({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Ww(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Tp({changeDir:jt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Ip({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 Ok(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Ln(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ir(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 lH({paths:e.paths,previous:t,next:r});return await Cr(cn(e.paths,t.name),sn({portableState:n,projectRoot:e.paths.projectRoot,branch:cH(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function hu(e){if(e.state.verification===null)return"not-applicable";let t=_r.join(jt(e.paths,e.state.name),"verification.md");return await du({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await fu({file:t,state:e.state}),"rebuilt")}async function Hk(e){let t=await ka(e.paths,e.name),i=cn(e.paths,e.name);try{let r=await uu(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var VG=16*1024;async function pu(e){let t=await Pp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(xl(t.selection.change),t.selection)}function Dk(e){return nu(e.projectRoot)}async function hs(e,t){return await $n(e.projectRoot),Ek(e.projectRoot,"native",t)}var wU=16*1024*1024,mu=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"},ps=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"};function Fk(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Sa.resolve(e.nativeRoot,...i.target.split("/"))}async function Lk(e,t,i){let r=await lr(e,t.id);if(r.some(m=>m.type==="archive-finalized"))return;let n=r.some(m=>m.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let m=t.operations.find(y=>y.id==="archive-change");if(!m||m.type!=="move"||!m.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let N=await Qt(Fk(e,t));if(N?.kind!=="directory"||N.hash!==m.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Fk(e,t),o=Sa.join(a,Re),s=await yN(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await Ie(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let m=fm(pi,l,new Set,ep,void 0);if(!m.action)throw new Error(m.reason??"Native archive produced no action");u=hm(pi,m.state,{actionId:m.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},ep,void 0)}let d=F(`archive:${t.id}:${s.name}`),f=await Xe(c,u.trajectoryRef),p=f.filter(m=>m.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(m=>m.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=p.find(m=>m.type==="state_transitioned"),h={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!fH(v.data,h)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||p.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await ru(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await zn(e,t,"archive-finalization-started")),!s.archived){let m={...s,archived:!0};await wN(o,m)}v||(v=await Nr({changeDir:c,run:u,type:"state_transitioned",data:h,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await nn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Xr(c,u),await hs(e,s.name),t.schema==="comet.native.transaction.v2"?await ru(e,t,"archive-finalized"):await zn(e,t,"archive-finalized")}async function Dp(e,t){let i=rt(e,t);try{let r=await Mk.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await Mk.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function hH(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await lr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Zl({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new ps(c,"Native Archive facts changed before the first transaction operation")}let o=await Nk(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await $e(e,t.change),u=await Ql({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await Lk(e,o,i);let s=await ru(e,o,"commit");return{journal:s,runtimeCleanupWarning:await Dp(e,s.change)}}let r=await py(e,t);await Lk(e,r,i);let n=await zn(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await Dp(e,n.change):null}}function pH(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Sa.resolve(t.projectRoot)!==Sa.resolve(e.projectRoot)||Sa.resolve(t.nativeRoot)!==Sa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Bk(e){return he(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await er(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await mt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Sp(e.paths,e.transactionId):i;return pH(e.paths,r),r.status==="committed"?(r.change&&await Dp(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await hH(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?bk(e.paths,r):ll(e.paths,r)}finally{await tr(t)}},{allowedTransactionId:e.transactionId})}import{promises as AH}from"fs";async function qk(e,t){let i=[],r=H(e,t.name),n=Qi(r,vt.stateRef),a;try{a=await Ie(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Qi(r,a.trajectoryRef),s=await Zn(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await Xe(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Qi(r,a.checkpointRef);try{let u=await Qn(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var mH=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function vH(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function gH(e){return e?e.map(vH).join(" "):null}function wH(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function $t(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function yH(e){return e.map(t=>$t(t,[],null))}function NH(e){let t=["comet","native","next",e.name,"--summary",""],i=[$t("summary",["--summary"],"")];if(e.phase==="shape")return t.push("--confirmed"),i.push($t("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact",""),i.push($t("artifact-or-no-code-reason",["--artifact"],"",{repeatable:!0,alternativeGroup:"build-evidence"}),$t("artifact-or-no-code-reason",["--no-code-reason"],"",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push($t("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","","--report",""),i.push($t("verification-result",["--result"],"",{choices:["pass","fail"]}),$t("verification-report",["--report"],"")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Je(e,t){let i=t.commandArgs===void 0?wH(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?gH(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??yH(t.requiredInputs??[])}}function vu(e){let i=(e.findings??[]).filter(d=>!ea(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||mH.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Je(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Je(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[$t("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Je(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Je(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Je(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary",""],requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"")]});if(n)return Je(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary",""];return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Je(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Je(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[$t("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Je(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Je(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=NH(e.state);return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import ms from"path";var Vk=8,bH={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function kH(e){let t=bH[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ea(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function SH(e,t,i){if(!i.path)return null;let r;if(ms.isAbsolute(i.path)?r=ms.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=ms.resolve(re(e,t.name),...i.path.split(/[\\/]/u)):r=ms.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=ms.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function EH(e,t,i){return e==="next"?`comet native next ${t.name} --summary ""${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Mp(e){return e.findings.map(t=>{let i=kH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:SH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:EH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Fp(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,Vk),truncated:t.length>Vk}}var Wk=240,zk=8,gu=50;function Jk(e){let t=Array.from(e);return t.length<=Wk?e:`${t.slice(0,Wk-1).join("")}…`}function PH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function RH(e){let t=[...new Set(e.map(PH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,zk),reasonCount:e.length,codesTruncated:t.length>zk};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,gu),reasonsTruncated:e.length>gu}}}async function Gk(e){let t=null;try{let s=await Er(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Sr(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Sr(e.paths,e.state.name)}}let i=await Xb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=RH(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:kr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Jk(i.checkpoint.summary),nextAction:Jk(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:kr.maxArtifacts}}async function xH(e,t){let i=H(e,t.name),r=await Ie(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Qn(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Xe(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function CH(e,t){let i=await xH(e,t);return{committed:i,latest:xb(i),history:Rb(i)}}async function Uk(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await CH(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var _H=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ea=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Lp(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function TH(e){return(await pu(e))?.change??null}function IH(e,t,i=!1,r){return vu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function jH(e,t){let i=re(e,t.name),r=[...(await xh(i,t.brief)).findings,...(await EN(e,t)).findings,...await qk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Xn(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await vl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await ga({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ti(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Ch(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Bp(e,t,i){let r=await TH(e)===t,n=await No(e,t),a=await oN(e,t),o;try{let g=await ui(e,t);if(g.status==="migration-required"&&g.state)return{name:t,phase:g.state.phase,revision:"revision"in g.state?g.state.revision:null,approval:g.state.approval,verificationResult:g.state.verification_result,specChanges:g.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,migrationRequired:!0,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message};if(g.status!=="current"||!g.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${t} is incompatible`};o=g.state}catch(g){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:g.message}}if(n.status!=="available"){let g={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Mp({paths:e,state:o,findings:[g]}),D=vu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:D.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Fp(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:D,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await Gk({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Uk(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let g=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:g,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let g=await ga({changeDir:re(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let De=await ma(e,o.name,o.verification_evidence);for(let ce of De.acceptanceTrace.entries)P.set(ce.acceptanceId,ce.status==="failed"?"failed":ce.status==="missing"?"missing":"satisfied")}let D=Mw({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),O=D.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",D.nextCursor,"--project-root",e.projectRoot]:null;u={...D,...O?{nextPageCommand:Lp(O),nextPageArgs:O}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Bl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await wt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let P=await ia({paths:e,identity:g});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Fo({paths:e,identity:g});f.push(...P.findingCodes.map(D=>({code:D,message:`Native workspace advisory changed: ${D} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let g=await ok({paths:e,state:o});v=g.freshness!=="fresh",p.push(...g.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Zl({paths:e,name:o.name}),m.push(...h.findingCodes.map(g=>({code:g,message:`Native Archive is blocked: ${g}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let N=[...await jH(e,o),...s.findings,...d,...f,...p,...l,...m].filter((g,P,D)=>D.findIndex(O=>O.code===g.code&&O.path===g.path)===P),y=Mp({paths:e,state:o,findings:N}),E=y.filter(g=>!ea(g.code)),S=o.phase==="archive"&&h?.ready===!0&&E.length===0,k=v||o.phase==="archive"&&(h?.findingCodes??[]).some(g=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(g)),b=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",w=y.find(g=>g.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||R?null:IH(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:Fp(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:vu({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:gu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...w?{error:w.message}:{}}}async function $H(e){let t;try{t=await Jt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await AH.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ea.maxChanges))throw new Error(`Native status exceeds ${Ea.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function wu(e,t){let i=t.toString(36),r=M("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function OH(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=_H.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=M("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function HH(e,t){let i=await $H(e),r=M("comet.native.status-names.v1",i),n=OH({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ea.maxItems).map(u=>Bp(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,p={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:fEa.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Yk(e){return JSON.stringify(e,null,2)+` +`}function Jp(e){return e.schema===we?Cl(e):Qr(e)}function Vp(e,t){return{...e,schema:we,minimum_runtime_version:2,revision:t}}function qH(e){return{...e,schema:Si,minimum_runtime_version:2,revision:1,previousState:Vp(e.previousState,1),nextState:Vp(e.nextState,2)}}function Nu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:ge,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function VH(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?F(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:rr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Nu(e.previousState),nextState:{...Nu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:pi.definition.metadata.version,skillHash:ns}:e.nextRun}}function Xk(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Pa(e,t){return JSON.stringify(Cl(e))===JSON.stringify(Cl(t))}function Qk(e,t){return JSON.stringify(Qr(e))===JSON.stringify(Qr(t))}function $i(e,t){return zp(e,t)}function WH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(yu(n,LH,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!ln.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!ln.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=hr(n.previousRun),o=hr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!$i(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==Kk.size||u.some(f=>!Kk.has(f))||l.fromSchema!==we||l.toSchema!==ge||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function vs(e,t){return Wp.join(H(e,t),"schema-migration.json")}function zH(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");yu(e,MH,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===Ke&&i.toSchema===we,n=i.fromSchema===we&&i.toSchema===ge;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!ln.test(i.sourceHash)||typeof i.targetHash!="string"||!ln.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?ai(i.nextState):st(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(F((0,bu.stringify)(Jp(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");yu(i.transition,FH,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!ln.test(l.sourceHash)||typeof l.targetHash!="string"||!ln.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?cp(l.nextJournal,t):sp(l.nextJournal,t);if(F(JSON.stringify(l.nextJournal,null,2)+` +`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===we?Pa(a,u.previousState)||Pa(a,u.nextState):a.schema===ge&&(Qk(a,u.previousState)||Qk(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==ge)throw new Error("Schema migration transition supersede target schema is invalid");s=WH(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");yu(i.runRetreat,BH,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=hr(l.previousRun),d=hr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!ln.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==ge||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function gs(e,t){let i=vs(e,t),r=j(e,i);await T(r,i);try{let n=await il({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return zH(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function JH(e,t,i){let r=await Xn(e,t),n=r?await vl(e,r):await gl(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=hh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ra(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await vh(e,t,n)}async function eS(e){try{return await Gt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function GH(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function tS(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await Xe(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!zp(o.event,GH(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function UH(e,t,i){if(!t.transitionSupersede)return;let r=ze(e,t.change),n=await eS(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await Ie(a),s=await tS(e,t),c=await Qn(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!$i(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==F(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function KH(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await Ie(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!$i(a,r.nextRun)){if(!$i(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Xr(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!$i(await Ie(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await tS(e,t);if(o.sequence===null){let l=await Nr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await nn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=ze(e,t.change),c=await eS(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await Zk.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function YH(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await Ie(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!$i(n,t.runRetreat.nextRun)){if(!$i(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Xr(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await Xe(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Nr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await nn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function XH(e,t,i){let r=await gs(e,t);if(!r)return null;if(await aa(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Wp.join(re(e,t),Re),a=await Gt(n);if(await UH(e,r,a===r.targetHash),await JH(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await ue(n,(0,bu.stringify)(Jp(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=ze(e,t),s=await Gt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await te(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await KH(e,r,i),await YH(e,r,i),await Zk.rm(vs(e,t),{force:!0}),r.nextState}async function QH(e){let t=H(e.paths,e.state.name),i=await Ie(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:we,toSchema:ge,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function ZH(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Pa(i,t.previousState),a=Pa(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await Ie(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&$i(s,t.previousRun),l=$i(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await Xe(o,t.nextRun.trajectoryRef)).map((N,y)=>({event:N,index:y})).filter(({event:N})=>N.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let N={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!zp(f.event,N)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Nu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,m=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await Gt(ze(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:h,evidenceHash:m,eventData:{fromSchema:we,toSchema:ge,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function eD(e){let t,i,r,n;if(e.state.schema===Ke){if(t=Vp(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Jr)throw new Error("Native v1 change has a transition from another schema generation");let s=qH(e.pendingTransition.journal);if(Xk(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(Xk(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=ze(e.paths,e.name);i={sourceHash:await Gt(c),targetHash:F(Yk(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Si)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await ZH({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=VH(s);if(Pa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Pa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=ze(e.paths,e.name);i={sourceHash:await Gt(u),targetHash:F(Yk(l)),nextJournal:l}}}else t=Nu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await QH({paths:e.paths,state:e.state,migrationId:e.id}));let a=Wp.join(re(e.paths,e.name),Re),o=(0,bu.stringify)(Jp(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Ke?we:ge,sourceHash:await Gt(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function iS(e){return he(e.paths,`migrate schema for ${e.name}`,()=>an(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await XH(e.paths,e.name,e.hooks);if(i?.schema===ge)return i;let r=await ui(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await aa(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==Ke&&n.schema!==we)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await lp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await eD({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??DH()}),s=vs(e.paths,e.name),c=j(e.paths,s);await T(c,s),await te(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Oi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),rD=512*1024,un=/^([a-f0-9]{64})\.json$/u,nD=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,aD=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,ku=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Kp(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yi(e,t){return Kp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function sS(e,t){return Kp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ra(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ze(e,t){return et?1:0}function oD(e,t){let i=se.relative(e.projectRoot,t);if(i.length===0||se.isAbsolute(i)||i===".."||i.startsWith(`..${se.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(se.sep).join("/")}function cS(e,t){return se.join(H(e,t),"evidence")}function Su(e,t){return oD(e,cS(e,t))}async function Eu(e,t){let i=se.resolve(e),r=se.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=se.relative(i,r).split(se.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=se.join(o,s));let c=await X.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await X.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ra(c)})}return a}async function Ot(e){for(let t of e){let i=await X.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kp(t,i)||await X.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function lS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:pa(e,t)}function rS(e){return e!==null&&aD.test(e)?[e]:[]}function sD(e,t,i,r){if(e==="snapshots")return{canonical:ca(i,t),dependencies:[]};if(e==="scopes"){let a=la(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Hl(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[pa("scopes",a.scopeHash)]}}if(e==="verifications"){let a=Zo(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(rS));return{canonical:a,dependencies:[a.implementationScopeRef,vb(a.reportHash),...rS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||tD("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Ml(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=Dl(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Ir(e){let t=await X.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?rD:yr;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await X.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Gp.O_RDONLY|Gp.O_NOFOLLOW|Gp.O_NONBLOCK,a=await X.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!yi(Ra(t),o)||!yi(Ra(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,E=await a.read(u,0,Math.min(u.length,y),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,p,v]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!p.isFile()||p.isSymbolicLink()||v!==r||!yi(Ra(o),f)||!yi(Ra(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),m;try{m=JSON.parse(h)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let N=sD(e.kind,e.hash,m,e.name);if(h!==JSON.stringify(N.canonical,null,2)+` +`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ra(f),directoryChain:e.directoryChain,dependencies:[...new Set(N.dependencies)].sort(Ze)}}finally{await a.close()}}async function nS(e){try{return await X.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function cD(e){let t=H(e.paths,e.name),i=t,r=cS(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Eu(t,r);n=await X.readdir(r,{withFileTypes:!0}),await Ot(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of ku){if(!n.some(f=>f.name===s))continue;let c=se.join(r,s),l=await Eu(t,c),u=(await X.readdir(c,{withFileTypes:!0})).sort((f,p)=>Ze(f.name,p.name)),d=new Map;for(let f of u){let p=nD.exec(f.name);if(!p)continue;let v=d.get(p[1])??[];v.push(f),d.set(p[1],v)}for(let[f,p]of[...d.entries()].sort(([v],[h])=>Ze(v,h))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=p[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let h=se.join(c,f),m=un.exec(f)?.[1];if(!m)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let N=lS(s,m),y=se.join(c,v.name),E=await Ir({changeRoot:i,file:y,ref:N,kind:s,hash:m,name:e.name,directoryChain:l}),S=await nS(h),k=S?null:await Ir({changeRoot:i,file:h,ref:N,kind:s,hash:m,name:e.name,directoryChain:l});a.push({ref:N,original:h,quarantine:y,document:E,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Ze);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:xa(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Pu(o)}`),path:Su(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Ze(c.ref,l.ref))){if(await Ot(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Ir({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Ir({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!yi(s.originalDocument.identity,d.identity)||!yi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain);continue}if(!await nS(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await X.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!yi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await X.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Ir({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Ir({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!sS(s.document.identity,l.identity)||!yi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:xa(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Pu(o)}`),path:Su(e.paths,e.name)}]}}async function lD(e,t){let i=H(e,t),r=i,n=se.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Eu(i,n);a=await X.readdir(n,{withFileTypes:!0}),await Ot(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!ku.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Ze);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Pu(o)}`);let s=[],c=0;for(let l of ku){if(!a.some(p=>p.name===l))continue;let u=se.join(n,l),d=await Eu(r,u),f=(await X.readdir(u,{withFileTypes:!0})).sort((p,v)=>Ze(p.name,v.name));await Ot(d);for(let p of f){if(s.length>=Oi.maxDocuments)throw new Error(`Native evidence store exceeds ${Oi.maxDocuments} documents`);let v=un.exec(p.name);if(!v||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let h=lS(l,v[1]),m=se.join(u,p.name);await T(j(e,m),m);let N=await Ir({changeRoot:r,file:m,ref:h,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=N.size,c>Oi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Oi.maxScannedBytes} scanned bytes`);s.push(N)}await Ot(d)}return s}function aS(e,t){let i=new Set,r=[...e].sort(Ze).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Ze).reverse())i.has(o)||r.push(o)}return i}function uD(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ze),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Ze))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function dD(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=aS(t,r),a=new Set(n);for(let c of e)i-c.mtimeMsu.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ze(u.ref,d.ref)).slice(0,Oi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=aS(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Oi.minimumAgeMs).sort((c,l)=>Ze(c.ref,l.ref));return{candidates:uD(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Pu(e){let t=e.slice(0,Oi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function xa(e){let t=Oi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Up(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Ze);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:xa(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Pu(n)}`),path:r}}async function oS(e,t){try{await X.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await X.rename(e,t)}catch{}}async function fD(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ot(e.directoryChain);let i=await Ir({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:un.exec(se.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await X.lstat(e.file),n=await X.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!yi(e.identity,r)||!yi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=se.join(se.dirname(e.file),`.${se.basename(e.file)}.${iD()}.gc`);await X.rename(e.file,a);try{let[o,s]=await Promise.all([X.lstat(a),X.realpath(a)]);if(await Ot(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!sS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await oS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await X.rm(a),await Ot(e.directoryChain)}catch(o){throw await oS(a,e.file),o}}async function hD(e){if((await Ne(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await X.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await mt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function pD(e,t){if(t)return[t];let i;try{i=await X.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Ze)}async function mD(e,t){let i=await ui(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Ti(e,t),gs(e,t),Er(e,t)]);return r!==null||n!==null||a!==null}async function vD(e){if(await mD(e.paths,e.name))return[];let t=await ui(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await cD({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await lD(e.paths,e.name),a=dD(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Su(e.paths,e.name);if(!e.repair)return[...i.findings,Up(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await fD(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Up(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:xa(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Up(e.name,a,!0,o)]}async function uS(e){if(e.deferAll||await hD(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await pD(e.paths,e.name))try{a.push(...await vD({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:xa(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Su(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await he(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:xa(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as gD,randomUUID as XK}from"crypto";import{promises as Ns}from"fs";import ne from"path";var Xp=64*1024*1024,wD=256*1024,pS=16*1024*1024;async function et(e){try{return await Ns.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function yD(e){let t;try{t=await Ns.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await wt(e,i.name);if(r){await Pl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function ys(e,t){let i=[];async function r(n){let a=await pt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(n,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await Ns.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ie({root:e,file:c,maxBytes:Xp,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function ND(e,t,i,r){await oi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await pt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await Ns.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await oi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await sr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Xp,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Ca(e,t,i,r){let n=await ys(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await ys(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ne.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function bD(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function kD(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function SD(e){return`${e}.removing`}function dS(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function mS(e,t,i){return ne.join(cl(e,t).directory,`root-move-cleanup-${i}.json`)}function ED(e){return JSON.stringify(e,null,2)+` +`}function PD(e){return gD("sha256").update(e).digest("hex")}function RD(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function xD(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(RD);for(let a=0;a0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function CD(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=ED(t);if(Buffer.byteLength(i,"utf8")>pS)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await ue(mS(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),PD(i)}async function AD(e){let t=await ie({root:e.paths.runtimeDir,file:mS(e.paths,e.id,e.cleanup.kind),maxBytes:pS,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return xD(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Yp(e){let t=await ys(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function fS(e){return e.ref.split("/").length}async function _D(e){let i=[...await Yp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>fS(a)-fS(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ne.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await rl({root:e.projectRoot,file:a,maxBytes:Xp,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Xf({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Yp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Xf({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function vS(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function TD(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function ID(e,t,i,r){for(let a of[e,t])try{let o=await mt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ne.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ie({root:i,file:n,maxBytes:wD,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function hS(e){let t=vS(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Zi(e.projectRoot,t),t}async function ws(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=vS(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Zi(e.projectRoot,i),i}async function Ru(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await et(e.target),a=await et(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await CD({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await ys(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await AD({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await et(e.target),a=await et(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await iy({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return ws({projectRoot:e.projectRoot,config:t,id:e.id})}return await Yp({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await _D({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),ws({projectRoot:e.projectRoot,config:t,id:e.id})}async function jD(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await et(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=SD(e.staging);t=await Ru({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await ys(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await ND(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ca(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await hS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await et(e.destinationPaths.nativeRoot)){if(await et(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ca(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await et(e.staging))throw new Error("Native move staging tree is missing");await Ca(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ns.rename(e.staging,e.destinationPaths.nativeRoot)}t=await hS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await et(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=kD(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await et(e.sourcePaths.nativeRoot)&&await Ca(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Ru({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await yD(e.destinationPaths);let n=await mt(e.destinationPaths,e.pending.id);await zn(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Zi(e.projectRoot,o),o}async function gS(e){let t=await Ne(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await Be(e.projectRoot,i.fromArtifactRoot),n=await Be(e.projectRoot,i.toArtifactRoot),a=bD(n,i.id),o=await et(r.nativeRoot)?r:n,s=await er(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await ID(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await et(r.nativeRoot))throw v;let h=TD({id:i.id,paths:r,now:new Date});await fy(r,h),c={journal:h,paths:r}}if(e.strategy==="continue"){let v=await jD({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await et(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=dS(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await et(n.nativeRoot)&&await Ca(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Ru({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=dS(a,i.id);!t.native.pending_root_move?.cleanup&&await et(a)&&await Ca(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Ru({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await mt(r,i.id);await ll(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Zi(e.projectRoot,p),{activeNativeRoot:r.nativeRoot,config:p}}finally{await tr(s)}}var Aa=4096,$D=4096,OD=1024;async function jr(e,t,i){try{let r=await pt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Cu(e,t){let i=new Map(e.map(r=>[xe.resolve(r.file),{...r,file:xe.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await bo(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Ff(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function HD(e,t){let i=Dk(e),r;try{await T(e.projectRoot,i);let n=await pu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await Tr(e,r.change)?[]:(await $e(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await xu.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function DD(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function MD(e,t){let i=[],r=[];for(let n of await jr(e,e.transactionsDir,$D)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await mt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:xe.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await On([e],`doctor archive recovery ${a.id}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,"archive.lock")}],i)?(await Bk({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function FD(e,t,i){let r=[];for(let n of await jr(e,e.locksDir,OD)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=xe.join(e.locksDir,n.name);try{let o=await bo(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await Ff(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function LD(e,t,i=5){let r=[],n=t?await qp(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await qp(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:xe.join(e.changesDir,a.name,Re)});continue}let o=await Bp(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:xe.join(e.projectRoot,s.path)}:{}})}return r}async function BD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await Zn(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Xy(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:xe.join(H(e,n),"trajectory.jsonl")})}return i}async function qD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await No(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=Vr(e,n),s=rt(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await On([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Jt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await xu.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Jt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await xu.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await xu.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function VD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await kh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:ta(e,n),repair:"migrate"});continue}let a=await $e(e,n);await cN({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:ta(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:ta(e,n)})}return i}async function WD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=vs(e,n);try{let o=await gs(e,n),s=await ui(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:xe.join(e.changesDir,n,Re)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:xe.join(e.changesDir,n,Re),repair:"migrate"});continue}await iS({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:xe.join(e.changesDir,n,Re)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function zD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Ti(e,n)}catch(o){if(o instanceof as)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:ze(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await On([e],`doctor transition recovery ${n}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Bb(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:ze(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:ze(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:ze(e,n),repair:"continue"})}}return i}async function JD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Sr(e,n),o;try{o=await Er(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await On([e],`doctor checkpoint recovery ${n}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Zb(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function bs(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Ne(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([Be(r.projectRoot,c.fromArtifactRoot),Be(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Cu([{paths:l,file:xe.join(l.locksDir,"root-move.lock")},{paths:u,file:xe.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await gS({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await Be(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await DD(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await MD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await qD(r,{name:e.name,repair:t})),i.push(...await WD(r,{name:e.name,repair:t})),i.push(...await VD(r,{name:e.name,repair:t})),i.push(...await BD(r,{name:e.name,repair:t})),i.push(...await zD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await JD(r,{name:e.name,repair:t})),i.push(...await uS({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await FD(r,t,s.unfinished)),i.push(...await HD(r,t)),e.projectOnly||i.push(...await LD(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as GD}from"node:crypto";import{promises as He}from"node:fs";import dt from"node:path";var Qp=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 wS(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function yS(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=dt.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function Au(e){try{return await He.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function NS(e,t){let i=dt.normalize(dt.resolve(e)),r=dt.normalize(dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function UD(e,t){let i;try{i=await He.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=dt.join(e.archiveDir,n.name);try{let o=await Ue(dt.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 KD(e,t){let i=await el(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function dn(e,t){await He.mkdir(e.transactionsDir,{recursive:!0}),await te(nr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function YD(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Rn(e.paths.projectRoot);i.some(a=>NS(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Ne(a);if(!o)continue;let s=await Be(a,o.native.artifact_root);r.some(c=>NS(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 He.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 Ue(dt.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 _l(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 XD(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 QD(e){let t=dt.join(e.paths.specsDir,e.change.capability),i=dt.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await He.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 He.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([He.realpath(e.paths.specsDir),He.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await He.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await He.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await He.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=dt.join(jt(e.paths,e.state.name),e.change.source);await ue(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await He.mkdir(t,{recursive:!0}),await ue(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function bS(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 ZD(e,t){let i=jt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Q({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function eM(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(bS(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Zp(e){return he(e.paths,`archive portable change ${e.name}`,async()=>{let t=XD(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await KD(e.paths,e.name),r=jt(e.paths,e.name),n=await Au(r),a=n?null:await UD(e.paths,e.name),o;if(n)o=await ka(e.paths,e.name);else if(i)o=await Ue(dt.join(yS(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 $k({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await Ok({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=yS(e.paths,i?.archive_ref??wS(o)),c=await Au(s);if(i&&eM(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 hs(e.paths,o.name),await He.rm(rt(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)bS(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await YD({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new Qp(l);i={schema:Zc,id:GD(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:wS(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await ZD(e.paths,o),created_at:new Date().toISOString()},await dn(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await dn(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({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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 tM}from"node:crypto";import{promises as _a}from"node:fs";import CS from"node:path";var em=["evidence.md","repair.md","archive.md","checkpoint.md"],iM="verification.md";async function rM(e){try{return await _a.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function tm(e,t){let i=re(e,t),r=[nr(e,{kind:"migration",change:t}),Vr(e,t),...em.map(n=>CS.join(i,n))];return(await Promise.all(r.map(rM))).some(Boolean)}async function nM(e,t){let i=await el(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function kS(e,t){await _a.mkdir(e.transactionsDir,{recursive:!0}),await te(nr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function SS(e,t,i={}){let r=i.removeVerificationReport===!1?em:[...em,iM];await Promise.all([_a.rm(rt(e,t),{recursive:!0,force:!0}),_a.rm(Vr(e,t),{recursive:!0,force:!0}),...r.map(n=>_a.rm(CS.join(re(e,t),n),{force:!0}))])}async function ES(e,t){await Cr(cn(e,t.name),sn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function PS(e,t){try{let i=await wt(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 RS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=Ae(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 aM(e){let t=re(e.paths,e.state.name),i=await Q({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 Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Jc({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function xS(e,t){let i=await _l(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function ks(e){return he(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await nM(e.paths,e.name),i=await Tr(e.paths,e.name)?await Ue(bt(e.paths,e.name)):null;if(!t&&i)return await SS(e.paths,e.name,{removeVerificationReport:!1}),await ES(e.paths,i),i;let r=null,n=null;for(t||(r=await xS(e.paths,e.name),n=await PS(e.paths,e.name),RS(e.paths,n),t={schema:Qc,id:tM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await kS(e.paths,t));;){let a=Gw(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await xS(e.paths,e.name),n??=await PS(e.paths,e.name),RS(e.paths,n),i=Jw({state:r,acceptance:await aM({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Xc(bt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await SS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ue(bt(e.paths,e.name)),await ES(e.paths,i)),t={...t,status:a.nextStatus},await kS(e.paths,t)}return await _a.rm(nr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ue(bt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as AS}from"node:fs";import _S from"node:path";function oM(e,t){let i=Ae(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 sM(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function cM(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Ln(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ir(t),completed_at:i});return nt({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:sM(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 lM(e){try{let t=await uu(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 TS(e){return he(e.paths,`recover portable change ${e.name}`,async()=>{let t=await ka(e.paths,e.name);if(t.status==="done")return await hu({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=oM(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=cn(e.paths,e.name),n=await lM(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(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Cr(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await hu({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(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=jp({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await zr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await AS.rm(_S.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=sn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Cr(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 f=cM(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 zr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=sn({portableState:t,projectRoot:e.paths.projectRoot,branch:Ae(e.paths.projectRoot).currentBranch});return await AS.mkdir(_S.dirname(cn(e.paths,t.name)),{recursive:!0}),await Cr(r,d,{containedRoot:e.paths.runtimeDir}),await hu({paths:e.paths,state:t}),{state:t,local:d,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{promises as IS}from"node:fs";function uM(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function dM(e,t){let i=Ae(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function Ta(e){let t=await Hk(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=dM(e.paths,t.state),n=await us({paths:e.paths,state:t.state}),a=_u(t.state,n),o=r.bindingState==="mismatch"?{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...a.runnerAction,kind:"none"}}:a;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:uM(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{children:n.children,readyChildren:n.readyChildren}:{},continuation:o,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function jS(e){let t;try{t=await IS.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await IS.readFile(`${jt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import nm from"path";var Tu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var $S=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],rm=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:$S,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] comet native next --runner-input `,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 Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--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.","--runner-input 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 "Implementation changed" --return-to-build','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 "]},archive:{usage:`comet native archive --dry-run [--finish merge|push|pull-request|keep] - comet native archive [--confirmed] [--serial-first ]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first During execution only, confirm that this change archives before detected capability peers; the value must equal .","--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 [] [--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 tm(e,t){return`${e}: + comet native archive [--confirmed] [--serial-first ]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first During execution only, confirm that this change archives before detected capability peers; the value must equal .","--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 [] [--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 im(e,t){return`${e}: ${t.map(i=>` ${i}`).join(` -`)}`}function dM(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return im[i]||t.length>1&&im[t[0]]?.subcommands?i:t[0]}function fM(e=[]){let t=dM(e),i=im[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",tm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...$S];return n&&n.length>0&&r.push("",tm("Options",n)),r.push("",`Output: - ${i.output}`),i.examples&&r.push("",tm("Examples",i.examples)),t===""&&r.push("","Run `comet native --help` for command-specific details."),{topic:t,usage:`${r.join(` +`)}`}function fM(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return rm[i]||t.length>1&&rm[t[0]]?.subcommands?i:t[0]}function hM(e=[]){let t=fM(e),i=rm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",im("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...$S];return n&&n.length>0&&r.push("",im("Options",n)),r.push("",`Output: + ${i.output}`),i.examples&&r.push("",im("Examples",i.examples)),t===""&&r.push("","Run `comet native --help` for command-specific details."),{topic:t,usage:`${r.join(` `)} -`}}var hM=fM().usage;var W4=10*1024*1024,Ht=class extends Error{};function Iu(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Ht(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function ju(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ht(`${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 Ht(`${t} requires a value`);return e.splice(r,2),n}function HS(e){if(e.length>0)throw new Ht(`Unexpected argument: ${e[0]}`)}function OS(e,t){let i=rm.normalize(e),r=rm.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function pM(e){let t=rm.resolve(e),i=Ae(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ae(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!OS(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||OS(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function DS(e){return e?pM(e):$f(process.cwd())}async function MS(e){let t=await Ne(e);return Be(e,t?.native.artifact_root??"docs")}function Hi(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` +`}}var pM=hM().usage;var z4=10*1024*1024,Ht=class extends Error{};function Iu(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Ht(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function ju(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ht(`${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 Ht(`${t} requires a value`);return e.splice(r,2),n}function HS(e){if(e.length>0)throw new Ht(`Unexpected argument: ${e[0]}`)}function OS(e,t){let i=nm.normalize(e),r=nm.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function mM(e){let t=nm.resolve(e),i=Ae(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ae(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!OS(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||OS(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function DS(e){return e?mM(e):$f(process.cwd())}async function MS(e){let t=await Ne(e);return Be(e,t?.native.artifact_root??"docs")}function Hi(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` `}}function FS(e,t){if(t instanceof Ht)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof mu)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 ps)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Bo)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 qo)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 Tu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ra)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 Pr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof cs)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 LS(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` -`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Ss(e,t){let i=await us({paths:e,state:t});return _u(t,i)}async function mM(e){let t;try{t=await VS.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function vM(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function BS(e,t){let i;try{i=await VS.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${vM(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:Ou.join(e.archiveDir,n.name)}:null}function gM(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function $u(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function qS(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:Ou.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function wM(e,t){let i=[],r=[];for(let n of await Xw(e)){let a=Ur(n);if(t&&a.change!==t)continue;let o=Ou.join(e.transactionsDir,n);try{let s=await Ro(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function nm(e,t){let i=Iu(e,"--repair"),r=ju(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Ht("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();HS(e);let a=await MS(t),o=await wM(a,n);if(n&&o.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let d=await Tr(a,n)?await Ta({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await Zp({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ss(a,v.state)})}let p=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:p.schema,stateVersion:p.state_version},state:p,continuation:await Ss(a,p)})}return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await Tr(a,n)){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([BS(a,n),em(a,n)]);if(u){let p=await Ta({paths:a,name:n,details:!0});return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[u],continuation:p.continuation})}if(d&&!i){let p=await Ta({paths:a,name:n,details:!0});return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[qS(a,n)],continuation:p.continuation})}if(i){if(d){let v=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Ss(a,v)})}let p=await TS({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:p,continuation:await Ss(a,p.state)})}let f=await Ta({paths:a,name:n,details:!0});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ss(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await jS(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");if(i){let k=await bs({paths:a,repair:!0,projectOnly:!0}),b=[];for(let g of c.transactions)g.kind==="archive"?await Zp({paths:a,name:g.change}):await ks({paths:a,name:g.change}),b.push({kind:g.kind,change:g.change,transactionId:g.journal.id});let R=await nm([],t),w=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...w,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await mM(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),p=u.filter(k=>!d.has(k)),[v,h,m,N,y]=await Promise.all([Promise.all(s.map(k=>Ta({paths:a,name:k}))),Promise.all(s.map(k=>BS(a,k))),Promise.all(s.map(k=>em(a,k))),Promise.all(p.map(k=>bs({paths:a,name:k}))),bs({paths:a,projectOnly:!0})]),E=gM([...h.filter(k=>k!==null),...s.flatMap((k,b)=>m[b]&&!f.has(k)?[qS(a,k)]:[]),...c.findings,...p.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:Ou.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...N.flatMap(({findings:k})=>k),...y.findings]),S={healthy:E.every(k=>k.severity==="info"),workflow:p.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:p,findings:E};return S.healthy?Hi("doctor",S):$u(S)}let l=await bs({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Hi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}function yM(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}})+` -`}}async function WS(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{Iu(n,"--json"),s=ju(n,"--project-root");let u=[...n,...a],d=await DS(s);c=await t(u,d)}catch(u){c=FS(e,u)}let l=o?yM(c):LS(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` +`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Ss(e,t){let i=await us({paths:e,state:t});return _u(t,i)}async function vM(e){let t;try{t=await VS.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function gM(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function BS(e,t){let i;try{i=await VS.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${gM(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:Ou.join(e.archiveDir,n.name)}:null}function wM(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function $u(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function qS(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:Ou.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function yM(e,t){let i=[],r=[];for(let n of await Qw(e)){let a=Ur(n);if(t&&a.change!==t)continue;let o=Ou.join(e.transactionsDir,n);try{let s=await Ro(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function am(e,t){let i=Iu(e,"--repair"),r=ju(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Ht("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();HS(e);let a=await MS(t),o=await yM(a,n);if(n&&o.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let d=await Tr(a,n)?await Ta({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await Zp({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ss(a,v.state)})}let p=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:p.schema,stateVersion:p.state_version},state:p,continuation:await Ss(a,p)})}return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await Tr(a,n)){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([BS(a,n),tm(a,n)]);if(u){let p=await Ta({paths:a,name:n,details:!0});return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[u],continuation:p.continuation})}if(d&&!i){let p=await Ta({paths:a,name:n,details:!0});return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[qS(a,n)],continuation:p.continuation})}if(i){if(d){let v=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Ss(a,v)})}let p=await TS({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:p,continuation:await Ss(a,p.state)})}let f=await Ta({paths:a,name:n,details:!0});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ss(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await jS(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");if(i){let k=await bs({paths:a,repair:!0,projectOnly:!0}),b=[];for(let g of c.transactions)g.kind==="archive"?await Zp({paths:a,name:g.change}):await ks({paths:a,name:g.change}),b.push({kind:g.kind,change:g.change,transactionId:g.journal.id});let R=await am([],t),w=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...w,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await vM(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),p=u.filter(k=>!d.has(k)),[v,h,m,N,y]=await Promise.all([Promise.all(s.map(k=>Ta({paths:a,name:k}))),Promise.all(s.map(k=>BS(a,k))),Promise.all(s.map(k=>tm(a,k))),Promise.all(p.map(k=>bs({paths:a,name:k}))),bs({paths:a,projectOnly:!0})]),E=wM([...h.filter(k=>k!==null),...s.flatMap((k,b)=>m[b]&&!f.has(k)?[qS(a,k)]:[]),...c.findings,...p.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:Ou.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...N.flatMap(({findings:k})=>k),...y.findings]),S={healthy:E.every(k=>k.severity==="info"),workflow:p.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:p,findings:E};return S.healthy?Hi("doctor",S):$u(S)}let l=await bs({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Hi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}function NM(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}})+` +`}}async function WS(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{Iu(n,"--json"),s=ju(n,"--project-root");let u=[...n,...a],d=await DS(s);c=await t(u,d)}catch(u){c=FS(e,u)}let l=o?NM(c):LS(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` `)?"":` -`)),l.exitCode}process.exitCode=await WS("doctor",nm); +`)),l.exitCode}process.exitCode=await WS("doctor",am); diff --git a/assets/skills/comet-native/scripts/comet-native-next.mjs b/assets/skills/comet-native/scripts/comet-native-next.mjs index 66f6c02ae..c21835394 100644 --- a/assets/skills/comet-native/scripts/comet-native-next.mjs +++ b/assets/skills/comet-native/scripts/comet-native-next.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Qh=Object.create;var Ic=Object.defineProperty;var Zh=Object.getOwnPropertyDescriptor;var ep=Object.getOwnPropertyNames;var tp=Object.getPrototypeOf,ip=Object.prototype.hasOwnProperty;var Pr=(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 rp=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ep(t))!ip.call(e,n)&&n!==i&&Ic(e,n,{get:()=>t[n],enumerable:!(r=Zh(t,n))||r.enumerable});return e};var di=(e,t,i)=>(i=e!=null?Qh(tp(e)):{},rp(t||!e||!e.__esModule?Ic(i,"default",{value:e,enumerable:!0}):i,e));var x=y(z=>{"use strict";var Aa=Symbol.for("yaml.alias"),jc=Symbol.for("yaml.document"),xr=Symbol.for("yaml.map"),$c=Symbol.for("yaml.pair"),_a=Symbol.for("yaml.scalar"),Rr=Symbol.for("yaml.seq"),Je=Symbol.for("yaml.node.type"),np=e=>!!e&&typeof e=="object"&&e[Je]===Aa,ap=e=>!!e&&typeof e=="object"&&e[Je]===jc,op=e=>!!e&&typeof e=="object"&&e[Je]===xr,sp=e=>!!e&&typeof e=="object"&&e[Je]===$c,Oc=e=>!!e&&typeof e=="object"&&e[Je]===_a,cp=e=>!!e&&typeof e=="object"&&e[Je]===Rr;function Hc(e){if(e&&typeof e=="object")switch(e[Je]){case xr:case Rr:return!0}return!1}function lp(e){if(e&&typeof e=="object")switch(e[Je]){case Aa:case xr:case _a:case Rr:return!0}return!1}var up=e=>(Oc(e)||Hc(e))&&!!e.anchor;z.ALIAS=Aa;z.DOC=jc;z.MAP=xr;z.NODE_TYPE=Je;z.PAIR=$c;z.SCALAR=_a;z.SEQ=Rr;z.hasAnchor=up;z.isAlias=np;z.isCollection=Hc;z.isDocument=ap;z.isMap=op;z.isNode=lp;z.isPair=sp;z.isScalar=Oc;z.isSeq=cp});var fi=y(Ta=>{"use strict";var F=x(),Z=Symbol("break visit"),Dc=Symbol("skip children"),je=Symbol("remove node");function Cr(e,t){let i=Bc(t);F.isDocument(e)?Ht(null,e.contents,i,Object.freeze([e]))===je&&(e.contents=null):Ht(null,e,i,Object.freeze([]))}Cr.BREAK=Z;Cr.SKIP=Dc;Cr.REMOVE=je;function Ht(e,t,i,r){let n=Lc(e,t,i,r);if(F.isNode(n)||F.isPair(n))return Mc(e,r,n),Ht(e,n,i,r);if(typeof n!="symbol"){if(F.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var Fc=x(),dp=fi(),fp={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hp=e=>e.replace(/[!,[\]{}]/g,t=>fp[t]),hi=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+hp(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&&Fc.isNode(t.contents)){let a={};dp.visit(t.contents,(o,s)=>{Fc.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(` -`)}};hi.defaultYaml={explicit:!1,version:"1.2"};hi.defaultTags={"!!":"tag:yaml.org,2002:"};Vc.Directives=hi});var _r=y(pi=>{"use strict";var qc=x(),pp=fi();function mp(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 Wc(e){let t=new Set;return pp.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function zc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function vp(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Wc(e));let o=zc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(qc.isScalar(o.node)||qc.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}}pi.anchorIsValid=mp;pi.anchorNames=Wc;pi.createNodeAnchors=vp;pi.findNewAnchor=zc});var ja=y(Jc=>{"use strict";function mi(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var gp=x();function Gc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Gc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!gp.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}Uc.toJS=Gc});var Tr=y(Yc=>{"use strict";var wp=ja(),Kc=x(),yp=tt(),$a=class{constructor(t){Object.defineProperty(this,Kc.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(!Kc.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=yp.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?wp.applyReviver(a,{"":s},"",s):s}};Yc.NodeBase=$a});var vi=y(Xc=>{"use strict";var Np=_r(),bp=fi(),Bt=x(),kp=Tr(),Sp=tt(),Oa=class extends kp.NodeBase{constructor(t){super(Bt.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=[],bp.visit(t,{Node:(a,o)=>{(Bt.isAlias(o)||Bt.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||(Sp.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=Ir(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(Np.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 Ir(e,t,i){if(Bt.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Bt.isCollection(t)){let r=0;for(let n of t.items){let a=Ir(e,n,i);a>r&&(r=a)}return r}else if(Bt.isPair(t)){let r=Ir(e,t.key,i),n=Ir(e,t.value,i);return Math.max(r,n)}return 1}Xc.Alias=Oa});var L=y(Ha=>{"use strict";var Ep=x(),Pp=Tr(),xp=tt(),Rp=e=>!e||typeof e!="function"&&typeof e!="object",it=class extends Pp.NodeBase{constructor(t){super(Ep.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:xp.toJS(this.value,t,i)}toString(){return String(this.value)}};it.BLOCK_FOLDED="BLOCK_FOLDED";it.BLOCK_LITERAL="BLOCK_LITERAL";it.PLAIN="PLAIN";it.QUOTE_DOUBLE="QUOTE_DOUBLE";it.QUOTE_SINGLE="QUOTE_SINGLE";Ha.Scalar=it;Ha.isScalarValue=Rp});var gi=y(Zc=>{"use strict";var Cp=vi(),gt=x(),Qc=L(),Ap="tag:yaml.org,2002:";function _p(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 Tp(e,t,i){if(gt.isDocument(e)&&(e=e.contents),gt.isNode(e))return e;if(gt.isPair(e)){let d=i.schema[gt.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 Cp.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Ap+t.slice(2));let l=_p(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Qc.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[gt.MAP]:Symbol.iterator in Object(e)?o[gt.SEQ]:o[gt.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Qc.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Zc.createNode=Tp});var $r=y(jr=>{"use strict";var Ip=gi(),$e=x(),jp=Tr();function Da(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 Ip.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 el=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ba=class extends jp.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=>$e.isNode(r)||$e.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(el(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if($e.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Da(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($e.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&&$e.isScalar(a)?a.value:a:$e.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!$e.isPair(i))return!1;let r=i.value;return r==null||t&&$e.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 $e.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($e.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Da(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};jr.Collection=Ba;jr.collectionFromPath=Da;jr.isEmptyPath=el});var wi=y(Or=>{"use strict";var $p=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function La(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Op=(e,t,i)=>e.endsWith(` +var Zh=Object.create;var Ic=Object.defineProperty;var ep=Object.getOwnPropertyDescriptor;var tp=Object.getOwnPropertyNames;var ip=Object.getPrototypeOf,rp=Object.prototype.hasOwnProperty;var Pr=(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 np=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of tp(t))!rp.call(e,n)&&n!==i&&Ic(e,n,{get:()=>t[n],enumerable:!(r=ep(t,n))||r.enumerable});return e};var di=(e,t,i)=>(i=e!=null?Zh(ip(e)):{},np(t||!e||!e.__esModule?Ic(i,"default",{value:e,enumerable:!0}):i,e));var x=y(z=>{"use strict";var Aa=Symbol.for("yaml.alias"),jc=Symbol.for("yaml.document"),xr=Symbol.for("yaml.map"),$c=Symbol.for("yaml.pair"),_a=Symbol.for("yaml.scalar"),Rr=Symbol.for("yaml.seq"),Je=Symbol.for("yaml.node.type"),ap=e=>!!e&&typeof e=="object"&&e[Je]===Aa,op=e=>!!e&&typeof e=="object"&&e[Je]===jc,sp=e=>!!e&&typeof e=="object"&&e[Je]===xr,cp=e=>!!e&&typeof e=="object"&&e[Je]===$c,Oc=e=>!!e&&typeof e=="object"&&e[Je]===_a,lp=e=>!!e&&typeof e=="object"&&e[Je]===Rr;function Hc(e){if(e&&typeof e=="object")switch(e[Je]){case xr:case Rr:return!0}return!1}function up(e){if(e&&typeof e=="object")switch(e[Je]){case Aa:case xr:case _a:case Rr:return!0}return!1}var dp=e=>(Oc(e)||Hc(e))&&!!e.anchor;z.ALIAS=Aa;z.DOC=jc;z.MAP=xr;z.NODE_TYPE=Je;z.PAIR=$c;z.SCALAR=_a;z.SEQ=Rr;z.hasAnchor=dp;z.isAlias=ap;z.isCollection=Hc;z.isDocument=op;z.isMap=sp;z.isNode=up;z.isPair=cp;z.isScalar=Oc;z.isSeq=lp});var fi=y(Ta=>{"use strict";var F=x(),Z=Symbol("break visit"),Dc=Symbol("skip children"),je=Symbol("remove node");function Cr(e,t){let i=Bc(t);F.isDocument(e)?Ht(null,e.contents,i,Object.freeze([e]))===je&&(e.contents=null):Ht(null,e,i,Object.freeze([]))}Cr.BREAK=Z;Cr.SKIP=Dc;Cr.REMOVE=je;function Ht(e,t,i,r){let n=Lc(e,t,i,r);if(F.isNode(n)||F.isPair(n))return Mc(e,r,n),Ht(e,n,i,r);if(typeof n!="symbol"){if(F.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var Fc=x(),fp=fi(),hp={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},pp=e=>e.replace(/[!,[\]{}]/g,t=>hp[t]),hi=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+pp(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&&Fc.isNode(t.contents)){let a={};fp.visit(t.contents,(o,s)=>{Fc.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(` +`)}};hi.defaultYaml={explicit:!1,version:"1.2"};hi.defaultTags={"!!":"tag:yaml.org,2002:"};Vc.Directives=hi});var _r=y(pi=>{"use strict";var qc=x(),mp=fi();function vp(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 Wc(e){let t=new Set;return mp.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function zc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function gp(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Wc(e));let o=zc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(qc.isScalar(o.node)||qc.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}}pi.anchorIsValid=vp;pi.anchorNames=Wc;pi.createNodeAnchors=gp;pi.findNewAnchor=zc});var ja=y(Jc=>{"use strict";function mi(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var wp=x();function Gc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Gc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!wp.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}Uc.toJS=Gc});var Tr=y(Yc=>{"use strict";var yp=ja(),Kc=x(),Np=tt(),$a=class{constructor(t){Object.defineProperty(this,Kc.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(!Kc.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=Np.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?yp.applyReviver(a,{"":s},"",s):s}};Yc.NodeBase=$a});var vi=y(Xc=>{"use strict";var bp=_r(),kp=fi(),Bt=x(),Sp=Tr(),Ep=tt(),Oa=class extends Sp.NodeBase{constructor(t){super(Bt.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=[],kp.visit(t,{Node:(a,o)=>{(Bt.isAlias(o)||Bt.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||(Ep.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=Ir(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(bp.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 Ir(e,t,i){if(Bt.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Bt.isCollection(t)){let r=0;for(let n of t.items){let a=Ir(e,n,i);a>r&&(r=a)}return r}else if(Bt.isPair(t)){let r=Ir(e,t.key,i),n=Ir(e,t.value,i);return Math.max(r,n)}return 1}Xc.Alias=Oa});var L=y(Ha=>{"use strict";var Pp=x(),xp=Tr(),Rp=tt(),Cp=e=>!e||typeof e!="function"&&typeof e!="object",it=class extends xp.NodeBase{constructor(t){super(Pp.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Rp.toJS(this.value,t,i)}toString(){return String(this.value)}};it.BLOCK_FOLDED="BLOCK_FOLDED";it.BLOCK_LITERAL="BLOCK_LITERAL";it.PLAIN="PLAIN";it.QUOTE_DOUBLE="QUOTE_DOUBLE";it.QUOTE_SINGLE="QUOTE_SINGLE";Ha.Scalar=it;Ha.isScalarValue=Cp});var gi=y(Zc=>{"use strict";var Ap=vi(),gt=x(),Qc=L(),_p="tag:yaml.org,2002:";function Tp(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 Ip(e,t,i){if(gt.isDocument(e)&&(e=e.contents),gt.isNode(e))return e;if(gt.isPair(e)){let d=i.schema[gt.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 Ap.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=_p+t.slice(2));let l=Tp(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Qc.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[gt.MAP]:Symbol.iterator in Object(e)?o[gt.SEQ]:o[gt.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Qc.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Zc.createNode=Ip});var $r=y(jr=>{"use strict";var jp=gi(),$e=x(),$p=Tr();function Da(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 jp.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 el=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ba=class extends $p.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=>$e.isNode(r)||$e.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(el(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if($e.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Da(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($e.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&&$e.isScalar(a)?a.value:a:$e.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!$e.isPair(i))return!1;let r=i.value;return r==null||t&&$e.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 $e.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($e.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Da(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};jr.Collection=Ba;jr.collectionFromPath=Da;jr.isEmptyPath=el});var wi=y(Or=>{"use strict";var Op=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function La(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Hp=(e,t,i)=>e.endsWith(` `)?La(i,t):i.includes(` `)?` -`+La(i,t):(e.endsWith(" ")?"":" ")+i;Or.indentComment=La;Or.lineComment=Op;Or.stringifyComment=$p});var il=y(yi=>{"use strict";var Hp="flow",Ma="block",Hr="quoted";function Dp(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):d=n-r);let u,p,m=!1,h=-1,v=-1,g=-1;i===Ma&&(h=tl(e,h,t.length),h!==-1&&(d=h+c));for(let N;N=e[h+=1];){if(i===Hr&&N==="\\"){switch(v=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(N===` +`+La(i,t):(e.endsWith(" ")?"":" ")+i;Or.indentComment=La;Or.lineComment=Hp;Or.stringifyComment=Op});var il=y(yi=>{"use strict";var Dp="flow",Ma="block",Hr="quoted";function Bp(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):d=n-r);let u,p,m=!1,h=-1,v=-1,g=-1;i===Ma&&(h=tl(e,h,t.length),h!==-1&&(d=h+c));for(let N;N=e[h+=1];){if(i===Hr&&N==="\\"){switch(v=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(N===` `)i===Ma&&(h=tl(e,h,t.length)),d=h+t.length+c,u=void 0;else{if(N===" "&&p&&p!==" "&&p!==` `&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==` `&&k!==" "&&(u=h)}if(h>=d)if(u)l.push(u),d=u+c,u=void 0;else if(i===Hr){for(;p===" "||p===" ";)p=N,N=e[h+=1],m=!0;let k=h>g+1?h-2:v-1;if(f[k])return e;l.push(k),f[k]=!0,d=k+c,u=void 0}else m=!0}p=N}if(m&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let N=0;N{"use strict";var Ne=L(),rt=il(),Br=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Lr=e=>/^(%|---|\.\.\.)/m.test(e);function Bp(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{"use strict";var Ne=L(),rt=il(),Br=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Lr=e=>/^(%|---|\.\.\.)/m.test(e);function Lp(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;ar)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Ni(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Lr(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 f=i.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length `;let d,u;for(u=i.length;u>0;--u){let E=i[u-1];if(E!==` `&&E!==" "&&E!==" ")break}let p=i.substring(u),m=p.indexOf(` @@ -29,12 +29,12 @@ ${i}`)+"'";return t.implicitKey?r:rt.foldFlowLines(r,i,rt.FOLD_FLOW,Br(t,!1))}fu `)g=v;else break}let w=i.substring(0,g{S=!0});let b=rt.foldFlowLines(`${w}${E}${p}`,l,rt.FOLD_BLOCK,R);if(!S)return`>${k} ${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k} -${l}${w}${i}${p}`}function Lp(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(` +${l}${w}${i}${p}`}function Mp(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(` `)||f&&/[[\]{},]/.test(a))return Lt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(` `)?Lt(a,t):Dr(e,t,i,r);if(!s&&!f&&n!==Ne.Scalar.PLAIN&&a.includes(` `))return Dr(e,t,i,r);if(Lr(a)){if(c==="")return t.forceBlockIndent=!0,Dr(e,t,i,r);if(s&&c===l)return Lt(a,t)}let d=a.replace(/\n+/g,`$& -${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(u)||p?.some(u))return Lt(a,t)}return s?d:rt.foldFlowLines(d,c,rt.FOLD_FLOW,Br(t,!1))}function Mp(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!==Ne.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ne.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ne.Scalar.BLOCK_FOLDED:case Ne.Scalar.BLOCK_LITERAL:return n||a?Lt(o.value,t):Dr(o,t,i,r);case Ne.Scalar.QUOTE_DOUBLE:return Ni(o.value,t);case Ne.Scalar.QUOTE_SINGLE:return Fa(o.value,t);case Ne.Scalar.PLAIN:return Lp(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}rl.stringifyString=Mp});var ki=y(qa=>{"use strict";var Fp=_r(),nt=x(),Vp=wi(),qp=bi();function Wp(e,t){let i=Object.assign({blockQuote:!0,commentString:Vp.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 zp(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(nt.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 Jp(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(nt.isScalar(e)||nt.isCollection(e))&&e.anchor;a&&Fp.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 Gp(e,t,i,r){if(nt.isPair(e))return e.toString(t,i,r);if(nt.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=nt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=zp(t.doc.schema.tags,a));let o=Jp(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):nt.isScalar(a)?qp.stringifyString(a,t,i,r):a.toString(t,i,r);return o?nt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} -${t.indent}${s}`:s}qa.createStringifyContext=Wp;qa.stringify=Gp});var sl=y(ol=>{"use strict";var Ge=x(),nl=L(),al=ki(),Si=wi();function Up({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=i,u=Ge.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(Ge.isCollection(e)||!Ge.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||u&&t==null&&!i.inFlow||Ge.isCollection(e)||(Ge.isScalar(e)?e.type===nl.Scalar.BLOCK_FOLDED||e.type===nl.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,v=al.stringify(e,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return m&&r&&r(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,u&&!m?v+=Si.lineComment(v,i.indent,l(u)):h&&n&&n(),v;m&&(u=null),p?(u&&(v+=Si.lineComment(v,i.indent,l(u))),v=`? ${v} +${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(u)||p?.some(u))return Lt(a,t)}return s?d:rt.foldFlowLines(d,c,rt.FOLD_FLOW,Br(t,!1))}function Fp(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!==Ne.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ne.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ne.Scalar.BLOCK_FOLDED:case Ne.Scalar.BLOCK_LITERAL:return n||a?Lt(o.value,t):Dr(o,t,i,r);case Ne.Scalar.QUOTE_DOUBLE:return Ni(o.value,t);case Ne.Scalar.QUOTE_SINGLE:return Fa(o.value,t);case Ne.Scalar.PLAIN:return Mp(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}rl.stringifyString=Fp});var ki=y(qa=>{"use strict";var Vp=_r(),nt=x(),qp=wi(),Wp=bi();function zp(e,t){let i=Object.assign({blockQuote:!0,commentString:qp.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(nt.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 Gp(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(nt.isScalar(e)||nt.isCollection(e))&&e.anchor;a&&Vp.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 Up(e,t,i,r){if(nt.isPair(e))return e.toString(t,i,r);if(nt.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=nt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Jp(t.doc.schema.tags,a));let o=Gp(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):nt.isScalar(a)?Wp.stringifyString(a,t,i,r):a.toString(t,i,r);return o?nt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} +${t.indent}${s}`:s}qa.createStringifyContext=zp;qa.stringify=Up});var sl=y(ol=>{"use strict";var Ge=x(),nl=L(),al=ki(),Si=wi();function Kp({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=i,u=Ge.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(Ge.isCollection(e)||!Ge.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||u&&t==null&&!i.inFlow||Ge.isCollection(e)||(Ge.isScalar(e)?e.type===nl.Scalar.BLOCK_FOLDED||e.type===nl.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,v=al.stringify(e,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return m&&r&&r(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,u&&!m?v+=Si.lineComment(v,i.indent,l(u)):h&&n&&n(),v;m&&(u=null),p?(u&&(v+=Si.lineComment(v,i.indent,l(u))),v=`? ${v} ${s}:`):(v=`${v}:`,u&&(v+=Si.lineComment(v,i.indent,l(u))));let g,w,N;Ge.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,N=t.comment):(g=!1,w=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!u&&Ge.isScalar(t)&&(i.indentAtStart=v.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!p&&Ge.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,E=al.stringify(t,i,()=>k=!0,()=>h=!0),S=" ";if(u||g||w){if(S=g?` `:"",w){let R=l(w);S+=` ${Si.indentComment(R,i.indent)}`}E===""&&!i.inFlow?S===` @@ -44,32 +44,32 @@ ${Si.indentComment(R,i.indent)}`}E===""&&!i.inFlow?S===` ${i.indent}`}else if(!p&&Ge.isCollection(t)){let R=E[0],b=E.indexOf(` `),O=b!==-1,Ie=i.inFlow??t.flow??t.items.length===0;if(O||!Ie){let ze=!1;if(O&&(R==="&"||R==="!")){let M=E.indexOf(" ");R==="&"&&M!==-1&&M{"use strict";var cl=Pr("process");function Kp(e,...t){e==="debug"&&console.log(...t)}function Yp(e,t){(e==="debug"||e==="warn")&&(typeof cl.emitWarning=="function"?cl.emitWarning(t):console.warn(t))}Wa.debug=Kp;Wa.warn=Yp});var Wr=y(qr=>{"use strict";var Vr=x(),ll=L(),Mr="<<",Fr={identify:e=>e===Mr||typeof e=="symbol"&&e.description===Mr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ll.Scalar(Symbol(Mr)),{addToJSMap:ul}),stringify:()=>Mr},Xp=(e,t)=>(Fr.identify(t)||Vr.isScalar(t)&&(!t.type||t.type===ll.Scalar.PLAIN)&&Fr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Fr.tag&&i.default);function ul(e,t,i){let r=dl(e,i);if(Vr.isSeq(r))for(let n of r.items)Ja(e,t,n);else if(Array.isArray(r))for(let n of r)Ja(e,t,n);else Ja(e,t,r)}function Ja(e,t,i){let r=dl(e,i);if(!Vr.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 dl(e,t){return e&&Vr.isAlias(t)?t.resolve(e.doc,e):t}qr.addMergeToJSMap=ul;qr.isMergeKey=Xp;qr.merge=Fr});var Ua=y(pl=>{"use strict";var Qp=za(),fl=Wr(),Zp=ki(),hl=x(),Ga=tt();function em(e,t,{key:i,value:r}){if(hl.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(fl.isMergeKey(e,i))fl.addMergeToJSMap(e,t,r);else{let n=Ga.toJS(i,"",e);if(t instanceof Map)t.set(n,Ga.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=tm(i,n,e),o=Ga.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 tm(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(hl.isNode(e)&&i?.doc){let r=Zp.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)}pl.addPairToJSMap=em});var at=y(Ka=>{"use strict";var ml=gi(),im=sl(),rm=Ua(),zr=x();function nm(e,t,i){let r=ml.createNode(e,void 0,i),n=ml.createNode(t,void 0,i);return new Jr(r,n)}var Jr=class e{constructor(t,i=null){Object.defineProperty(this,zr.NODE_TYPE,{value:zr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return zr.isNode(i)&&(i=i.clone(t)),zr.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return rm.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?im.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ka.Pair=Jr;Ka.createPair=nm});var Ya=y(gl=>{"use strict";var wt=x(),vl=ki(),Gr=wi();function am(e,t,i){return(t.inFlow??e.flow?sm:om)(e,t,i)}function om({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:a,type:null}),d=!1,u=[];for(let m=0;mv=null,()=>d=!0);v&&(g+=Gr.lineComment(g,a,l(v))),d&&v&&(d=!1),u.push(r+g)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let m=1;m{"use strict";var cl=Pr("process");function Yp(e,...t){e==="debug"&&console.log(...t)}function Xp(e,t){(e==="debug"||e==="warn")&&(typeof cl.emitWarning=="function"?cl.emitWarning(t):console.warn(t))}Wa.debug=Yp;Wa.warn=Xp});var Wr=y(qr=>{"use strict";var Vr=x(),ll=L(),Mr="<<",Fr={identify:e=>e===Mr||typeof e=="symbol"&&e.description===Mr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ll.Scalar(Symbol(Mr)),{addToJSMap:ul}),stringify:()=>Mr},Qp=(e,t)=>(Fr.identify(t)||Vr.isScalar(t)&&(!t.type||t.type===ll.Scalar.PLAIN)&&Fr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Fr.tag&&i.default);function ul(e,t,i){let r=dl(e,i);if(Vr.isSeq(r))for(let n of r.items)Ja(e,t,n);else if(Array.isArray(r))for(let n of r)Ja(e,t,n);else Ja(e,t,r)}function Ja(e,t,i){let r=dl(e,i);if(!Vr.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 dl(e,t){return e&&Vr.isAlias(t)?t.resolve(e.doc,e):t}qr.addMergeToJSMap=ul;qr.isMergeKey=Qp;qr.merge=Fr});var Ua=y(pl=>{"use strict";var Zp=za(),fl=Wr(),em=ki(),hl=x(),Ga=tt();function tm(e,t,{key:i,value:r}){if(hl.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(fl.isMergeKey(e,i))fl.addMergeToJSMap(e,t,r);else{let n=Ga.toJS(i,"",e);if(t instanceof Map)t.set(n,Ga.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=im(i,n,e),o=Ga.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 im(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(hl.isNode(e)&&i?.doc){let r=em.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)+'..."'),Zp.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)}pl.addPairToJSMap=tm});var at=y(Ka=>{"use strict";var ml=gi(),rm=sl(),nm=Ua(),zr=x();function am(e,t,i){let r=ml.createNode(e,void 0,i),n=ml.createNode(t,void 0,i);return new Jr(r,n)}var Jr=class e{constructor(t,i=null){Object.defineProperty(this,zr.NODE_TYPE,{value:zr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return zr.isNode(i)&&(i=i.clone(t)),zr.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return nm.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?rm.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ka.Pair=Jr;Ka.createPair=am});var Ya=y(gl=>{"use strict";var wt=x(),vl=ki(),Gr=wi();function om(e,t,i){return(t.inFlow??e.flow?cm:sm)(e,t,i)}function sm({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:a,type:null}),d=!1,u=[];for(let m=0;mv=null,()=>d=!0);v&&(g+=Gr.lineComment(g,a,l(v))),d&&v&&(d=!1),u.push(r+g)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let m=1;mv=null);l||(l=d.length>f||g.includes(` +`+Gr.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function cm({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,f=0,d=[];for(let m=0;mv=null);l||(l=d.length>f||g.includes(` `)),m0&&(l||(l=d.reduce((w,N)=>w+N.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=Gr.lineComment(g,r,s(v))),d.push(g),f=d.length}let{start:u,end:p}=i;if(d.length===0)return u+p;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=u;for(let h of d)m+=h?` ${a}${n}${h}`:` `;return`${m} -${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function Ur({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Gr.indentComment(t(r),e);i.push(a.trimStart())}}gl.stringifyCollection=am});var st=y(Qa=>{"use strict";var cm=Ya(),lm=Ua(),um=$r(),ot=x(),Kr=at(),dm=L();function Ei(e,t){let i=ot.isScalar(t)?t.value:t;for(let r of e)if(ot.isPair(r)&&(r.key===t||r.key===i||ot.isScalar(r.key)&&r.key.value===i))return r}var Xa=class extends um.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ot.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(Kr.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;ot.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Kr.Pair(t,t?.value):r=new Kr.Pair(t.key,t.value);let n=Ei(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);ot.isScalar(n.value)&&dm.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=Ei(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Ei(this.items,t)?.value;return(!i&&ot.isScalar(n)?n.value:n)??void 0}has(t){return!!Ei(this.items,t)}set(t,i){this.add(new Kr.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)lm.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!ot.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})),cm.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Qa.YAMLMap=Xa;Qa.findPair=Ei});var Mt=y(yl=>{"use strict";var fm=x(),wl=st(),hm={collection:"map",default:!0,nodeClass:wl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return fm.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>wl.YAMLMap.from(e,t,i)};yl.map=hm});var ct=y(Nl=>{"use strict";var pm=gi(),mm=Ya(),vm=$r(),Xr=x(),gm=L(),wm=tt(),Za=class extends vm.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Xr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Yr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Yr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Xr.isScalar(n)?n.value:n}has(t){let i=Yr(t);return typeof i=="number"&&i=0?t:null}Nl.YAMLSeq=Za});var Ft=y(kl=>{"use strict";var ym=x(),bl=ct(),Nm={collection:"seq",default:!0,nodeClass:bl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ym.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>bl.YAMLSeq.from(e,t,i)};kl.seq=Nm});var Pi=y(Sl=>{"use strict";var bm=bi(),km={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),bm.stringifyString(e,t,i,r)}};Sl.string=km});var Qr=y(xl=>{"use strict";var El=L(),Pl={identify:e=>e==null,createNode:()=>new El.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new El.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Pl.test.test(e)?e:t.options.nullStr};xl.nullTag=Pl});var eo=y(Cl=>{"use strict";var Sm=L(),Rl={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Sm.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Rl.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Cl.boolTag=Rl});var Vt=y(Al=>{"use strict";function Em({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}Al.stringifyNumber=Em});var io=y(Zr=>{"use strict";var Pm=L(),to=Vt(),xm={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:to.stringifyNumber},Rm={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():to.stringifyNumber(e)}},Cm={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 Pm.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:to.stringifyNumber};Zr.float=Cm;Zr.floatExp=Rm;Zr.floatNaN=xm});var no=y(tn=>{"use strict";var _l=Vt(),en=e=>typeof e=="bigint"||Number.isInteger(e),ro=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Tl(e,t,i){let{value:r}=e;return en(r)&&r>=0?i+r.toString(t):_l.stringifyNumber(e)}var Am={identify:e=>en(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>ro(e,2,8,i),stringify:e=>Tl(e,8,"0o")},_m={identify:en,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>ro(e,0,10,i),stringify:_l.stringifyNumber},Tm={identify:e=>en(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>ro(e,2,16,i),stringify:e=>Tl(e,16,"0x")};tn.int=_m;tn.intHex=Tm;tn.intOct=Am});var jl=y(Il=>{"use strict";var Im=Mt(),jm=Qr(),$m=Ft(),Om=Pi(),Hm=eo(),ao=io(),oo=no(),Dm=[Im.map,$m.seq,Om.string,jm.nullTag,Hm.boolTag,oo.intOct,oo.int,oo.intHex,ao.floatNaN,ao.floatExp,ao.float];Il.schema=Dm});var Hl=y(Ol=>{"use strict";var Bm=L(),Lm=Mt(),Mm=Ft();function $l(e){return typeof e=="bigint"||Number.isInteger(e)}var rn=({value:e})=>JSON.stringify(e),Fm=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:rn},{identify:e=>e==null,createNode:()=>new Bm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:rn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:rn},{identify:$l,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})=>$l(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:rn}],Vm={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},qm=[Lm.map,Mm.seq].concat(Fm,Vm);Ol.schema=qm});var co=y(Dl=>{"use strict";var xi=Pr("buffer"),so=L(),Wm=bi(),zm={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof xi.Buffer=="function")return xi.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{"use strict";var nn=x(),lo=at(),Jm=L(),Gm=ct();function Bl(e,t){if(nn.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new lo.Pair(new Jm.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} +${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function Ur({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Gr.indentComment(t(r),e);i.push(a.trimStart())}}gl.stringifyCollection=om});var st=y(Qa=>{"use strict";var lm=Ya(),um=Ua(),dm=$r(),ot=x(),Kr=at(),fm=L();function Ei(e,t){let i=ot.isScalar(t)?t.value:t;for(let r of e)if(ot.isPair(r)&&(r.key===t||r.key===i||ot.isScalar(r.key)&&r.key.value===i))return r}var Xa=class extends dm.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ot.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(Kr.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;ot.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Kr.Pair(t,t?.value):r=new Kr.Pair(t.key,t.value);let n=Ei(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);ot.isScalar(n.value)&&fm.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=Ei(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Ei(this.items,t)?.value;return(!i&&ot.isScalar(n)?n.value:n)??void 0}has(t){return!!Ei(this.items,t)}set(t,i){this.add(new Kr.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)um.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!ot.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})),lm.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Qa.YAMLMap=Xa;Qa.findPair=Ei});var Mt=y(yl=>{"use strict";var hm=x(),wl=st(),pm={collection:"map",default:!0,nodeClass:wl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return hm.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>wl.YAMLMap.from(e,t,i)};yl.map=pm});var ct=y(Nl=>{"use strict";var mm=gi(),vm=Ya(),gm=$r(),Xr=x(),wm=L(),ym=tt(),Za=class extends gm.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Xr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Yr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Yr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Xr.isScalar(n)?n.value:n}has(t){let i=Yr(t);return typeof i=="number"&&i=0?t:null}Nl.YAMLSeq=Za});var Ft=y(kl=>{"use strict";var Nm=x(),bl=ct(),bm={collection:"seq",default:!0,nodeClass:bl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Nm.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>bl.YAMLSeq.from(e,t,i)};kl.seq=bm});var Pi=y(Sl=>{"use strict";var km=bi(),Sm={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),km.stringifyString(e,t,i,r)}};Sl.string=Sm});var Qr=y(xl=>{"use strict";var El=L(),Pl={identify:e=>e==null,createNode:()=>new El.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new El.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Pl.test.test(e)?e:t.options.nullStr};xl.nullTag=Pl});var eo=y(Cl=>{"use strict";var Em=L(),Rl={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Em.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Rl.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Cl.boolTag=Rl});var Vt=y(Al=>{"use strict";function Pm({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}Al.stringifyNumber=Pm});var io=y(Zr=>{"use strict";var xm=L(),to=Vt(),Rm={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:to.stringifyNumber},Cm={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():to.stringifyNumber(e)}},Am={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 xm.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:to.stringifyNumber};Zr.float=Am;Zr.floatExp=Cm;Zr.floatNaN=Rm});var no=y(tn=>{"use strict";var _l=Vt(),en=e=>typeof e=="bigint"||Number.isInteger(e),ro=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Tl(e,t,i){let{value:r}=e;return en(r)&&r>=0?i+r.toString(t):_l.stringifyNumber(e)}var _m={identify:e=>en(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>ro(e,2,8,i),stringify:e=>Tl(e,8,"0o")},Tm={identify:en,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>ro(e,0,10,i),stringify:_l.stringifyNumber},Im={identify:e=>en(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>ro(e,2,16,i),stringify:e=>Tl(e,16,"0x")};tn.int=Tm;tn.intHex=Im;tn.intOct=_m});var jl=y(Il=>{"use strict";var jm=Mt(),$m=Qr(),Om=Ft(),Hm=Pi(),Dm=eo(),ao=io(),oo=no(),Bm=[jm.map,Om.seq,Hm.string,$m.nullTag,Dm.boolTag,oo.intOct,oo.int,oo.intHex,ao.floatNaN,ao.floatExp,ao.float];Il.schema=Bm});var Hl=y(Ol=>{"use strict";var Lm=L(),Mm=Mt(),Fm=Ft();function $l(e){return typeof e=="bigint"||Number.isInteger(e)}var rn=({value:e})=>JSON.stringify(e),Vm=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:rn},{identify:e=>e==null,createNode:()=>new Lm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:rn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:rn},{identify:$l,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})=>$l(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:rn}],qm={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Wm=[Mm.map,Fm.seq].concat(Vm,qm);Ol.schema=Wm});var co=y(Dl=>{"use strict";var xi=Pr("buffer"),so=L(),zm=bi(),Jm={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof xi.Buffer=="function")return xi.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{"use strict";var nn=x(),lo=at(),Gm=L(),Um=ct();function Bl(e,t){if(nn.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new lo.Pair(new Gm.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment} -${a.comment}`:r.comment}r=n}e.items[i]=nn.isPair(r)?r:new lo.Pair(r)}}else t("Expected a sequence for this tag");return e}function Ll(e,t,i){let{replacer:r}=i,n=new Gm.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(lo.createPair(s,c,i))}return n}var Um={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bl,createNode:Ll};an.createPairs=Ll;an.pairs=Um;an.resolvePairs=Bl});var ho=y(fo=>{"use strict";var Ml=x(),uo=tt(),Ri=st(),Km=ct(),Fl=on(),yt=class e extends Km.YAMLSeq{constructor(){super(),this.add=Ri.YAMLMap.prototype.add.bind(this),this.delete=Ri.YAMLMap.prototype.delete.bind(this),this.get=Ri.YAMLMap.prototype.get.bind(this),this.has=Ri.YAMLMap.prototype.has.bind(this),this.set=Ri.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(Ml.isPair(n)?(a=uo.toJS(n.key,"",i),o=uo.toJS(n.value,a,i)):a=uo.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=Fl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};yt.tag="tag:yaml.org,2002:omap";var Ym={collection:"seq",identify:e=>e instanceof Map,nodeClass:yt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Fl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Ml.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new yt,i)},createNode:(e,t,i)=>yt.from(e,t,i)};fo.YAMLOMap=yt;fo.omap=Ym});var Jl=y(po=>{"use strict";var Vl=L();function ql({value:e,source:t},i){return t&&(e?Wl:zl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Wl={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 Vl.Scalar(!0),stringify:ql},zl={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 Vl.Scalar(!1),stringify:ql};po.falseTag=zl;po.trueTag=Wl});var Gl=y(sn=>{"use strict";var Xm=L(),mo=Vt(),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:mo.stringifyNumber},Zm={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():mo.stringifyNumber(e)}},ev={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 Xm.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:mo.stringifyNumber};sn.float=ev;sn.floatExp=Zm;sn.floatNaN=Qm});var Kl=y(Ai=>{"use strict";var Ul=Vt(),Ci=e=>typeof e=="bigint"||Number.isInteger(e);function cn(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 vo(e,t,i){let{value:r}=e;if(Ci(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Ul.stringifyNumber(e)}var tv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>cn(e,2,2,i),stringify:e=>vo(e,2,"0b")},iv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>cn(e,1,8,i),stringify:e=>vo(e,8,"0")},rv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>cn(e,0,10,i),stringify:Ul.stringifyNumber},nv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>cn(e,2,16,i),stringify:e=>vo(e,16,"0x")};Ai.int=rv;Ai.intBin=tv;Ai.intHex=nv;Ai.intOct=iv});var wo=y(go=>{"use strict";var dn=x(),ln=at(),un=st(),Nt=class e extends un.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;dn.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new ln.Pair(t.key,null):i=new ln.Pair(t,null),un.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=un.findPair(this.items,t);return!i&&dn.isPair(r)?dn.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=un.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new ln.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(ln.createPair(o,null,r));return a}};Nt.tag="tag:yaml.org,2002:set";var av={collection:"map",identify:e=>e instanceof Set,nodeClass:Nt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Nt.from(e,t,i),resolve(e,t){if(dn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Nt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};go.YAMLSet=Nt;go.set=av});var No=y(fn=>{"use strict";var ov=Vt();function yo(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 Yl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ov.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 sv={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})=>yo(e,i),stringify:Yl},cv={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=>yo(e,!1),stringify:Yl},Xl={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(Xl.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),f=t[8];if(f&&f!=="Z"){let d=yo(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};fn.floatTime=cv;fn.intTime=sv;fn.timestamp=Xl});var eu=y(Zl=>{"use strict";var lv=Mt(),uv=Qr(),dv=Ft(),fv=Pi(),hv=co(),Ql=Jl(),bo=Gl(),hn=Kl(),pv=Wr(),mv=ho(),vv=on(),gv=wo(),ko=No(),wv=[lv.map,dv.seq,fv.string,uv.nullTag,Ql.trueTag,Ql.falseTag,hn.intBin,hn.intOct,hn.int,hn.intHex,bo.floatNaN,bo.floatExp,bo.float,hv.binary,pv.merge,mv.omap,vv.pairs,gv.set,ko.intTime,ko.floatTime,ko.timestamp];Zl.schema=wv});var uu=y(Po=>{"use strict";var nu=Mt(),yv=Qr(),au=Ft(),Nv=Pi(),bv=eo(),So=io(),Eo=no(),kv=jl(),Sv=Hl(),ou=co(),_i=Wr(),su=ho(),cu=on(),tu=eu(),lu=wo(),pn=No(),iu=new Map([["core",kv.schema],["failsafe",[nu.map,au.seq,Nv.string]],["json",Sv.schema],["yaml11",tu.schema],["yaml-1.1",tu.schema]]),ru={binary:ou.binary,bool:bv.boolTag,float:So.float,floatExp:So.floatExp,floatNaN:So.floatNaN,floatTime:pn.floatTime,int:Eo.int,intHex:Eo.intHex,intOct:Eo.intOct,intTime:pn.intTime,map:nu.map,merge:_i.merge,null:yv.nullTag,omap:su.omap,pairs:cu.pairs,seq:au.seq,set:lu.set,timestamp:pn.timestamp},Ev={"tag:yaml.org,2002:binary":ou.binary,"tag:yaml.org,2002:merge":_i.merge,"tag:yaml.org,2002:omap":su.omap,"tag:yaml.org,2002:pairs":cu.pairs,"tag:yaml.org,2002:set":lu.set,"tag:yaml.org,2002:timestamp":pn.timestamp};function Pv(e,t,i){let r=iu.get(t);if(r&&!e)return i&&!r.includes(_i.merge)?r.concat(_i.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(iu.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(_i.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?ru[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(ru).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Po.coreKnownTags=Ev;Po.getTags=Pv});var Co=y(du=>{"use strict";var xo=x(),xv=Mt(),Rv=Ft(),Cv=Pi(),mn=uu(),Av=(e,t)=>e.keyt.key?1:0,Ro=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?mn.getTags(t,"compat"):t?mn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?mn.coreKnownTags:{},this.tags=mn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,xo.MAP,{value:xv.map}),Object.defineProperty(this,xo.SCALAR,{value:Cv.string}),Object.defineProperty(this,xo.SEQ,{value:Rv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Av:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};du.Schema=Ro});var hu=y(fu=>{"use strict";var _v=x(),Ao=ki(),Ti=wi();function Tv(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=Ao.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Ti.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(_v.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);i.push(Ti.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ao.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ti.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ao.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` +${a.comment}`:r.comment}r=n}e.items[i]=nn.isPair(r)?r:new lo.Pair(r)}}else t("Expected a sequence for this tag");return e}function Ll(e,t,i){let{replacer:r}=i,n=new Um.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(lo.createPair(s,c,i))}return n}var Km={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bl,createNode:Ll};an.createPairs=Ll;an.pairs=Km;an.resolvePairs=Bl});var ho=y(fo=>{"use strict";var Ml=x(),uo=tt(),Ri=st(),Ym=ct(),Fl=on(),yt=class e extends Ym.YAMLSeq{constructor(){super(),this.add=Ri.YAMLMap.prototype.add.bind(this),this.delete=Ri.YAMLMap.prototype.delete.bind(this),this.get=Ri.YAMLMap.prototype.get.bind(this),this.has=Ri.YAMLMap.prototype.has.bind(this),this.set=Ri.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(Ml.isPair(n)?(a=uo.toJS(n.key,"",i),o=uo.toJS(n.value,a,i)):a=uo.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=Fl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};yt.tag="tag:yaml.org,2002:omap";var Xm={collection:"seq",identify:e=>e instanceof Map,nodeClass:yt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Fl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Ml.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new yt,i)},createNode:(e,t,i)=>yt.from(e,t,i)};fo.YAMLOMap=yt;fo.omap=Xm});var Jl=y(po=>{"use strict";var Vl=L();function ql({value:e,source:t},i){return t&&(e?Wl:zl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Wl={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 Vl.Scalar(!0),stringify:ql},zl={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 Vl.Scalar(!1),stringify:ql};po.falseTag=zl;po.trueTag=Wl});var Gl=y(sn=>{"use strict";var Qm=L(),mo=Vt(),Zm={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:mo.stringifyNumber},ev={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():mo.stringifyNumber(e)}},tv={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 Qm.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:mo.stringifyNumber};sn.float=tv;sn.floatExp=ev;sn.floatNaN=Zm});var Kl=y(Ai=>{"use strict";var Ul=Vt(),Ci=e=>typeof e=="bigint"||Number.isInteger(e);function cn(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 vo(e,t,i){let{value:r}=e;if(Ci(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Ul.stringifyNumber(e)}var iv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>cn(e,2,2,i),stringify:e=>vo(e,2,"0b")},rv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>cn(e,1,8,i),stringify:e=>vo(e,8,"0")},nv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>cn(e,0,10,i),stringify:Ul.stringifyNumber},av={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>cn(e,2,16,i),stringify:e=>vo(e,16,"0x")};Ai.int=nv;Ai.intBin=iv;Ai.intHex=av;Ai.intOct=rv});var wo=y(go=>{"use strict";var dn=x(),ln=at(),un=st(),Nt=class e extends un.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;dn.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new ln.Pair(t.key,null):i=new ln.Pair(t,null),un.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=un.findPair(this.items,t);return!i&&dn.isPair(r)?dn.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=un.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new ln.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(ln.createPair(o,null,r));return a}};Nt.tag="tag:yaml.org,2002:set";var ov={collection:"map",identify:e=>e instanceof Set,nodeClass:Nt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Nt.from(e,t,i),resolve(e,t){if(dn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Nt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};go.YAMLSet=Nt;go.set=ov});var No=y(fn=>{"use strict";var sv=Vt();function yo(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 Yl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return sv.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 cv={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})=>yo(e,i),stringify:Yl},lv={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=>yo(e,!1),stringify:Yl},Xl={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(Xl.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),f=t[8];if(f&&f!=="Z"){let d=yo(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};fn.floatTime=lv;fn.intTime=cv;fn.timestamp=Xl});var eu=y(Zl=>{"use strict";var uv=Mt(),dv=Qr(),fv=Ft(),hv=Pi(),pv=co(),Ql=Jl(),bo=Gl(),hn=Kl(),mv=Wr(),vv=ho(),gv=on(),wv=wo(),ko=No(),yv=[uv.map,fv.seq,hv.string,dv.nullTag,Ql.trueTag,Ql.falseTag,hn.intBin,hn.intOct,hn.int,hn.intHex,bo.floatNaN,bo.floatExp,bo.float,pv.binary,mv.merge,vv.omap,gv.pairs,wv.set,ko.intTime,ko.floatTime,ko.timestamp];Zl.schema=yv});var uu=y(Po=>{"use strict";var nu=Mt(),Nv=Qr(),au=Ft(),bv=Pi(),kv=eo(),So=io(),Eo=no(),Sv=jl(),Ev=Hl(),ou=co(),_i=Wr(),su=ho(),cu=on(),tu=eu(),lu=wo(),pn=No(),iu=new Map([["core",Sv.schema],["failsafe",[nu.map,au.seq,bv.string]],["json",Ev.schema],["yaml11",tu.schema],["yaml-1.1",tu.schema]]),ru={binary:ou.binary,bool:kv.boolTag,float:So.float,floatExp:So.floatExp,floatNaN:So.floatNaN,floatTime:pn.floatTime,int:Eo.int,intHex:Eo.intHex,intOct:Eo.intOct,intTime:pn.intTime,map:nu.map,merge:_i.merge,null:Nv.nullTag,omap:su.omap,pairs:cu.pairs,seq:au.seq,set:lu.set,timestamp:pn.timestamp},Pv={"tag:yaml.org,2002:binary":ou.binary,"tag:yaml.org,2002:merge":_i.merge,"tag:yaml.org,2002:omap":su.omap,"tag:yaml.org,2002:pairs":cu.pairs,"tag:yaml.org,2002:set":lu.set,"tag:yaml.org,2002:timestamp":pn.timestamp};function xv(e,t,i){let r=iu.get(t);if(r&&!e)return i&&!r.includes(_i.merge)?r.concat(_i.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(iu.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(_i.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?ru[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(ru).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Po.coreKnownTags=Pv;Po.getTags=xv});var Co=y(du=>{"use strict";var xo=x(),Rv=Mt(),Cv=Ft(),Av=Pi(),mn=uu(),_v=(e,t)=>e.keyt.key?1:0,Ro=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?mn.getTags(t,"compat"):t?mn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?mn.coreKnownTags:{},this.tags=mn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,xo.MAP,{value:Rv.map}),Object.defineProperty(this,xo.SCALAR,{value:Av.string}),Object.defineProperty(this,xo.SEQ,{value:Cv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?_v:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};du.Schema=Ro});var hu=y(fu=>{"use strict";var Tv=x(),Ao=ki(),Ti=wi();function Iv(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=Ao.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Ti.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Tv.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);i.push(Ti.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ao.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ti.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ao.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` `)?(i.push("..."),i.push(Ti.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(Ti.indentComment(a(c),"")))}return i.join(` `)+` -`}fu.stringifyDocument=Tv});var Ii=y(pu=>{"use strict";var Iv=vi(),qt=$r(),le=x(),jv=at(),$v=tt(),Ov=Co(),Hv=hu(),_o=_r(),Dv=ja(),Bv=gi(),To=Ia(),Io=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 To.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){Wt(this.contents)&&this.contents.add(t)}addIn(t,i){Wt(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=_o.anchorNames(this);t.anchor=!i||r.has(i)?_o.findNewAnchor(i||"a",r):i}return new Iv.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 v=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=i.filter(v).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:f}=r??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=_o.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Bv.createNode(t,f,m);return s&&le.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new jv.Pair(n,a)}delete(t){return Wt(this.contents)?this.contents.delete(t):!1}deleteIn(t){return qt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Wt(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 qt.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 qt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=qt.collectionFromPath(this.schema,[t],i):Wt(this.contents)&&this.contents.set(t,i)}setIn(t,i){qt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=qt.collectionFromPath(this.schema,Array.from(t),i):Wt(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 To.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 To.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 Ov.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=$v.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Dv.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 Hv.stringifyDocument(this,t)}};function Wt(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}pu.Document=Io});var Oi=y($i=>{"use strict";var ji=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},jo=class extends ji{constructor(t,i,r){super("YAMLParseError",t,i,r)}},$o=class extends ji{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Lv=(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)+`… +`}fu.stringifyDocument=Iv});var Ii=y(pu=>{"use strict";var jv=vi(),qt=$r(),le=x(),$v=at(),Ov=tt(),Hv=Co(),Dv=hu(),_o=_r(),Bv=ja(),Lv=gi(),To=Ia(),Io=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 To.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){Wt(this.contents)&&this.contents.add(t)}addIn(t,i){Wt(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=_o.anchorNames(this);t.anchor=!i||r.has(i)?_o.findNewAnchor(i||"a",r):i}return new jv.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 v=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=i.filter(v).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:f}=r??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=_o.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Lv.createNode(t,f,m);return s&&le.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new $v.Pair(n,a)}delete(t){return Wt(this.contents)?this.contents.delete(t):!1}deleteIn(t){return qt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Wt(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 qt.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 qt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=qt.collectionFromPath(this.schema,[t],i):Wt(this.contents)&&this.contents.set(t,i)}setIn(t,i){qt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=qt.collectionFromPath(this.schema,Array.from(t),i):Wt(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 To.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 To.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 Hv.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=Ov.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Bv.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 Dv.stringifyDocument(this,t)}};function Wt(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}pu.Document=Io});var Oi=y($i=>{"use strict";var ji=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},jo=class extends ji{constructor(t,i,r){super("YAMLParseError",t,i,r)}},$o=class extends ji{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Mv=(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)+`… `),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+=`: ${o} ${l} -`}};$i.YAMLError=ji;$i.YAMLParseError=jo;$i.YAMLWarning=$o;$i.prettifyError=Lv});var Hi=y(mu=>{"use strict";function Mv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,m=!1,h=null,v=null,g=null,w=null,N=null,k=null,E=null;for(let b of e)switch(m&&(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"),m=!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),f=!0;break;case"comment":{f||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=b.source.substring(1)||" ";d?d+=u+O:d=O,u="",l=!1;break}case"newline":l?d?d+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=b.source,l=!0,p=!0,(v||g)&&(w=b),f=!0;break;case"anchor":v&&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),v=b,E??(E=b.offset),l=!1,f=!1,m=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,E??(E=b.offset),l=!1,f=!1,m=!0;break}case i:(v||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",f=!1;break;case"comma":if(t){N&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=b,l=!1,f=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let S=e[e.length-1],R=S?S.offset+S.source.length:n;return m&&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:N,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:g,newlineAfterProp:w,end:R,start:E??R}}mu.resolveProps=Mv});var vn=y(vu=>{"use strict";function Oo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` -`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Oo(t.key)||Oo(t.value))return!0}return!1;default:return!0}}vu.containsNewline=Oo});var Ho=y(gu=>{"use strict";var Fv=vn();function Vv(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Fv.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}gu.flowIndentCheck=Vv});var Do=y(yu=>{"use strict";var wu=x();function qv(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||wu.isScalar(a)&&wu.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}yu.mapIncludes=qv});var Pu=y(Eu=>{"use strict";var Nu=at(),Wv=st(),bu=Hi(),zv=vn(),ku=Ho(),Jv=Do(),Su="All mapping items must start at the same column";function Gv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Wv.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:d,key:u,sep:p,value:m}=f,h=bu.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),v=!h.found;if(v){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",Su)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` -`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||zv.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Su);i.atKey=!0;let g=h.end,w=u?e(i,u,h,n):t(i,g,d,null,h,n);i.schema.compat&&ku.flowIndentCheck(r.indent,u,n),i.atKey=!1,Jv.mapIncludes(i,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let N=bu.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=N.end,N.found){v&&(m?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var Uv=ct(),Kv=Hi(),Yv=Ho();function Xv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Uv.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:f,value:d}of r.items){let u=Kv.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?e(i,d,u,n):t(i,u.end,f,null,u,n);i.schema.compat&&Yv.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}xu.resolveBlockSeq=Xv});var zt=y(Cu=>{"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 f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Cu.resolveEnd=Qv});var Iu=y(Tu=>{"use strict";var Zv=x(),eg=at(),Au=st(),tg=ct(),ig=zt(),_u=Hi(),rg=vn(),ng=Do(),Bo="Block collections are not allowed within flow collections",Lo=e=>e&&(e.type==="block-map"||e.type==="block-seq");function ag({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Au.YAMLMap:tg.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let v=0;v{"use strict";function Fv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,m=!1,h=null,v=null,g=null,w=null,N=null,k=null,E=null;for(let b of e)switch(m&&(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"),m=!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),f=!0;break;case"comment":{f||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=b.source.substring(1)||" ";d?d+=u+O:d=O,u="",l=!1;break}case"newline":l?d?d+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=b.source,l=!0,p=!0,(v||g)&&(w=b),f=!0;break;case"anchor":v&&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),v=b,E??(E=b.offset),l=!1,f=!1,m=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,E??(E=b.offset),l=!1,f=!1,m=!0;break}case i:(v||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",f=!1;break;case"comma":if(t){N&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=b,l=!1,f=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let S=e[e.length-1],R=S?S.offset+S.source.length:n;return m&&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:N,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:g,newlineAfterProp:w,end:R,start:E??R}}mu.resolveProps=Fv});var vn=y(vu=>{"use strict";function Oo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` +`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Oo(t.key)||Oo(t.value))return!0}return!1;default:return!0}}vu.containsNewline=Oo});var Ho=y(gu=>{"use strict";var Vv=vn();function qv(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Vv.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}gu.flowIndentCheck=qv});var Do=y(yu=>{"use strict";var wu=x();function Wv(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||wu.isScalar(a)&&wu.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}yu.mapIncludes=Wv});var Pu=y(Eu=>{"use strict";var Nu=at(),zv=st(),bu=Hi(),Jv=vn(),ku=Ho(),Gv=Do(),Su="All mapping items must start at the same column";function Uv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??zv.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:d,key:u,sep:p,value:m}=f,h=bu.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),v=!h.found;if(v){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",Su)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` +`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Jv.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Su);i.atKey=!0;let g=h.end,w=u?e(i,u,h,n):t(i,g,d,null,h,n);i.schema.compat&&ku.flowIndentCheck(r.indent,u,n),i.atKey=!1,Gv.mapIncludes(i,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let N=bu.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=N.end,N.found){v&&(m?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var Kv=ct(),Yv=Hi(),Xv=Ho();function Qv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Kv.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:f,value:d}of r.items){let u=Yv.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?e(i,d,u,n):t(i,u.end,f,null,u,n);i.schema.compat&&Xv.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}xu.resolveBlockSeq=Qv});var zt=y(Cu=>{"use strict";function Zv(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 f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Cu.resolveEnd=Zv});var Iu=y(Tu=>{"use strict";var eg=x(),tg=at(),Au=st(),ig=ct(),rg=zt(),_u=Hi(),ng=vn(),ag=Do(),Bo="Block collections are not allowed within flow collections",Lo=e=>e&&(e.type==="block-map"||e.type==="block-seq");function og({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Au.YAMLMap:ig.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let v=0;v0){let v=ig.resolveEnd(m,h,i.options.strict,n);v.comment&&(l.comment?l.comment+=` -`+v.comment:l.comment=v.comment),l.range=[r.offset,h,v.offset]}else l.range=[r.offset,h,h];return l}Tu.resolveFlowCollection=ag});var $u=y(ju=>{"use strict";var og=x(),sg=L(),cg=st(),lg=ct(),ug=Pu(),dg=Ru(),fg=Iu();function Mo(e,t,i,r,n,a){let o=i.type==="block-map"?ug.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?dg.resolveBlockSeq(e,t,i,r,a):fg.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function hg(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,m=u&&a?u.offset>a.offset?u:a:u??a;m&&(!p||p.offsetu.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Mo(e,t,i,n,o)}let l=Mo(e,t,i,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=og.isNode(f)?f:new sg.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ju.composeCollection=hg});var Vo=y(Ou=>{"use strict";var Fo=L();function pg(e,t,i){let r=t.offset,n=mg(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Fo.Scalar.BLOCK_FOLDED:Fo.Scalar.BLOCK_LITERAL,o=t.source?vg(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` +`+O.comment:b.comment=O.comment);let ze=new tg.Pair(b,Ie);if(i.options.keepSourceTokens&&(ze.srcToken=g),o){let M=l;ag.mapIncludes(i,M.items,b)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),M.items.push(ze)}else{let M=new Au.YAMLMap(i.schema);M.flow=!0,M.items.push(ze);let Tc=(Ie??b).range;M.range=[b.range[0],Tc[1],Tc[2]],l.items.push(M)}d=Ie?Ie.range[2]:O.end}}let u=o?"}":"]",[p,...m]=r.end,h=d;if(p?.source===u)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=f?`${v} must end with a ${u}`:`${v} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",g),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=rg.resolveEnd(m,h,i.options.strict,n);v.comment&&(l.comment?l.comment+=` +`+v.comment:l.comment=v.comment),l.range=[r.offset,h,v.offset]}else l.range=[r.offset,h,h];return l}Tu.resolveFlowCollection=og});var $u=y(ju=>{"use strict";var sg=x(),cg=L(),lg=st(),ug=ct(),dg=Pu(),fg=Ru(),hg=Iu();function Mo(e,t,i,r,n,a){let o=i.type==="block-map"?dg.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?fg.resolveBlockSeq(e,t,i,r,a):hg.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function pg(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,m=u&&a?u.offset>a.offset?u:a:u??a;m&&(!p||p.offsetu.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Mo(e,t,i,n,o)}let l=Mo(e,t,i,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=sg.isNode(f)?f:new cg.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ju.composeCollection=pg});var Vo=y(Ou=>{"use strict";var Fo=L();function mg(e,t,i){let r=t.offset,n=vg(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Fo.Scalar.BLOCK_FOLDED:Fo.Scalar.BLOCK_LITERAL,o=t.source?gg(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",v=r+n.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let h=0;hc&&(c=v.length);else{v.length=s;--h)o[h][0].length>c&&(s=h+1);let d="",u="",p=!1;for(let h=0;hc||g[0]===" "?(u===" "?u=` @@ -84,41 +84,41 @@ ${l} `+o[h][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let m=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,m,m]}}function mg({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let u=1;u{"use strict";var qo=L(),gg=zt();function wg(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(u,p,m)=>i(r+u,p,m);switch(n){case"scalar":s=qo.Scalar.PLAIN,c=yg(a,l);break;case"single-quoted-scalar":s=qo.Scalar.QUOTE_SINGLE,c=Ng(a,l);break;case"double-quoted-scalar":s=qo.Scalar.QUOTE_DOUBLE,c=bg(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let f=r+a.length,d=gg.resolveEnd(o,f,t,i);return{value:c,type:s,comment:d.comment,range:[r,f,d.offset]}}function yg(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Hu(e)}function Ng(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Hu(e.slice(1,-1)).replace(/''/g,"'")}function Hu(e){let t,i;try{t=new RegExp(`(.*?)(?{"use strict";var qo=L(),wg=zt();function yg(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(u,p,m)=>i(r+u,p,m);switch(n){case"scalar":s=qo.Scalar.PLAIN,c=Ng(a,l);break;case"single-quoted-scalar":s=qo.Scalar.QUOTE_SINGLE,c=bg(a,l);break;case"double-quoted-scalar":s=qo.Scalar.QUOTE_DOUBLE,c=kg(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let f=r+a.length,d=wg.resolveEnd(o,f,t,i);return{value:c,type:s,comment:d.comment,range:[r,f,d.offset]}}function Ng(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Hu(e)}function bg(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Hu(e.slice(1,-1)).replace(/''/g,"'")}function Hu(e){let t,i;try{t=new RegExp(`(.*?)(?a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function kg(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===` +`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Sg(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===` `||r==="\r")&&!(r==="\r"&&e[t+2]!==` `);)r===` `&&(i+=` -`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Sg={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Eg(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}}Du.resolveFlowScalar=wg});var Mu=y(Lu=>{"use strict";var bt=x(),Bu=L(),Pg=Vo(),xg=Wo();function Rg(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Pg.resolveBlockScalar(e,t,r):xg.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[bt.SCALAR]:c?l=Cg(e.schema,n,c,i,r):t.type==="scalar"?l=Ag(e,n,t,r):l=e.schema[bt.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??t,"TAG_RESOLVE_FAILED",u),e.options);f=bt.isScalar(d)?d:new Bu.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",u),f=new Bu.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Cg(e,t,i,r,n){if(i==="!")return e[bt.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[bt.SCALAR])}function Ag({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[bt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[bt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Lu.composeScalar=Rg});var Vu=y(Fu=>{"use strict";function _g(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}Fu.emptyScalarPosition=_g});var zu=y(Jo=>{"use strict";var Tg=vi(),Ig=x(),jg=$u(),qu=Mu(),$g=zt(),Og=Vu(),Hg={composeNode:Wu,composeEmptyNode:zo};function Wu(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(t.type){case"alias":l=Dg(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=qu.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=jg.composeCollection(Hg,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",u)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=zo(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&&(!Ig.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&&f&&(l.srcToken=t),l}function zo(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Og.emptyScalarPosition(t,i,r),indent:-1,source:""},d=qu.composeScalar(e,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Dg({options:e},{offset:t,source:i,end:r},n){let a=new Tg.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=$g.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Jo.composeEmptyNode=zo;Jo.composeNode=Wu});var Uu=y(Gu=>{"use strict";var Bg=Ii(),Ju=zu(),Lg=zt(),Mg=Hi();function Fg(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Bg.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Mg.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Ju.composeNode(l,n,f,o):Ju.composeEmptyNode(l,f.end,r,null,f,o);let d=c.contents.range[2],u=Lg.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,d,u.offset],c}Gu.composeDoc=Fg});var Uo=y(Xu=>{"use strict";var Vg=Pr("process"),qg=Ia(),Wg=Ii(),Di=Oi(),Ku=x(),zg=Uu(),Jg=zt();function Bi(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 Yu(e){let t="",i=!1,r=!1;for(let n=0;n{"use strict";var bt=x(),Bu=L(),xg=Vo(),Rg=Wo();function Cg(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?xg.resolveBlockScalar(e,t,r):Rg.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[bt.SCALAR]:c?l=Ag(e.schema,n,c,i,r):t.type==="scalar"?l=_g(e,n,t,r):l=e.schema[bt.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??t,"TAG_RESOLVE_FAILED",u),e.options);f=bt.isScalar(d)?d:new Bu.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",u),f=new Bu.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Ag(e,t,i,r,n){if(i==="!")return e[bt.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[bt.SCALAR])}function _g({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[bt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[bt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Lu.composeScalar=Cg});var Vu=y(Fu=>{"use strict";function Tg(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}Fu.emptyScalarPosition=Tg});var zu=y(Jo=>{"use strict";var Ig=vi(),jg=x(),$g=$u(),qu=Mu(),Og=zt(),Hg=Vu(),Dg={composeNode:Wu,composeEmptyNode:zo};function Wu(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(t.type){case"alias":l=Bg(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=qu.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=$g.composeCollection(Dg,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",u)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=zo(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&&(!jg.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&&f&&(l.srcToken=t),l}function zo(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Hg.emptyScalarPosition(t,i,r),indent:-1,source:""},d=qu.composeScalar(e,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Bg({options:e},{offset:t,source:i,end:r},n){let a=new Ig.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=Og.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Jo.composeEmptyNode=zo;Jo.composeNode=Wu});var Uu=y(Gu=>{"use strict";var Lg=Ii(),Ju=zu(),Mg=zt(),Fg=Hi();function Vg(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Lg.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Fg.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Ju.composeNode(l,n,f,o):Ju.composeEmptyNode(l,f.end,r,null,f,o);let d=c.contents.range[2],u=Mg.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,d,u.offset],c}Gu.composeDoc=Vg});var Uo=y(Xu=>{"use strict";var qg=Pr("process"),Wg=Ia(),zg=Ii(),Di=Oi(),Ku=x(),Jg=Uu(),Gg=zt();function Bi(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 Yu(e){let t="",i=!1,r=!1;for(let n=0;n{let o=Bi(i);a?this.warnings.push(new Di.YAMLWarning(o,r,n)):this.errors.push(new Di.YAMLParseError(o,r,n))},this.directives=new qg.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Yu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} +`)+(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 Go=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Bi(i);a?this.warnings.push(new Di.YAMLWarning(o,r,n)):this.errors.push(new Di.YAMLParseError(o,r,n))},this.directives=new Wg.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Yu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ku.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ku.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r} ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r} -${o}`:r}}if(i){for(let a=0;a{let a=Bi(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=zg.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 Di.YAMLParseError(Bi(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 Di.YAMLParseError(Bi(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Jg.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} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Di.YAMLParseError(Bi(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 Wg.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}}};Xu.Composer=Go});var ed=y(gn=>{"use strict";var Gg=Vo(),Ug=Wo(),Kg=Oi(),Qu=bi();function Yg(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 Kg.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ug.resolveFlowScalar(e,t,r);case"block-scalar":return Gg.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Xg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Qu.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:` +${o}`:r}}if(i){for(let a=0;a{let a=Bi(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 Di.YAMLParseError(Bi(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 Di.YAMLParseError(Bi(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Gg.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} +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Di.YAMLParseError(Bi(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 zg.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}}};Xu.Composer=Go});var ed=y(gn=>{"use strict";var Ug=Vo(),Kg=Wo(),Yg=Oi(),Qu=bi();function Xg(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 Yg.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Kg.resolveFlowScalar(e,t,r);case"block-scalar":return Ug.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Qg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Qu.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:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),f=s.substring(0,l),d=s.substring(l+1)+` `,u=[{type:"block-scalar-header",offset:a,indent:r,source:f}];return Zu(u,c)||u.push({type:"newline",offset:-1,indent:r,source:` -`}),{type:"block-scalar",offset:a,indent:r,props:u,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function Qg(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Qu.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Zg(e,c);break;case'"':Ko(e,c,"double-quoted-scalar");break;case"'":Ko(e,c,"single-quoted-scalar");break;default:Ko(e,c,"scalar")}}function Zg(e,t){let i=t.indexOf(` +`}),{type:"block-scalar",offset:a,indent:r,props:u,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function Zg(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Qu.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":ew(e,c);break;case'"':Ko(e,c,"double-quoted-scalar");break;case"'":Ko(e,c,"single-quoted-scalar");break;default:Ko(e,c,"scalar")}}function ew(e,t){let i=t.indexOf(` `),r=t.substring(0,i),n=t.substring(i+1)+` `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];Zu(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Zu(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 Ko(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:` -`};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})}}}gn.createScalarToken=Xg;gn.resolveAsScalar=Yg;gn.setScalarValue=Qg});var id=y(td=>{"use strict";var ew=e=>"type"in e?yn(e):wn(e);function yn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=yn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=wn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=wn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=wn(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 wn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=yn(t)),i)for(let a of i)n+=a.source;return r&&(n+=yn(r)),n}td.stringify=ew});var od=y(ad=>{"use strict";var Yo=Symbol("break visit"),tw=Symbol("skip children"),rd=Symbol("remove item");function kt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),nd(Object.freeze([]),e,t)}kt.BREAK=Yo;kt.SKIP=tw;kt.REMOVE=rd;kt.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};kt.parentCollection=(e,t)=>{let i=kt.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 nd(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{"use strict";var Xo=ed(),iw=id(),rw=od(),Qo="\uFEFF",Zo="",es="",ts="",nw=e=>!!e&&"items"in e,aw=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function ow(e){switch(e){case Qo:return"";case Zo:return"";case es:return"";case ts:return"";default:return JSON.stringify(e)}}function sw(e){switch(e){case Qo:return"byte-order-mark";case Zo:return"doc-mode";case es:return"flow-error-end";case ts:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`};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})}}}gn.createScalarToken=Qg;gn.resolveAsScalar=Xg;gn.setScalarValue=Zg});var id=y(td=>{"use strict";var tw=e=>"type"in e?yn(e):wn(e);function yn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=yn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=wn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=wn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=wn(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 wn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=yn(t)),i)for(let a of i)n+=a.source;return r&&(n+=yn(r)),n}td.stringify=tw});var od=y(ad=>{"use strict";var Yo=Symbol("break visit"),iw=Symbol("skip children"),rd=Symbol("remove item");function kt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),nd(Object.freeze([]),e,t)}kt.BREAK=Yo;kt.SKIP=iw;kt.REMOVE=rd;kt.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};kt.parentCollection=(e,t)=>{let i=kt.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 nd(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{"use strict";var Xo=ed(),rw=id(),nw=od(),Qo="\uFEFF",Zo="",es="",ts="",aw=e=>!!e&&"items"in e,ow=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function sw(e){switch(e){case Qo:return"";case Zo:return"";case es:return"";case ts:return"";default:return JSON.stringify(e)}}function cw(e){switch(e){case Qo:return"byte-order-mark";case Zo:return"doc-mode";case es:return"flow-error-end";case ts:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(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}ee.createScalarToken=Xo.createScalarToken;ee.resolveAsScalar=Xo.resolveAsScalar;ee.setScalarValue=Xo.setScalarValue;ee.stringify=iw.stringify;ee.visit=rw.visit;ee.BOM=Qo;ee.DOCUMENT=Zo;ee.FLOW_END=es;ee.SCALAR=ts;ee.isCollection=nw;ee.isScalar=aw;ee.prettyToken=ow;ee.tokenType=sw});var ns=y(cd=>{"use strict";var Li=Nn();function be(e){switch(e){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var sd=new Set("0123456789ABCDEFabcdef"),cw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),bn=new Set(",[]{}"),lw=new Set(` ,[]{} -\r `),is=e=>!e||lw.has(e),rs=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===` +`: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}ee.createScalarToken=Xo.createScalarToken;ee.resolveAsScalar=Xo.resolveAsScalar;ee.setScalarValue=Xo.setScalarValue;ee.stringify=rw.stringify;ee.visit=nw.visit;ee.BOM=Qo;ee.DOCUMENT=Zo;ee.FLOW_END=es;ee.SCALAR=ts;ee.isCollection=aw;ee.isScalar=ow;ee.prettyToken=sw;ee.tokenType=cw});var ns=y(cd=>{"use strict";var Li=Nn();function be(e){switch(e){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var sd=new Set("0123456789ABCDEFabcdef"),lw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),bn=new Set(",[]{}"),uw=new Set(` ,[]{} +\r `),is=e=>!e||uw.has(e),rs=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===` `?!0:i==="\r"?this.buffer[t+1]===` `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===` `||!n&&!this.atEnd)return t+r+1}return i===` @@ -133,24 +133,24 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Li.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(be(a)||t&&bn.has(a))break;i=r}else if(be(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===` `?(r+=1,n=` `,a=this.buffer[r+1]):i=r),a==="#"||t&&bn.has(a))break;if(n===` -`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&bn.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Li.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(is),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(be(r)||i&&bn.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(;!be(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(cw.has(i))i=this.buffer[++t];else if(i==="%"&&sd.has(this.buffer[t+1])&&sd.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` +`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&bn.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Li.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(is),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(be(r)||i&&bn.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(;!be(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(lw.has(i))i=this.buffer[++t];else if(i==="%"&&sd.has(this.buffer[t+1])&&sd.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,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)}};cd.Lexer=rs});var os=y(ld=>{"use strict";var as=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var uw=Pr("process"),ud=Nn(),dw=ns();function lt(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Sn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&fd(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&&dd(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent0&&(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)}};cd.Lexer=rs});var os=y(ld=>{"use strict";var as=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var dw=Pr("process"),ud=Nn(),fw=ns();function lt(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Sn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&fd(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&&dd(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.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;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":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(lt(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(hd(i.key)&&!lt(i.sep,"newline")){let o=Jt(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(lt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Jt(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]}):lt(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&&!lt(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)){Sn(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||lt(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=kn(r),a=Jt(n);fd(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=kn(t),r=Jt(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=kn(t),r=Jt(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())}}};pd.Parser=ss});var yd=y(Fi=>{"use strict";var md=Uo(),fw=Ii(),Mi=Oi(),hw=za(),pw=x(),mw=os(),vd=cs();function gd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new mw.LineCounter||null,prettyErrors:t}}function vw(e,t={}){let{lineCounter:i,prettyErrors:r}=gd(t),n=new vd.Parser(i?.addNewLine),a=new md.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Mi.prettifyError(e,i)),s.warnings.forEach(Mi.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function wd(e,t={}){let{lineCounter:i,prettyErrors:r}=gd(t),n=new vd.Parser(i?.addNewLine),a=new md.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 Mi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Mi.prettifyError(e,i)),o.warnings.forEach(Mi.prettifyError(e,i))),o}function gw(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=wd(e,i);if(!n)return null;if(n.warnings.forEach(a=>hw.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 ww(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 pw.isDocument(e)&&!r?e.toString(i):new fw.Document(e,r,i).toString(i)}Fi.parse=gw;Fi.parseAllDocuments=vw;Fi.parseDocument=wd;Fi.stringify=ww});var Gt=y(C=>{"use strict";var yw=Uo(),Nw=Ii(),bw=Co(),ls=Oi(),kw=vi(),ut=x(),Sw=at(),Ew=L(),Pw=st(),xw=ct(),Rw=Nn(),Cw=ns(),Aw=os(),_w=cs(),En=yd(),Nd=fi();C.Composer=yw.Composer;C.Document=Nw.Document;C.Schema=bw.Schema;C.YAMLError=ls.YAMLError;C.YAMLParseError=ls.YAMLParseError;C.YAMLWarning=ls.YAMLWarning;C.Alias=kw.Alias;C.isAlias=ut.isAlias;C.isCollection=ut.isCollection;C.isDocument=ut.isDocument;C.isMap=ut.isMap;C.isNode=ut.isNode;C.isPair=ut.isPair;C.isScalar=ut.isScalar;C.isSeq=ut.isSeq;C.Pair=Sw.Pair;C.Scalar=Ew.Scalar;C.YAMLMap=Pw.YAMLMap;C.YAMLSeq=xw.YAMLSeq;C.CST=Rw;C.Lexer=Cw.Lexer;C.LineCounter=Aw.LineCounter;C.Parser=_w.Parser;C.parse=En.parse;C.parseAllDocuments=En.parseAllDocuments;C.parseDocument=En.parseDocument;C.stringify=En.stringify;C.visit=Nd.visit;C.visitAsync=Nd.visitAsync});var Os=di(Gt(),1);import{promises as Fd}from"node:fs";import pe from"node:path";import{execFileSync as Tw}from"child_process";import qi from"path";function Vi(e,t){return Tw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Iw(e,t){let i=qi.normalize(e),r=qi.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ue(e){try{let t=qi.resolve(Vi(e,["rev-parse","--show-toplevel"])),r=Vi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?qi.resolve(r.slice(9)):t,a=null;try{a=Vi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Iw(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function bd(e){try{Vi(e,["rev-parse","--is-inside-work-tree"]);let t=Vi(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:qi.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 Pn(e){return bd(e).map(t=>t.root)}import{execFileSync as jw}from"node:child_process";var $w=3e4,Ow=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 Hw(e,t){try{return jw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$w,maxBuffer:Ow,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 ds(e,t){return Hw(e,t).trim()}import{createHash as Mw}from"node:crypto";import{promises as ke}from"node:fs";import de from"node:path";import{TextDecoder as Fw}from"node:util";var Dw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Bw=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Lw(e){return e.toLowerCase().startsWith(".env")}function Wi(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Lw(r))?"environment-file":i.some(r=>Bw.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Dw.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function dt(e){return e!==0&&e!==0n&&e!=="0"}function ae(e,t){return dt(e.dev)&&dt(t.dev)&&dt(e.ino)&&dt(t.ino)}function $(e,t){let i=dt(e.dev)&&dt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=dt(e.ino)&&dt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var Rn=1024*1024;function fs(e,t){let i=de.relative(e,t);return i===""||!de.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${de.sep}`)}function Vw(e){let t=de.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})||de.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=Wi(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 qw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Ww(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xn(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ae(i,r)?$(i,r):$(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kd(e){let t=await ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zw(e,t){let i=de.resolve(e),r=de.resolve(t);if(!fs(i,r))throw new Error("Native artifact path is outside its root");let n=[await kd(i)],a=i;for(let o of de.relative(i,r).split(de.sep).filter(Boolean)){a=de.join(a,o);let s=await kd(a);if(!fs(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Sd(e){for(let t of e){let i=await ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ww(t,i)||await ke.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function V(e){let t=Vw(e.ref),i=e.maxBytes===null?null:qw(e.maxBytes??Rn),r=de.resolve(e.root,...t.split("/")),n=await zw(e.root,de.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await ke.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 ke.realpath(r);if(!fs(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ke.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),ke.lstat(r),ke.realpath(r)]);if(await Sd(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!xn(a,c)||!xn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let N=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,N),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),ke.lstat(r),ke.realpath(r)]);if(await Sd(n),!h.isFile()||h.isSymbolicLink()||v!==o||!xn(c,m)||!xn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,u),w;try{w=new Fw("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:u,hash:e.includeHash===!1?null:Mw("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}import{createHash as Jw}from"crypto";function Se(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Gw(e,t){t.has(e)&&Se("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&Se("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Se("symbol properties are not supported"),`[${e.map(r=>hs(r,t)).join(",")}]`}finally{t.delete(e)}}function Uw(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Se("only plain objects are supported"),t.has(e)&&Se("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Se("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))&&Se("accessor properties are not supported"),`${JSON.stringify(o)}:${hs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function hs(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)||Se("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Gw(e,t):Uw(e,t);case"bigint":case"function":case"symbol":case"undefined":return Se(`${typeof e} values are not supported`)}return Se("unsupported value type")}function ps(e){return hs(e,new Set)}function te(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 Jw("sha256").update(`${e} -${ps(t)}`).digest("hex")}var vs=di(Gt(),1);import Cn from"path";var zi=64*1024,An=1024,_n=64,gs=5,Kw=[".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/**",".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/**"],Yw=["**/.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"],Xw=[...Kw,...Yw].sort((e,t)=>e.localeCompare(t,"en"));var oe={include:["**/*"],exclude:[...Xw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Qw(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Cn.posix.isAbsolute(i)||Cn.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 St(e){let t=Qw(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Pd(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 Tn(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||Cn.posix.isAbsolute(r)||Cn.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 Ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function xd(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 ws(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>An)throw new Error(`${t} exceeds ${An} characters`);let i=0;for(let r=0;r_n)throw new Error(`${t} contains more than ${_n} wildcard tokens`);return e}function Ed(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=>ws(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ms(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 Zw(e){if(e===void 0)return{...oe,include:[...oe.include],exclude:[...oe.exclude]};let t=Ut(e,"native.snapshot");return{include:Ed(t.include,"native.snapshot.include",oe.include),exclude:Ed(t.exclude,"native.snapshot.exclude",oe.exclude),max_files:ms(t.max_files,oe.max_files,"native.snapshot.max_files"),max_total_bytes:ms(t.max_total_bytes,oe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ms(t.max_duration_ms,oe.max_duration_ms,"native.snapshot.max_duration_ms")}}function ey(e){if(e===void 0)return;let t=Ut(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=Ut(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:St(r),toArtifactRoot:St(n),stage:a,...o?{cleanup:o}:{}}}function ty(e,t={}){let i=Ut(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??gs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ey(i.pending_root_move);return{artifact_root:St(r),language:xd(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Zw(i.snapshot),...s?{pending_root_move:s}:{}}}function iy(e){let t=Ut(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:Pd(t.artifact_layout),language:xd(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function ry(e){let i=Ut(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)=>Tn(r,`hook.allow_paths[${n}]`)))]}}function ny(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function ay(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(f=>f!=="native"&&f!=="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 Ji(e,t={}){let i=(0,vs.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=ny(n.ambient_resume),o=n.hook===void 0?void 0:ry(n.hook),s=n.native===void 0?void 0:ty(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:iy(n.classic),l=ay(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 In(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:St(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:gs,snapshot:{...oe,include:[...oe.include],exclude:[...oe.exclude]}}}}import{createHash as sy}from"crypto";import{promises as On}from"fs";import ft from"path";import{constants as jn,promises as Et}from"fs";var Ee=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function ys(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Rd(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Gi(e){return{dev:e.dev,ino:e.ino,birthtime:ys(e)}}function $n(e,t){let i=Gi(e),r=Gi(t);return ae(i,r)?$(i,r):$(i,r)&&ys(e)===ys(t)&&Rd(e)===Rd(t)&&e.size===t.size}async function Kt(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 Et.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ee("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ee("too-large",`${r} exceeds ${t} bytes`);let o=await Et.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Gi(a)});let s=process.platform==="win32"?jn.O_RDONLY:jn.O_RDONLY|jn.O_NOFOLLOW|jn.O_NONBLOCK,c;try{c=await Et.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ee("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Et.lstat(e,{bigint:n}),Et.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!$n(a,l)||!$n(a,f))throw new Ee("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Gi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:N}=await c.read(m,0,Math.min(m.length,w),null);if(N===0)break;if(p+=N,p>t)throw new Ee("too-large",`${r} exceeds ${t} bytes`);u.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),Et.lstat(e,{bigint:n}),Et.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!$n(a,h)||!$n(a,v))throw new Ee("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Gi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function oy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ns(e,t){let i=ft.relative(e,t);return i===""||!ft.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ft.sep}`)}async function Cd(e,t){let i=ft.resolve(e),r=await On.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return On.realpath(i)}async function Ad(e,t,i,r){let n=e;for(let a=0;a{if(!Ns(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Ad(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Ui=".comet/config.yaml";function cy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Hn(e,t={}){return(await Dn(e,t)).document}async function ly(e){try{return(await ht(e,Ui,zi,{label:Ui})).bytes}catch(t){if(cy(t))return null;throw t}}function uy(e){return e?{exists:!0,sha256:sy("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Dn(e,t={}){let i=await ly(e);return{document:i?Ji(i.toString("utf8"),t):null,identity:uy(i)}}async function bs(e){return(await Hn(e))?.config??null}var GP=16*1024;import{randomUUID as my}from"crypto";import{promises as K}from"fs";import Pe from"path";function Ps(e,t){let i=Pe.relative(e,t);return i===""||!Pe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Pe.sep}`)}function vy(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Es(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ae(i,r)?$(i,r):$(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Td(e){let t=await K.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 K.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yi(e){for(let t of e){let i=await K.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!vy(t,i)||await K.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function gy(e,t){let i=Pe.resolve(e),r=Pe.resolve(t);if(!Ps(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Td(i)],a=Pe.relative(i,r).split(Pe.sep).filter(Boolean),o=i;for(let s of a){await Yi(n),o=Pe.join(o,s);try{await K.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Td(o);if(!Ps(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Yi(n),n}async function wy(e){let t;try{t=await K.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 yy(e,t,i={}){let r=Pe.dirname(e),n=i.containedRoot?await gy(i.containedRoot,r):null;n||await K.mkdir(r,{recursive:!0});let a=Pe.join(r,`.${Pe.basename(e)}.${my()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await K.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([K.lstat(a),K.realpath(a)]);if(await Yi(n),!c.isFile()||c.isSymbolicLink()||!Es(s,c)||!Ps(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Es(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await Yi(n);let c=await K.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Es(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await K.link(a,e),await K.unlink(a)):await K.rename(a,e),await wy(r)}catch(c){if(await o?.close(),!n)await K.rm(a,{force:!0});else try{await Yi(n),await K.rm(a,{force:!0})}catch{}throw c}}async function xe(e,t,i={}){await yy(e,t,i)}async function fe(e,t,i={}){await xe(e,JSON.stringify(t,null,2)+` -`,i)}import{existsSync as Id,promises as Pt}from"fs";import A from"path";import Ny from"os";var Bn=".comet/config.yaml",by=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function xs(e){try{return await Pt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ky(e){try{let t=await Pt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Qt(e,t){let i=A.relative(e,t);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function Xt(e){let t=[],i=e;for(;!await xs(i);){let n=A.dirname(i);if(n===i)break;t.push(A.basename(i)),i=n}let r=await Pt.realpath(i);return A.resolve(r,...t.reverse())}async function Rs(e){try{return(await Pt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ln(e){let t=A.resolve(e);try{(await Pt.stat(t)).isDirectory()||(t=A.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=A.resolve(Ny.homedir());for(;;){if(!(t===r&&i!==r)){let o=A.join(t,...Bn.split("/")),s=t===i||await ky(o);if(await xs(o)&&s)return t}if(await xs(A.join(t,".git")))return t;let a=A.dirname(t);if(a===t)return i;t=a}}function Mn(e){return St(e)}async function Sy(e,t){let i=Mn(t),r=A.resolve(e,...i.split("/")),n=await Pt.realpath(e),a=await Xt(r);if(!Qt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function xt(e,t){let i=Mn(t),r=await Sy(e,i),n=A.join(r,"comet");if(await Rs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Xt(r),Xt(n)]);if(!Qt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=A.resolve(e),c=A.join(s,".comet","runtime","native");if(await Rs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Pt.realpath(s),Xt(c)]);if(!Qt(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(e,...Bn.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:A.join(n,"specs"),changesDir:A.join(n,"changes"),archiveDir:A.join(n,"archive"),runtimeDir:c,changesRuntimeDir:A.join(c,"changes"),locksDir:A.join(c,"locks"),transactionsDir:A.join(c,"transactions")}}function jd(e){if(!by.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ue(e,t){jd(t);let i=A.join(e.changesRuntimeDir,t);if(!X(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Cs(e,t){jd(t);let i=A.join(e.changesDir,t,"runtime");if(!X(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function Oe(e,t){let i=Ue(e,t);if(Id(i))return i;let r=Cs(e,t);return Id(r)?r:i}function He(e,t){let i=A.resolve(t);if(X(e.runtimeDir,i))return e.runtimeDir;if(X(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function X(e,t){return Qt(A.resolve(e),A.resolve(t))}async function B(e,t){let i=A.resolve(e),r=A.resolve(t);if(!Qt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Rs(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Xt(i),Xt(r)]);if(!Qt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function Py(e="docs",t="en"){return In(e,t)}async function De(e){let t=(await Hn(e))?.config??null;return t?.native?t:null}async function Fn(e){let t=await De(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 $d(e){let t=await Ln(e.startPath),i=await De(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Bn} 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?Mn(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??Py(r??"docs"),a=await xt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}var Wn=di(Gt(),1);import{promises as xy}from"node:fs";var Zt="comet.native.v4",Xi="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 Ry=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Cy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ay=/^A[1-9][0-9]*$/u,_y=/^[a-f0-9]{64}$/u,Ty=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"]),qn=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 ie(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function re(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 G(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:G(e,t)}function Iy(e,t){let i=G(e,t);if(!_y.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ei(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function D(e,t,i=0){if(!Number.isSafeInteger(e)||ei(r,n))}function zn(e,t){return Be(e,t,(i,r)=>G(i,`${t}[${r}]`))}function Rt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ti(e,t){let i=G(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=G(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 Re(e,t){let i=ie(e,t);return re(i,new Set(["text","truncated"]),t),{text:G(i.text,`${t}.text`,{empty:!0}),truncated:ei(i.truncated,`${t}.truncated`)}}function $y(e,t){let i=`Native spec_changes[${t}]`,r=ie(e,i);re(r,new Set(["capability","operation","source"]),i);let n=G(r.capability,`${i}.capability`);if(!Cy.test(n))throw new Error(`${i}.capability is invalid`);let a=J(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 Oy(e){let t="Native workspace",i=ie(e,t);re(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=J(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:J(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 Hy(e){let t="Native loop",i=ie(e,t);re(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=zn(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Rt(r,`${t}.previous_unresolved_ids`),{stage:J(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:D(i.goal_cycle,`${t}.goal_cycle`,1),iteration:D(i.iteration,`${t}.iteration`),attempt:D(i.attempt,`${t}.attempt`),retry_epoch:D(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:D(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:D(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:D(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ts(i.next_action,`${t}.next_action`)}}function Dy(e,t){let i=`Native acceptance[${t}]`,r=ie(e,i);re(r,new Set(["id","source","text","result","reason"]),i);let n=G(r.id,`${i}.id`);if(!Ay.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Is(r.source,`${i}.source`),text:G(r.text,`${i}.text`),result:J(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Re(r.reason,`${i}.reason`)}}function By(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ie(e,i);return re(r,new Set(["name","result","note"]),i),{name:Re(r.name,`${i}.name`),result:J(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Re(r.note,`${i}.note`)}}function Ly(e){let t="Native builder_handoff",i=ie(e,t);re(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=zn(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Rt(r,`${t}.addressed_acceptance_ids`),{candidate_id:G(i.candidate_id,`${t}.candidate_id`),identity_provider:G(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:G(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:D(i.iteration,`${t}.iteration`,1),summary:Re(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Be(i.checks,`${t}.checks`,By),checks_truncated:ei(i.checks_truncated,`${t}.checks_truncated`),known_limits:Be(i.known_limits,`${t}.known_limits`,(n,a)=>Re(n,`${t}.known_limits[${a}]`)),known_limits_truncated:ei(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:ti(i.submitted_at,`${t}.submitted_at`)}}function My(e,t){let i=`Native blockers[${t}]`,r=ie(e,i);re(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=zn(r.acceptance_ids,`${i}.acceptance_ids`);return Rt(n,`${i}.acceptance_ids`),{owner:J(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Re(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:J(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Fy(e,t){let i=`Native verification.checks[${t}]`,r=ie(e,i);return re(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:G(r.id,`${i}.id`),name:Re(r.name,`${i}.name`),argv_display:Be(r.argv_display,`${i}.argv_display`,(n,a)=>Re(n,`${i}.argv_display[${a}]`)),argv_truncated:ei(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Is(r.cwd_ref,`${i}.cwd_ref`,!0),status:J(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:jy(r.exit_code,`${i}.exit_code`),duration_ms:D(r.duration_ms,`${i}.duration_ms`)}}function Vy(e){let t="Native verification",i=ie(e,t);re(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Be(i.checks,`${t}.checks`,Fy);Rt(r.map(a=>a.id),`${t}.checks IDs`);let n=G(i.identity_provider,`${t}.identity_provider`);return{candidate_id:G(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:G(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:D(i.iteration,`${t}.iteration`,1),attempt:D(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":J(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:J(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Re(i.summary,`${t}.summary`),risks:Be(i.risks,`${t}.risks`,(a,o)=>Re(a,`${t}.risks[${o}]`)),risks_truncated:ei(i.risks_truncated,`${t}.risks_truncated`),completed_at:ti(i.completed_at,`${t}.completed_at`)}}function Od(e,t){let i=`Native history[${t}]`,r=ie(e,i);re(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=zn(r.unresolved_ids,`${i}.unresolved_ids`);return Rt(n,`${i}.unresolved_ids`),{goal_cycle:D(r.goal_cycle,`${i}.goal_cycle`,1),iteration:D(r.iteration,`${i}.iteration`),attempt:D(r.attempt,`${i}.attempt`),outcome:J(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Re(r.summary,`${i}.summary`),completed_at:ti(r.completed_at,`${i}.completed_at`)}}function qy(e){let t="Native history_overflow.outcome_counts",i=ie(e,t),r=["pass","fail","blocked","execution-error","recovery"];return re(i,new Set(r),t),{pass:D(i.pass,`${t}.pass`),fail:D(i.fail,`${t}.fail`),blocked:D(i.blocked,`${t}.blocked`),"execution-error":D(i["execution-error"],`${t}.execution-error`),recovery:D(i.recovery,`${t}.recovery`)}}function Wy(e){let t="Native history_overflow",i=ie(e,t);re(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=D(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:ti(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:ti(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=qy(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 zy(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 Jy(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 P(e){let t=ie(e,"Native portable state");if(re(t,Ty,"Native portable state"),t.schema!==Zt)throw new Error(`Native portable state schema must be ${Zt}`);let i=G(t.name,"Native state name");if(!Ry.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=Be(t.spec_changes,"Native spec_changes",$y);Rt(r.map(s=>s.capability),"Native spec change capabilities");let n=Be(t.acceptance,"Native acceptance",Dy);Rt(n.map(s=>s.id),"Native acceptance IDs");let a=Be(t.history,"Native history",Od);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Zt,name:i,language:J(t.language,["en","zh-CN"],"Native state language"),phase:J(t.phase,["shape","build","verify","archive"],"Native state phase"),status:J(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:D(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Iy(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Oy(t.workspace),loop:Hy(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ly(t.builder_handoff),blockers:Be(t.blockers,"Native blockers",My),verification:t.verification===null?null:Vy(t.verification),history:a,history_overflow:Wy(t.history_overflow),verification_result:J(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:J(t.verification_report,["verification.md"],"Native verification_report"),archived:ei(t.archived,"Native archived"),created_at:ti(t.created_at,"Native created_at")};return zy(o),Jy(o),o}function he(e,t){let i=P(e),r=Od(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 P({...i,history:n,history_overflow:a})}function Gy(e,t){let i=(0,Wn.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 Ce(e){let t=await xy.readFile(e,"utf8");return P(Gy(t,"Native portable state"))}async function Jn(e,t,i={}){let r=P(t);await xe(e,(0,Wn.stringify)(r),i)}var Vn=new Map;async function Uy(e,t){let i=Vn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Vn.set(e,a),await i;try{return await t()}finally{r(),Vn.get(e)===a&&Vn.delete(e)}}async function Qi(e){return Uy(e.file,async()=>{let t=D(e.expectedStateVersion,"Native expected state version",1),i=P(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ce(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new qn(t,r.state_version);return await Jn(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ce(e.file);if(n.state_version!==t)throw new qn(t,n.state_version)}}),i})}var Hd="children.yaml",js="comet.native.children.v1",Ky=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Yy=new Set(["schema","children"]),Xy=new Set(["name","depends_on","covers"]);function Dd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bd(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 Ld(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 $s(e,t){let i=pe.normalize(pe.resolve(e)),r=pe.normalize(pe.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Qy(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 Zy(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function eN(e,t){let i=(0,Os.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Dd(i.toJS({mapAsMap:!1}),"Native children contract");if(Bd(r,Yy,"Native children contract"),r.schema!==js)throw new Error(`Native children schema must be ${js}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Dd(s,`Native child ${c}`);if(Bd(l,Xy,`Native child ${c}`),typeof l.name!="string"||!Ky.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:Ld(l.depends_on,`Native child ${l.name} depends_on`),covers:Ld(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return Qy(n),t&&Zy(n,t),{schema:js,children:n}}async function Zi(e){let t=pe.join(e.changeDir,Hd);try{await Fd.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await V({root:e.changeDir,ref:Hd});return{contract:eN(i.text,e.acceptanceIds),size:i.size}}function Gn(e){return te("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function tN(e){let t=Pn(e.projectRoot);t.some(r=>$s(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>pe.resolve(n)))]){let n=await De(r);n&&i.push({projectRoot:r,paths:await xt(r,n.native.artifact_root),parent:$s(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function iN(e,t){let i=pe.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ce(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function rN(e,t){let i;try{i=await Fd.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=pe.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ce(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function nN(e,t,i){let r=pe.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${pe.sep}`))return null;let n=r.split(pe.sep).join("/");try{let a=(0,Os.parseDocument)(ds(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:P(a.toJS({mapAsMap:!1}))}catch{return null}}function aN(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Md(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ct(e){let t=pe.join(e.paths.changesDir,e.state.name),i=await Zi({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=Gn({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await tN(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:h})=>h)),c=new Map,l=new Map;for(let h of a){let v=h.parent&&o?`refs/heads/${o}`:"HEAD";for(let g of await rN(h,s)){let w={...g,source:h,committedState:nN(h,g.file,v)};c.set(g.state.name,[...c.get(g.state.name)??[],w])}for(let g of s){let w=await iN(h,g);w&&l.set(g,[...l.get(g)??[],{source:h,state:w}])}}let f=new Map;for(let h of i.contract.children){let v=(c.get(h.name)??[]).find(({source:N,committedState:k})=>N.parent&&k?.name===h.name&&Md(k,o));if(v){f.set(h.name,{kind:"done",phase:v.state.phase,projectRoot:v.source.projectRoot,message:null});continue}let g=c.get(h.name)?.[0];if(g){f.set(h.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=l.get(h.name)??[];w.length>1?f.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):w[0]&&f.set(h.name,aN(w[0].state,w[0].source,o))}let d=new Map(i.contract.children.map(h=>[h.name,h])),u=new Map,p=h=>{let v=u.get(h);if(v)return v;let g=d.get(h),N=g.depends_on.map(p).every(({status:O})=>O==="done"),k=f.get(h),E=k?.kind==="active"&&N?g.depends_on.filter(O=>!(c.get(O)??[]).some(({source:Ie,committedState:ze})=>$s(Ie.projectRoot,k.projectRoot)&&ze?.name===O&&Md(ze,o))):[],S,R=k?.message??null;k?.kind==="done"?(S=N?"done":"blocked",N||(R=`Native child ${h} was merged before its dependencies`)):k?.kind==="active"?(S=N&&E.length===0?"active":"blocked",N?E.length>0&&(R=`Native child ${h} does not include merged dependencies: ${E.join(", ")}`):R=`Native child ${h} started before its dependencies merged`):k?.kind==="blocked"?S="blocked":(S=n&&N?"ready":"pending",n||(R="Parent Shape confirmation is required"));let b={name:h,dependsOn:[...g.depends_on],covers:[...g.covers],status:S,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:R};return u.set(h,b),b},m=i.contract.children.map(({name:h})=>p(h));return{contractHash:r,confirmed:n,parentBranch:o,children:m,readyChildren:m.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:m.every(({status:h})=>h==="done")}}function me(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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 Wk}from"node:crypto";import{promises as br}from"node:fs";import zk from"node:path";var nc=di(Gt(),1);import ni from"path";import{promises as lb}from"fs";import ub from"path";import{AsyncLocalStorage as oN}from"async_hooks";import{randomUUID as Wd}from"crypto";import{promises as ve}from"fs";import zd from"os";import Q from"path";var Vd=16*1024,Jd=".coordinator",sN=5e3,qd=new oN,Un=new Map;function cN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function lN(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 Gd(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 Hs(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ae(i,r)?$(i,r):$(i,r)&&e.size===t.size}function Ds(e,t){return Hs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ke(e){let t,i;try{let r=await Kt(e,Vd,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Ee?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${Vd} 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:lN(JSON.parse(t.toString("utf8")),e),identity:Gd(i)}}async function uN(e){return(await Ke(e))?.owner??null}function Ud(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==zd.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dN(e,t){try{await ve.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ve.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Bs(e,t){let i=await Ke(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ds(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ve.mkdir(t,{recursive:!0});let r=Q.join(t,`${Q.basename(e.file)}.${e.owner.id}.${Wd()}.removed`);try{await ve.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ke(r);if(!n||n.owner.id!==e.owner.id||!Hs(n.identity,e.identity))throw await dN(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ve.rm(r,{force:!0}),"removed"}function Kd(e){return{id:Wd(),pid:process.pid,hostname:zd.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Yd(e,t){let i;try{i=await ve.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await uN(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)+` -`,"utf8"),await i.sync(),Gd(await i.stat({bigint:!0}))}finally{await i.close()}}async function fN(e,t){let i=await B(e.runtimeDir,e.locksDir);await ve.mkdir(i,{recursive:!0});let r=await B(e.runtimeDir,Q.join(i,Jd));await ve.mkdir(r,{recursive:!0});let n=Kd(t),a=Q.join(r,`.${n.id}.tmp`),o=Q.join(r,`${n.id}.claim`);try{let s=await Yd(a,n);await ve.rename(a,o);let c=await Ke(o);if(!c||!Hs(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 ve.rm(a,{force:!0})}}async function hN(e){let t=Q.dirname(e.file),i=!1,r=Q.basename(e.file);for(let n of await ve.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Q.join(t,n.name);if(Q.resolve(a)!==Q.resolve(e.file))try{let o=await Ke(a),s=Ud(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bs(o,t);continue}n.name=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 mN(e){let t=Un.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Un.set(e,n),await t,()=>{i(),Un.get(e)===n&&Un.delete(e)}}async function Qd(e,t,i){let r=Q.resolve(e.locksDir),n=qd.getStore();if(n?.has(r))return i();let a=await mN(r);try{let o=await pN(e,t),s=new Map(n??[]);return s.set(r,o),await qd.run(s,async()=>{try{return await i()}finally{await Xd(o)}})}finally{a()}}async function Kn(e,t,i){return Qd(e,`acquire ${t}`,async()=>{let r=await B(e.runtimeDir,e.locksDir);await ve.mkdir(r,{recursive:!0});let n=await B(e.runtimeDir,Q.join(r,cN(t))),a=Kd(i),o=await Yd(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Yn(e){await Ke(e.file)&&await Qd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Q.basename(e.file)}`,async()=>{let t=await Ke(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ds(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=Q.join(e.locksDir,Jd);await Bs(t,i)})}function vN(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Zd(e){return Ud(await Ke(e))}import Gs from"node:path";import kN from"node:path";import tf from"node:path";var gN="comet.native.acceptance.v1";var zx=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ir=Object.freeze({maxCriteria:1024});function Ms(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 Ls(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 ef(e){return e.includes("-->")||e.includes("--!>")}function*er(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` +`,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=kn(t),r=Jt(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=kn(t),r=Jt(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())}}};pd.Parser=ss});var yd=y(Fi=>{"use strict";var md=Uo(),hw=Ii(),Mi=Oi(),pw=za(),mw=x(),vw=os(),vd=cs();function gd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new vw.LineCounter||null,prettyErrors:t}}function gw(e,t={}){let{lineCounter:i,prettyErrors:r}=gd(t),n=new vd.Parser(i?.addNewLine),a=new md.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Mi.prettifyError(e,i)),s.warnings.forEach(Mi.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function wd(e,t={}){let{lineCounter:i,prettyErrors:r}=gd(t),n=new vd.Parser(i?.addNewLine),a=new md.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 Mi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Mi.prettifyError(e,i)),o.warnings.forEach(Mi.prettifyError(e,i))),o}function ww(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=wd(e,i);if(!n)return null;if(n.warnings.forEach(a=>pw.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 yw(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 mw.isDocument(e)&&!r?e.toString(i):new hw.Document(e,r,i).toString(i)}Fi.parse=ww;Fi.parseAllDocuments=gw;Fi.parseDocument=wd;Fi.stringify=yw});var Gt=y(C=>{"use strict";var Nw=Uo(),bw=Ii(),kw=Co(),ls=Oi(),Sw=vi(),ut=x(),Ew=at(),Pw=L(),xw=st(),Rw=ct(),Cw=Nn(),Aw=ns(),_w=os(),Tw=cs(),En=yd(),Nd=fi();C.Composer=Nw.Composer;C.Document=bw.Document;C.Schema=kw.Schema;C.YAMLError=ls.YAMLError;C.YAMLParseError=ls.YAMLParseError;C.YAMLWarning=ls.YAMLWarning;C.Alias=Sw.Alias;C.isAlias=ut.isAlias;C.isCollection=ut.isCollection;C.isDocument=ut.isDocument;C.isMap=ut.isMap;C.isNode=ut.isNode;C.isPair=ut.isPair;C.isScalar=ut.isScalar;C.isSeq=ut.isSeq;C.Pair=Ew.Pair;C.Scalar=Pw.Scalar;C.YAMLMap=xw.YAMLMap;C.YAMLSeq=Rw.YAMLSeq;C.CST=Cw;C.Lexer=Aw.Lexer;C.LineCounter=_w.LineCounter;C.Parser=Tw.Parser;C.parse=En.parse;C.parseAllDocuments=En.parseAllDocuments;C.parseDocument=En.parseDocument;C.stringify=En.stringify;C.visit=Nd.visit;C.visitAsync=Nd.visitAsync});var Os=di(Gt(),1);import{promises as Fd}from"node:fs";import pe from"node:path";import{execFileSync as Iw}from"child_process";import qi from"path";function Vi(e,t){return Iw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function jw(e,t){let i=qi.normalize(e),r=qi.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ue(e){try{let t=qi.resolve(Vi(e,["rev-parse","--show-toplevel"])),r=Vi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?qi.resolve(r.slice(9)):t,a=null;try{a=Vi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!jw(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function bd(e){try{Vi(e,["rev-parse","--is-inside-work-tree"]);let t=Vi(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:qi.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 Pn(e){return bd(e).map(t=>t.root)}import{execFileSync as $w}from"node:child_process";var Ow=3e4,Hw=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 Dw(e,t){try{return $w("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Ow,maxBuffer:Hw,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 ds(e,t){return Dw(e,t).trim()}import{createHash as Fw}from"node:crypto";import{promises as ke}from"node:fs";import de from"node:path";import{TextDecoder as Vw}from"node:util";var Bw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Lw=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Mw(e){return e.toLowerCase().startsWith(".env")}function Wi(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Mw(r))?"environment-file":i.some(r=>Lw.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Bw.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function dt(e){return e!==0&&e!==0n&&e!=="0"}function ae(e,t){return dt(e.dev)&&dt(t.dev)&&dt(e.ino)&&dt(t.ino)}function $(e,t){let i=dt(e.dev)&&dt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=dt(e.ino)&&dt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var Rn=1024*1024;function fs(e,t){let i=de.relative(e,t);return i===""||!de.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${de.sep}`)}function qw(e){let t=de.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})||de.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=Wi(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 Ww(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function zw(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xn(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ae(i,r)?$(i,r):$(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kd(e){let t=await ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Jw(e,t){let i=de.resolve(e),r=de.resolve(t);if(!fs(i,r))throw new Error("Native artifact path is outside its root");let n=[await kd(i)],a=i;for(let o of de.relative(i,r).split(de.sep).filter(Boolean)){a=de.join(a,o);let s=await kd(a);if(!fs(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Sd(e){for(let t of e){let i=await ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!zw(t,i)||await ke.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function V(e){let t=qw(e.ref),i=e.maxBytes===null?null:Ww(e.maxBytes??Rn),r=de.resolve(e.root,...t.split("/")),n=await Jw(e.root,de.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await ke.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 ke.realpath(r);if(!fs(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ke.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),ke.lstat(r),ke.realpath(r)]);if(await Sd(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!xn(a,c)||!xn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let N=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,N),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),ke.lstat(r),ke.realpath(r)]);if(await Sd(n),!h.isFile()||h.isSymbolicLink()||v!==o||!xn(c,m)||!xn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,u),w;try{w=new Vw("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:u,hash:e.includeHash===!1?null:Fw("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}import{createHash as Gw}from"crypto";function Se(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Uw(e,t){t.has(e)&&Se("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&Se("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Se("symbol properties are not supported"),`[${e.map(r=>hs(r,t)).join(",")}]`}finally{t.delete(e)}}function Kw(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Se("only plain objects are supported"),t.has(e)&&Se("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Se("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))&&Se("accessor properties are not supported"),`${JSON.stringify(o)}:${hs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function hs(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)||Se("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Uw(e,t):Kw(e,t);case"bigint":case"function":case"symbol":case"undefined":return Se(`${typeof e} values are not supported`)}return Se("unsupported value type")}function ps(e){return hs(e,new Set)}function te(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 Gw("sha256").update(`${e} +${ps(t)}`).digest("hex")}var vs=di(Gt(),1);import Cn from"path";var zi=64*1024,An=1024,_n=64,gs=5,Yw=[".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/**",".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/**"],Xw=["**/.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"],Qw=[...Yw,...Xw].sort((e,t)=>e.localeCompare(t,"en"));var oe={include:["**/*"],exclude:[...Qw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Zw(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Cn.posix.isAbsolute(i)||Cn.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 St(e){let t=Zw(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Pd(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 Tn(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||Cn.posix.isAbsolute(r)||Cn.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 Ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function xd(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 ws(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>An)throw new Error(`${t} exceeds ${An} characters`);let i=0;for(let r=0;r_n)throw new Error(`${t} contains more than ${_n} wildcard tokens`);return e}function Ed(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=>ws(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ms(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 ey(e){if(e===void 0)return{...oe,include:[...oe.include],exclude:[...oe.exclude]};let t=Ut(e,"native.snapshot");return{include:Ed(t.include,"native.snapshot.include",oe.include),exclude:Ed(t.exclude,"native.snapshot.exclude",oe.exclude),max_files:ms(t.max_files,oe.max_files,"native.snapshot.max_files"),max_total_bytes:ms(t.max_total_bytes,oe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ms(t.max_duration_ms,oe.max_duration_ms,"native.snapshot.max_duration_ms")}}function ty(e){if(e===void 0)return;let t=Ut(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=Ut(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:St(r),toArtifactRoot:St(n),stage:a,...o?{cleanup:o}:{}}}function iy(e,t={}){let i=Ut(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??gs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ty(i.pending_root_move);return{artifact_root:St(r),language:xd(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:ey(i.snapshot),...s?{pending_root_move:s}:{}}}function ry(e){let t=Ut(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:Pd(t.artifact_layout),language:xd(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function ny(e){let i=Ut(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)=>Tn(r,`hook.allow_paths[${n}]`)))]}}function ay(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function oy(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(f=>f!=="native"&&f!=="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 Ji(e,t={}){let i=(0,vs.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=ay(n.ambient_resume),o=n.hook===void 0?void 0:ny(n.hook),s=n.native===void 0?void 0:iy(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:ry(n.classic),l=oy(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 In(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:St(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:gs,snapshot:{...oe,include:[...oe.include],exclude:[...oe.exclude]}}}}import{createHash as cy}from"crypto";import{promises as On}from"fs";import ft from"path";import{constants as jn,promises as Et}from"fs";var Ee=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function ys(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Rd(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Gi(e){return{dev:e.dev,ino:e.ino,birthtime:ys(e)}}function $n(e,t){let i=Gi(e),r=Gi(t);return ae(i,r)?$(i,r):$(i,r)&&ys(e)===ys(t)&&Rd(e)===Rd(t)&&e.size===t.size}async function Kt(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 Et.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ee("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ee("too-large",`${r} exceeds ${t} bytes`);let o=await Et.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Gi(a)});let s=process.platform==="win32"?jn.O_RDONLY:jn.O_RDONLY|jn.O_NOFOLLOW|jn.O_NONBLOCK,c;try{c=await Et.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ee("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Et.lstat(e,{bigint:n}),Et.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!$n(a,l)||!$n(a,f))throw new Ee("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Gi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:N}=await c.read(m,0,Math.min(m.length,w),null);if(N===0)break;if(p+=N,p>t)throw new Ee("too-large",`${r} exceeds ${t} bytes`);u.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),Et.lstat(e,{bigint:n}),Et.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!$n(a,h)||!$n(a,v))throw new Ee("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Gi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function sy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ns(e,t){let i=ft.relative(e,t);return i===""||!ft.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ft.sep}`)}async function Cd(e,t){let i=ft.resolve(e),r=await On.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return On.realpath(i)}async function Ad(e,t,i,r){let n=e;for(let a=0;a{if(!Ns(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Ad(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Ui=".comet/config.yaml";function ly(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Hn(e,t={}){return(await Dn(e,t)).document}async function uy(e){try{return(await ht(e,Ui,zi,{label:Ui})).bytes}catch(t){if(ly(t))return null;throw t}}function dy(e){return e?{exists:!0,sha256:cy("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Dn(e,t={}){let i=await uy(e);return{document:i?Ji(i.toString("utf8"),t):null,identity:dy(i)}}async function bs(e){return(await Hn(e))?.config??null}var UP=16*1024;import{randomUUID as vy}from"crypto";import{promises as K}from"fs";import Pe from"path";function Ps(e,t){let i=Pe.relative(e,t);return i===""||!Pe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Pe.sep}`)}function gy(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Es(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ae(i,r)?$(i,r):$(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Td(e){let t=await K.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 K.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yi(e){for(let t of e){let i=await K.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!gy(t,i)||await K.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function wy(e,t){let i=Pe.resolve(e),r=Pe.resolve(t);if(!Ps(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Td(i)],a=Pe.relative(i,r).split(Pe.sep).filter(Boolean),o=i;for(let s of a){await Yi(n),o=Pe.join(o,s);try{await K.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Td(o);if(!Ps(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Yi(n),n}async function yy(e){let t;try{t=await K.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 Ny(e,t,i={}){let r=Pe.dirname(e),n=i.containedRoot?await wy(i.containedRoot,r):null;n||await K.mkdir(r,{recursive:!0});let a=Pe.join(r,`.${Pe.basename(e)}.${vy()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await K.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([K.lstat(a),K.realpath(a)]);if(await Yi(n),!c.isFile()||c.isSymbolicLink()||!Es(s,c)||!Ps(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Es(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await Yi(n);let c=await K.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Es(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await K.link(a,e),await K.unlink(a)):await K.rename(a,e),await yy(r)}catch(c){if(await o?.close(),!n)await K.rm(a,{force:!0});else try{await Yi(n),await K.rm(a,{force:!0})}catch{}throw c}}async function xe(e,t,i={}){await Ny(e,t,i)}async function fe(e,t,i={}){await xe(e,JSON.stringify(t,null,2)+` +`,i)}import{existsSync as Id,promises as Pt}from"fs";import A from"path";import by from"os";var Bn=".comet/config.yaml",ky=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function xs(e){try{return await Pt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Sy(e){try{let t=await Pt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Qt(e,t){let i=A.relative(e,t);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function Xt(e){let t=[],i=e;for(;!await xs(i);){let n=A.dirname(i);if(n===i)break;t.push(A.basename(i)),i=n}let r=await Pt.realpath(i);return A.resolve(r,...t.reverse())}async function Rs(e){try{return(await Pt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ln(e){let t=A.resolve(e);try{(await Pt.stat(t)).isDirectory()||(t=A.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=A.resolve(by.homedir());for(;;){if(!(t===r&&i!==r)){let o=A.join(t,...Bn.split("/")),s=t===i||await Sy(o);if(await xs(o)&&s)return t}if(await xs(A.join(t,".git")))return t;let a=A.dirname(t);if(a===t)return i;t=a}}function Mn(e){return St(e)}async function Ey(e,t){let i=Mn(t),r=A.resolve(e,...i.split("/")),n=await Pt.realpath(e),a=await Xt(r);if(!Qt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function xt(e,t){let i=Mn(t),r=await Ey(e,i),n=A.join(r,"comet");if(await Rs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Xt(r),Xt(n)]);if(!Qt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=A.resolve(e),c=A.join(s,".comet","runtime","native");if(await Rs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Pt.realpath(s),Xt(c)]);if(!Qt(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(e,...Bn.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:A.join(n,"specs"),changesDir:A.join(n,"changes"),archiveDir:A.join(n,"archive"),runtimeDir:c,changesRuntimeDir:A.join(c,"changes"),locksDir:A.join(c,"locks"),transactionsDir:A.join(c,"transactions")}}function jd(e){if(!ky.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ue(e,t){jd(t);let i=A.join(e.changesRuntimeDir,t);if(!X(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Cs(e,t){jd(t);let i=A.join(e.changesDir,t,"runtime");if(!X(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function Oe(e,t){let i=Ue(e,t);if(Id(i))return i;let r=Cs(e,t);return Id(r)?r:i}function He(e,t){let i=A.resolve(t);if(X(e.runtimeDir,i))return e.runtimeDir;if(X(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function X(e,t){return Qt(A.resolve(e),A.resolve(t))}async function B(e,t){let i=A.resolve(e),r=A.resolve(t);if(!Qt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Rs(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Xt(i),Xt(r)]);if(!Qt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function xy(e="docs",t="en"){return In(e,t)}async function De(e){let t=(await Hn(e))?.config??null;return t?.native?t:null}async function Fn(e){let t=await De(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 $d(e){let t=await Ln(e.startPath),i=await De(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Bn} 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?Mn(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??xy(r??"docs"),a=await xt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}var Wn=di(Gt(),1);import{promises as Ry}from"node:fs";var Zt="comet.native.v4",Xi="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 Cy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ay=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_y=/^A[1-9][0-9]*$/u,Ty=/^[a-f0-9]{64}$/u,Iy=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"]),qn=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 ie(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function re(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 G(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:G(e,t)}function jy(e,t){let i=G(e,t);if(!Ty.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ei(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function D(e,t,i=0){if(!Number.isSafeInteger(e)||ei(r,n))}function zn(e,t){return Be(e,t,(i,r)=>G(i,`${t}[${r}]`))}function Rt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ti(e,t){let i=G(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=G(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 Re(e,t){let i=ie(e,t);return re(i,new Set(["text","truncated"]),t),{text:G(i.text,`${t}.text`,{empty:!0}),truncated:ei(i.truncated,`${t}.truncated`)}}function Oy(e,t){let i=`Native spec_changes[${t}]`,r=ie(e,i);re(r,new Set(["capability","operation","source"]),i);let n=G(r.capability,`${i}.capability`);if(!Ay.test(n))throw new Error(`${i}.capability is invalid`);let a=J(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 Hy(e){let t="Native workspace",i=ie(e,t);re(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=J(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:J(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 Dy(e){let t="Native loop",i=ie(e,t);re(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=zn(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Rt(r,`${t}.previous_unresolved_ids`),{stage:J(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:D(i.goal_cycle,`${t}.goal_cycle`,1),iteration:D(i.iteration,`${t}.iteration`),attempt:D(i.attempt,`${t}.attempt`),retry_epoch:D(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:D(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:D(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:D(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ts(i.next_action,`${t}.next_action`)}}function By(e,t){let i=`Native acceptance[${t}]`,r=ie(e,i);re(r,new Set(["id","source","text","result","reason"]),i);let n=G(r.id,`${i}.id`);if(!_y.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Is(r.source,`${i}.source`),text:G(r.text,`${i}.text`),result:J(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Re(r.reason,`${i}.reason`)}}function Ly(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ie(e,i);return re(r,new Set(["name","result","note"]),i),{name:Re(r.name,`${i}.name`),result:J(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Re(r.note,`${i}.note`)}}function My(e){let t="Native builder_handoff",i=ie(e,t);re(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=zn(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Rt(r,`${t}.addressed_acceptance_ids`),{candidate_id:G(i.candidate_id,`${t}.candidate_id`),identity_provider:G(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:G(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:D(i.iteration,`${t}.iteration`,1),summary:Re(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Be(i.checks,`${t}.checks`,Ly),checks_truncated:ei(i.checks_truncated,`${t}.checks_truncated`),known_limits:Be(i.known_limits,`${t}.known_limits`,(n,a)=>Re(n,`${t}.known_limits[${a}]`)),known_limits_truncated:ei(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:ti(i.submitted_at,`${t}.submitted_at`)}}function Fy(e,t){let i=`Native blockers[${t}]`,r=ie(e,i);re(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=zn(r.acceptance_ids,`${i}.acceptance_ids`);return Rt(n,`${i}.acceptance_ids`),{owner:J(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Re(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:J(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Vy(e,t){let i=`Native verification.checks[${t}]`,r=ie(e,i);return re(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:G(r.id,`${i}.id`),name:Re(r.name,`${i}.name`),argv_display:Be(r.argv_display,`${i}.argv_display`,(n,a)=>Re(n,`${i}.argv_display[${a}]`)),argv_truncated:ei(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Is(r.cwd_ref,`${i}.cwd_ref`,!0),status:J(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:$y(r.exit_code,`${i}.exit_code`),duration_ms:D(r.duration_ms,`${i}.duration_ms`)}}function qy(e){let t="Native verification",i=ie(e,t);re(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Be(i.checks,`${t}.checks`,Vy);Rt(r.map(a=>a.id),`${t}.checks IDs`);let n=G(i.identity_provider,`${t}.identity_provider`);return{candidate_id:G(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:G(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:D(i.iteration,`${t}.iteration`,1),attempt:D(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":J(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:J(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Re(i.summary,`${t}.summary`),risks:Be(i.risks,`${t}.risks`,(a,o)=>Re(a,`${t}.risks[${o}]`)),risks_truncated:ei(i.risks_truncated,`${t}.risks_truncated`),completed_at:ti(i.completed_at,`${t}.completed_at`)}}function Od(e,t){let i=`Native history[${t}]`,r=ie(e,i);re(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=zn(r.unresolved_ids,`${i}.unresolved_ids`);return Rt(n,`${i}.unresolved_ids`),{goal_cycle:D(r.goal_cycle,`${i}.goal_cycle`,1),iteration:D(r.iteration,`${i}.iteration`),attempt:D(r.attempt,`${i}.attempt`),outcome:J(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Re(r.summary,`${i}.summary`),completed_at:ti(r.completed_at,`${i}.completed_at`)}}function Wy(e){let t="Native history_overflow.outcome_counts",i=ie(e,t),r=["pass","fail","blocked","execution-error","recovery"];return re(i,new Set(r),t),{pass:D(i.pass,`${t}.pass`),fail:D(i.fail,`${t}.fail`),blocked:D(i.blocked,`${t}.blocked`),"execution-error":D(i["execution-error"],`${t}.execution-error`),recovery:D(i.recovery,`${t}.recovery`)}}function zy(e){let t="Native history_overflow",i=ie(e,t);re(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=D(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:ti(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:ti(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=Wy(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 Jy(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 Gy(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 P(e){let t=ie(e,"Native portable state");if(re(t,Iy,"Native portable state"),t.schema!==Zt)throw new Error(`Native portable state schema must be ${Zt}`);let i=G(t.name,"Native state name");if(!Cy.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=Be(t.spec_changes,"Native spec_changes",Oy);Rt(r.map(s=>s.capability),"Native spec change capabilities");let n=Be(t.acceptance,"Native acceptance",By);Rt(n.map(s=>s.id),"Native acceptance IDs");let a=Be(t.history,"Native history",Od);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Zt,name:i,language:J(t.language,["en","zh-CN"],"Native state language"),phase:J(t.phase,["shape","build","verify","archive"],"Native state phase"),status:J(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:D(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:jy(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Hy(t.workspace),loop:Dy(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:My(t.builder_handoff),blockers:Be(t.blockers,"Native blockers",Fy),verification:t.verification===null?null:qy(t.verification),history:a,history_overflow:zy(t.history_overflow),verification_result:J(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:J(t.verification_report,["verification.md"],"Native verification_report"),archived:ei(t.archived,"Native archived"),created_at:ti(t.created_at,"Native created_at")};return Jy(o),Gy(o),o}function he(e,t){let i=P(e),r=Od(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 P({...i,history:n,history_overflow:a})}function Uy(e,t){let i=(0,Wn.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 Ce(e){let t=await Ry.readFile(e,"utf8");return P(Uy(t,"Native portable state"))}async function Jn(e,t,i={}){let r=P(t);await xe(e,(0,Wn.stringify)(r),i)}var Vn=new Map;async function Ky(e,t){let i=Vn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Vn.set(e,a),await i;try{return await t()}finally{r(),Vn.get(e)===a&&Vn.delete(e)}}async function Qi(e){return Ky(e.file,async()=>{let t=D(e.expectedStateVersion,"Native expected state version",1),i=P(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ce(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new qn(t,r.state_version);return await Jn(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ce(e.file);if(n.state_version!==t)throw new qn(t,n.state_version)}}),i})}var Hd="children.yaml",js="comet.native.children.v1",Yy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xy=new Set(["schema","children"]),Qy=new Set(["name","depends_on","covers"]);function Dd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bd(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 Ld(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 $s(e,t){let i=pe.normalize(pe.resolve(e)),r=pe.normalize(pe.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Zy(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 eN(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function tN(e,t){let i=(0,Os.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Dd(i.toJS({mapAsMap:!1}),"Native children contract");if(Bd(r,Xy,"Native children contract"),r.schema!==js)throw new Error(`Native children schema must be ${js}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Dd(s,`Native child ${c}`);if(Bd(l,Qy,`Native child ${c}`),typeof l.name!="string"||!Yy.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:Ld(l.depends_on,`Native child ${l.name} depends_on`),covers:Ld(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return Zy(n),t&&eN(n,t),{schema:js,children:n}}async function Zi(e){let t=pe.join(e.changeDir,Hd);try{await Fd.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await V({root:e.changeDir,ref:Hd});return{contract:tN(i.text,e.acceptanceIds),size:i.size}}function Gn(e){return te("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function iN(e){let t=Pn(e.projectRoot);t.some(r=>$s(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>pe.resolve(n)))]){let n=await De(r);n&&i.push({projectRoot:r,paths:await xt(r,n.native.artifact_root),parent:$s(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function rN(e,t){let i=pe.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ce(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function nN(e,t){let i;try{i=await Fd.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=pe.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ce(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function aN(e,t,i){let r=pe.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${pe.sep}`))return null;let n=r.split(pe.sep).join("/");try{let a=(0,Os.parseDocument)(ds(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:P(a.toJS({mapAsMap:!1}))}catch{return null}}function oN(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Md(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ct(e){let t=pe.join(e.paths.changesDir,e.state.name),i=await Zi({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=Gn({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await iN(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:h})=>h)),c=new Map,l=new Map;for(let h of a){let v=h.parent&&o?`refs/heads/${o}`:"HEAD";for(let g of await nN(h,s)){let w={...g,source:h,committedState:aN(h,g.file,v)};c.set(g.state.name,[...c.get(g.state.name)??[],w])}for(let g of s){let w=await rN(h,g);w&&l.set(g,[...l.get(g)??[],{source:h,state:w}])}}let f=new Map;for(let h of i.contract.children){let v=(c.get(h.name)??[]).find(({source:N,committedState:k})=>N.parent&&k?.name===h.name&&Md(k,o));if(v){f.set(h.name,{kind:"done",phase:v.state.phase,projectRoot:v.source.projectRoot,message:null});continue}let g=c.get(h.name)?.[0];if(g){f.set(h.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=l.get(h.name)??[];w.length>1?f.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):w[0]&&f.set(h.name,oN(w[0].state,w[0].source,o))}let d=new Map(i.contract.children.map(h=>[h.name,h])),u=new Map,p=h=>{let v=u.get(h);if(v)return v;let g=d.get(h),N=g.depends_on.map(p).every(({status:O})=>O==="done"),k=f.get(h),E=k?.kind==="active"&&N?g.depends_on.filter(O=>!(c.get(O)??[]).some(({source:Ie,committedState:ze})=>$s(Ie.projectRoot,k.projectRoot)&&ze?.name===O&&Md(ze,o))):[],S,R=k?.message??null;k?.kind==="done"?(S=N?"done":"blocked",N||(R=`Native child ${h} was merged before its dependencies`)):k?.kind==="active"?(S=N&&E.length===0?"active":"blocked",N?E.length>0&&(R=`Native child ${h} does not include merged dependencies: ${E.join(", ")}`):R=`Native child ${h} started before its dependencies merged`):k?.kind==="blocked"?S="blocked":(S=n&&N?"ready":"pending",n||(R="Parent Shape confirmation is required"));let b={name:h,dependsOn:[...g.depends_on],covers:[...g.covers],status:S,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:R};return u.set(h,b),b},m=i.contract.children.map(({name:h})=>p(h));return{contractHash:r,confirmed:n,parentBranch:o,children:m,readyChildren:m.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:m.every(({status:h})=>h==="done")}}function me(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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 zk}from"node:crypto";import{promises as br}from"node:fs";import Jk from"node:path";var nc=di(Gt(),1);import ni from"path";import{promises as ub}from"fs";import db from"path";import{AsyncLocalStorage as sN}from"async_hooks";import{randomUUID as Wd}from"crypto";import{promises as ve}from"fs";import zd from"os";import Q from"path";var Vd=16*1024,Jd=".coordinator",cN=5e3,qd=new sN,Un=new Map;function lN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function uN(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 Gd(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 Hs(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ae(i,r)?$(i,r):$(i,r)&&e.size===t.size}function Ds(e,t){return Hs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ke(e){let t,i;try{let r=await Kt(e,Vd,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Ee?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${Vd} 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:uN(JSON.parse(t.toString("utf8")),e),identity:Gd(i)}}async function dN(e){return(await Ke(e))?.owner??null}function Ud(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==zd.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=gN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function fN(e,t){try{await ve.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ve.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Bs(e,t){let i=await Ke(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ds(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ve.mkdir(t,{recursive:!0});let r=Q.join(t,`${Q.basename(e.file)}.${e.owner.id}.${Wd()}.removed`);try{await ve.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ke(r);if(!n||n.owner.id!==e.owner.id||!Hs(n.identity,e.identity))throw await fN(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ve.rm(r,{force:!0}),"removed"}function Kd(e){return{id:Wd(),pid:process.pid,hostname:zd.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Yd(e,t){let i;try{i=await ve.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await dN(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)+` +`,"utf8"),await i.sync(),Gd(await i.stat({bigint:!0}))}finally{await i.close()}}async function hN(e,t){let i=await B(e.runtimeDir,e.locksDir);await ve.mkdir(i,{recursive:!0});let r=await B(e.runtimeDir,Q.join(i,Jd));await ve.mkdir(r,{recursive:!0});let n=Kd(t),a=Q.join(r,`.${n.id}.tmp`),o=Q.join(r,`${n.id}.claim`);try{let s=await Yd(a,n);await ve.rename(a,o);let c=await Ke(o);if(!c||!Hs(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 ve.rm(a,{force:!0})}}async function pN(e){let t=Q.dirname(e.file),i=!1,r=Q.basename(e.file);for(let n of await ve.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Q.join(t,n.name);if(Q.resolve(a)!==Q.resolve(e.file))try{let o=await Ke(a),s=Ud(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bs(o,t);continue}n.name=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 vN(e){let t=Un.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Un.set(e,n),await t,()=>{i(),Un.get(e)===n&&Un.delete(e)}}async function Qd(e,t,i){let r=Q.resolve(e.locksDir),n=qd.getStore();if(n?.has(r))return i();let a=await vN(r);try{let o=await mN(e,t),s=new Map(n??[]);return s.set(r,o),await qd.run(s,async()=>{try{return await i()}finally{await Xd(o)}})}finally{a()}}async function Kn(e,t,i){return Qd(e,`acquire ${t}`,async()=>{let r=await B(e.runtimeDir,e.locksDir);await ve.mkdir(r,{recursive:!0});let n=await B(e.runtimeDir,Q.join(r,lN(t))),a=Kd(i),o=await Yd(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Yn(e){await Ke(e.file)&&await Qd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Q.basename(e.file)}`,async()=>{let t=await Ke(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ds(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=Q.join(e.locksDir,Jd);await Bs(t,i)})}function gN(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Zd(e){return Ud(await Ke(e))}import Gs from"node:path";import SN from"node:path";import tf from"node:path";var wN="comet.native.acceptance.v1";var Jx=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ir=Object.freeze({maxCriteria:1024});function Ms(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 Ls(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 ef(e){return e.includes("-->")||e.includes("--!>")}function*er(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(` -`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Ls(l,t);else if(i)ef(l)&&(i=!1);else if(r!==null)new RegExp(``,"iu").test(l)&&(r=null);else{let d=Ls(l,null);if(d!==null)t=d;else{let u=l.trimStart();if(u.startsWith(""||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 m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(m){c(),s={parts:[m[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(),Vs(n,"Specification mandatory requirements",r)}var yN=/^A[1-9]\d*$/u;function rf(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||tf.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||tf.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function NN(e,t){return e.localeCompare(t,"en")}function Xn(e){let t=rf(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>NN(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=qs(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=rf(a.source,`Native spec source for ${a.capability}`);r.push(...Ws(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...zs(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=tr(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 nf(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}function bN(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function I(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(bN(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 Ye="comet.native.v3",Le="comet.native.v2",Me="comet.native.v1";var Qn="comet.native.portable-migration.v1",SN=new Set(["schema","id","change","fromSchema","status","createdAt"]),EN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PN=/^[a-z0-9][a-z0-9-]{7,127}$/u,xN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),RN=new Set([Me,Le,Ye]);function CN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function AN(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 _N(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 TN(e){return e.schema===Me?rr(e):e.schema===Le?nr(e):ar(e)}function IN(e){return kN.posix.normalize(e.replaceAll("\\","/"))}function jN(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:IN(t.source)})}function $N(e){return e==="shape"?"shape":"build"}function ON(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function HN(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 of(e){let t=TN(e.state);nf(e.acceptance);let i=$N(t.phase),r=i==="shape"?0:1,n=AN(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 P({schema:Zt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:jN(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:ON(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:I(HN(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=CN(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!SN.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Qn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!PN.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!EN.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!RN.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!xN.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Qn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:_N(t.createdAt,"Native portable migration transaction createdAt")}}function sf(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 cf="comet.native.archive-transaction.v4",lf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",DN=new RegExp(`^portable-archive-(${lf})\\.json$`,"u"),BN=new RegExp(`^portable-migration-(${lf})\\.json$`,"u"),LN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,MN=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FN=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),VN=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),qN=new Set(["capability","operation","source","content"]),uf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function df(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ff(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 WN(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=df(e,i);if(ff(r,qN,i),typeof r.capability!="string"||!uf.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 zN(e){let t=df(e,"Native portable Archive transaction");if(ff(t,VN,"Native portable Archive transaction"),t.schema!==cf)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!LN.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!uf.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"||!MN.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"||!FN.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(WN);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:cf,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 Zn(e){let t=DN.exec(e);if(t)return{kind:"archive",change:t[1]};let i=BN.exec(e);return i?{kind:"migration",change:i[1]}:null}function ea(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Zn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Gs.join(e.transactionsDir,i)}async function Us(e,t){let i=Zn(t);if(!i)return null;let r=await V({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Gs.join(e.transactionsDir,t);if(i.kind==="archive"){let s=zN(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 hf(e,t){let i=ea(e,t);try{return await Us(e,Gs.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function pf(e){return e.kind==="archive"||e.journal.status!=="committed"}import Xe from"path";import{TextDecoder as ZN}from"util";import{createHash as JN}from"node:crypto";import{constants as ta,promises as Ae}from"node:fs";import _e from"node:path";function ra(e,t){let i=_e.relative(e,t);return i===""||!_e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_e.sep}`)}function GN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function UN(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function KN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ia(e,t){return $({...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 Ks(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function YN(e,t,i){let r=_e.resolve(e),n=_e.resolve(t);if(!ra(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Ks(r,i)],o=r;for(let s of _e.relative(r,n).split(_e.sep).filter(Boolean)){await At(a,i),o=_e.join(o,s);let c=await Ks(o,i);if(!ra(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await At(a,i),a}async function At(e,t){for(let i of e){let r=await Ae.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!UN(i,r)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function XN(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 ii(e){let t=GN(e.maxBytes),i=_e.resolve(e.file),r=await YN(e.root,_e.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Ks(_e.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await At(r,e.label);let a=await Ae.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=KN(a),s=await Ae.realpath(i);if(!ra(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>ra(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ta.O_RDONLY:ta.O_RDONLY|ta.O_NOFOLLOW|ta.O_NONBLOCK,l=await Ae.open(i,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!ia(o,f)||!ia(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await XN(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ia(o,m)||!ia(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:JN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var eb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),tb=new Set(["id","type","source","target","staged","backup"]),ib=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),rb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var gf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var nb=256*1024,ER=1024*1024,PR=16*1024;var xR=64*1024*1024;var ab=new ZN("utf-8",{fatal:!0});function aa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function oa(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 wf(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ys(e,t){if(typeof e!="string"||e.length===0||Xe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function na(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function mf(e,t){if(Ys(e,t),e.includes("\\")||e!==Xe.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 ob(e,t){let i=aa(e,`transaction operations[${t}]`);if(oa(i,tb,`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`);Ys(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ys(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 yf(e){let t=aa(e,"Native Archive transaction journal");if(oa(t,ib,"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"||!gf.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(!wf(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(na(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=aa(s,`Archive transaction operations[${c}]`);if(oa(l,rb,`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`);mf(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&mf(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&na(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(na(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`);na(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 sb(e){let t=aa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return yf(t);if(oa(t,eb,"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"||!gf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Xe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Xe.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(!wf(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(ob),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 cb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Xe.join(e.transactionsDir,t)}function Nf(e,t){let i=cb(e,t);return{directory:i,journal:Xe.join(i,"transaction.json"),events:Xe.join(i,"events.jsonl"),staged:Xe.join(i,"staged"),backups:Xe.join(i,"backups")}}async function Qs(e,t){let i=Nf(e,t);return await Promise.all(Object.values(i).map(r=>B(e.runtimeDir,r))),i}async function Zs(e,t,i={}){let r=await Qs(e,t),n=await ii({root:e.runtimeDir,file:r.journal,maxBytes:nb,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(ab.decode(n.bytes)),o=sb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function db(e,t,i){let r;try{r=await lb.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 Zs(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(Zn(n.name))try{let a=await Us(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(pf(a))return!0}catch{return!0}return!1}async function fb(e,t){let i=Date.now()+5e3,r=ub.join(e.locksDir,"root-move.lock");for(;;)try{return await Kn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Zd(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 _(e,t,i,r){let n=await fb(e,t);try{if(await Fn(e.projectRoot),await db(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Yn(n)}}import{createHash as hb}from"crypto";function ge(e){return hb("sha256").update(e).digest("hex")}var GR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var UR=8*1024*1024;var KR=64*1024,YR=64*1024;var XR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},QR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var ZR=(1n<<256n)-1n;var Nb=di(Gt(),1);var mC=4*1024*1024;var bb=null;function kb(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function bf(e,t){return(...i)=>{let r=bb;if(r===null)return t(...i);let n=kb(`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 NC=bf("hookWritePolicy",async e=>(await bs(e))?.hook??{allow_paths:[]});var mA=256*1024;var CA={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 ri from"node:path";var or=/^[a-f0-9]{64}$/u,Sf=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Pb=16*1024,WA=process.platform;function xb(e,t){let i=ri.relative(e,t);return ri.isAbsolute(i)||i===".."||i.startsWith(`..${ri.sep}`)?null:i.replaceAll("\\","/")||"."}function Ef(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Pf(e,t){if(e.length===0||Ef(e)||e.includes("\\")||ri.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=ri.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Rb(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 ec(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ef(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Cb(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ec(e.changeBranch,"Native workspace change branch"),ec(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 Ab(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"||!Sf.test(t.baseCommit)||typeof t.targetCommit!="string"||!Sf.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ec(t.targetBranch,"Native workspace Git target branch")}function _b(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"||!or.test(String(t.projectRootId))||!or.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Rb(t.capturedAt),Pf(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&&!or.test(String(t.projectRootPathId))||a&&!or.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!or.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Ab(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(Cb(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 Tb(e,t){return ri.join(Oe(e,t),"workspace.json")}function Ib(e,t){let i=Tb(e,t),r=He(e,i),n=xb(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Pf(n,"Native workspace file ref")}}async function jb(e,t){try{let i=Ib(e,t),r=await V({root:i.root,ref:i.ref,maxBytes:Pb});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function sr(e,t){let i=await jb(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(_b(i),i)}var Rf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Ob=new Set(Rf),Cf=new Set([...Rf,"minimum_runtime_version","revision"]),Hb=new Set([...Cf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Db=new Set(["capability","operation","source","base_hash"]),Bb=new Set(["shape","build","verify","archive"]),Lb=new Set(["implicit","confirmed"]),Mb=new Set(["pending","pass","fail"]),_t="comet-state.yaml",ic=/^[a-f0-9]{64}$/u,Af=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fb=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,rc=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"},ai=class extends Error{constructor(i,r){super(i!==Ye||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},sa=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"},cr=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"},ca=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"},m_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function ur(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _f(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 ac(e){if(!Af.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Vb(e){if(!Af.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Tf(e,t){if(e.length===0||ni.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function qb(e,t){let i=ur(e,`spec_changes[${t}]`);if(_f(i,Db,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Vb(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"&&Tf(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"||!ic.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"||!ic.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 Wb(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 oc(e,t){if(_f(e,t,_t),typeof e.name!="string")throw new Error("Native change name is required");if(ac(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"||!Bb.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&&!Lb.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(qb),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"||!Mb.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"&&Tf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Wb(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 rr(e){let t=ur(e,_t);if(t.schema!==Me)throw new Error(`Expected ${Me}`);return{schema:Me,...oc(t,Ob)}}function lr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function tc(e,t,i){if(e===null)return null;let r=typeof e=="string"?Fb.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function zb(e){if(e==null)return null;if(typeof e!="string"||!ic.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Jb(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 nr(e){let t=ur(e,_t);if(t.schema!==Le)throw new Error(`Expected ${Le}`);if(lr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:lr(t.revision,"Native v2 revision"),...oc(t,Cf)}}function ar(e){let t=ur(e,_t);if(t.schema!==Ye){if(t.schema===Me||t.schema===Le){let o=t.schema===Me?rr(t):nr(t);throw new rc(o.name,o.schema)}throw new ai(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=lr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ai(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=lr(t.revision,"Native revision"),n=oc(t,Hb),a=zb(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:r,verification_protocol:Jb(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:tc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:tc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:tc(t.partial_allowance,"Native partial_allowance","allowances")}}function Gb(e){let t=ur(e,_t);if(t.schema===Me){let n=rr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema===Le){let n=nr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema!==Ye){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 ai(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=lr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ai(t.schema,i).message};let r=ar(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Fe(e,t){ac(t);let i=ni.join(e.changesDir,t);if(!X(e.changesDir,i))throw new Error("Native change path escaped");return i}var Ub=256*1024;async function Kb(e,t=ni.dirname(e)){let i=ni.relative(t,e).split(ni.sep).join("/"),r=await V({root:t,ref:i,maxBytes:Ub}),n=(0,nc.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 If(e,t){let i=ni.join(Fe(e,t),_t);await B(e.nativeRoot,i);let r=Gb(await Kb(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{randomUUID as ba}from"node:crypto";import{promises as wr}from"node:fs";import W from"node:path";import{createWriteStream as vk,promises as gk}from"node:fs";import se from"node:path";import{spawn as sc}from"node:child_process";import{existsSync as jf}from"node:fs";import Tt from"node:path";var Yb=new Set([".bat",".cmd",".ps1"]),Xb=new Set([".bat",".cmd"]),Qb=/[&|<>()^%"!\r\n]/u,Zb=["$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("; ");function cc(e,t){let i=t.toLowerCase();return Object.entries(e).find(([r,n])=>r.toLowerCase()===i&&n!==void 0)?.[1]}function ek(e){let t=(cc(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function tk(e,t,i){let n=Tt.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(cc(t,"PATH")??"").split(Tt.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Tt.win32.extname(e)?[e]:ek(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Tt.join(s,c):Tt.resolve(i,c)))}function ik(e,t,i){return tk(e,t,i).find(r=>jf(r))??e}function rk(e){let t=cc(e,"SystemRoot");if(t){let i=Tt.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(jf(i))return i}return"powershell.exe"}function nk(e){if(e.some(t=>Qb.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function ak(e,t,i){let r=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(Zb,"utf16le").toString("base64");return sc(rk(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:i.cwd,env:{...i.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function lc(e,t,i){let r=i.env??process.env;if(process.platform!=="win32")return sc(e,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=ik(e,r,i.cwd),a=Tt.win32.extname(n).toLowerCase();return Xb.has(a)&&nk(t),Yb.has(a)?ak(n,t,{cwd:i.cwd,env:r}):sc(n,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as ok}from"node:child_process";import uc from"node:path";var sk=1e3,ck=2;async function la(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,r=i&&uc.win32.isAbsolute(i)?uc.win32.resolve(i):"C:\\Windows",n=uc.win32.join(r,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(d,u=!1)=>{s||(s=!0,l&&clearTimeout(l),u&&c?.kill("SIGKILL"),o(d))};try{c=ok(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",d=>f(d===0)),l=setTimeout(()=>f(!1,!0),sk)}catch{f(!1)}});for(let o=0;o{if(t)return t=!1,"[REDACTED]";let r=mt(i);return wk.test(i)&&(t=!0),r})}function da(e,t){if(Of(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return ua(e,t.cwdRef)}async function fc(e){let{plan:t}=e;Of(e.operationId,"Native check operation ID");let i=da(e.projectRoot,t),r=se.join(e.runtimeDir,"logs","checks"),n=se.join(r,`${e.operationId}-${t.id}.log`);if(!$f(se.resolve(e.runtimeDir),se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await gk.mkdir(r,{recursive:!0});let a=(e.now??(()=>new Date))(),o=vk(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=lc(t.executable,t.argv,{cwd:i,env:process.env})}catch(p){o.destroy(),c(p);return}let f=!1,d=null,u=setTimeout(()=>{f=!0,la(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);u.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",p=>{d=p,o.write(` +`),o.context,r)),o=null}};for(let{line:c,body:l}of er(e)){let f=l?Ms(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=tr(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Vs(n,"Specification",r)}function zs(e,t="spec.md",i=ir.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(Fs("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(f=>/^(?:non-?goals?|非目标)$/iu.test(f.text.trim()));for(let{line:f,body:d}of er(e)){let u=d?Ms(f):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=f.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Ls(f,null)!==null||p.startsWith(""||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 m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(m){c(),s={parts:[m[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(),Vs(n,"Specification mandatory requirements",r)}var NN=/^A[1-9]\d*$/u;function rf(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||tf.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||tf.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function bN(e,t){return e.localeCompare(t,"en")}function Xn(e){let t=rf(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>bN(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=qs(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=rf(a.source,`Native spec source for ${a.capability}`);r.push(...Ws(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...zs(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=tr(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 nf(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}function kN(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function I(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(kN(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 Ye="comet.native.v3",Le="comet.native.v2",Me="comet.native.v1";var Qn="comet.native.portable-migration.v1",EN=new Set(["schema","id","change","fromSchema","status","createdAt"]),PN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xN=/^[a-z0-9][a-z0-9-]{7,127}$/u,RN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),CN=new Set([Me,Le,Ye]);function AN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _N(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 TN(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 IN(e){return e.schema===Me?rr(e):e.schema===Le?nr(e):ar(e)}function jN(e){return SN.posix.normalize(e.replaceAll("\\","/"))}function $N(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:jN(t.source)})}function ON(e){return e==="shape"?"shape":"build"}function HN(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function DN(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 of(e){let t=IN(e.state);nf(e.acceptance);let i=ON(t.phase),r=i==="shape"?0:1,n=_N(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 P({schema:Zt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:$N(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:HN(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:I(DN(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=AN(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!EN.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Qn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!xN.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!PN.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!CN.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!RN.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Qn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:TN(t.createdAt,"Native portable migration transaction createdAt")}}function sf(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 cf="comet.native.archive-transaction.v4",lf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",BN=new RegExp(`^portable-archive-(${lf})\\.json$`,"u"),LN=new RegExp(`^portable-migration-(${lf})\\.json$`,"u"),MN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,FN=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VN=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),qN=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),WN=new Set(["capability","operation","source","content"]),uf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function df(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ff(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 zN(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=df(e,i);if(ff(r,WN,i),typeof r.capability!="string"||!uf.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 JN(e){let t=df(e,"Native portable Archive transaction");if(ff(t,qN,"Native portable Archive transaction"),t.schema!==cf)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!MN.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!uf.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"||!FN.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"||!VN.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(zN);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:cf,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 Zn(e){let t=BN.exec(e);if(t)return{kind:"archive",change:t[1]};let i=LN.exec(e);return i?{kind:"migration",change:i[1]}:null}function ea(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Zn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Gs.join(e.transactionsDir,i)}async function Us(e,t){let i=Zn(t);if(!i)return null;let r=await V({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Gs.join(e.transactionsDir,t);if(i.kind==="archive"){let s=JN(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 hf(e,t){let i=ea(e,t);try{return await Us(e,Gs.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function pf(e){return e.kind==="archive"||e.journal.status!=="committed"}import Xe from"path";import{TextDecoder as eb}from"util";import{createHash as GN}from"node:crypto";import{constants as ta,promises as Ae}from"node:fs";import _e from"node:path";function ra(e,t){let i=_e.relative(e,t);return i===""||!_e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_e.sep}`)}function UN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function KN(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function YN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ia(e,t){return $({...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 Ks(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function XN(e,t,i){let r=_e.resolve(e),n=_e.resolve(t);if(!ra(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Ks(r,i)],o=r;for(let s of _e.relative(r,n).split(_e.sep).filter(Boolean)){await At(a,i),o=_e.join(o,s);let c=await Ks(o,i);if(!ra(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await At(a,i),a}async function At(e,t){for(let i of e){let r=await Ae.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!KN(i,r)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function QN(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 ii(e){let t=UN(e.maxBytes),i=_e.resolve(e.file),r=await XN(e.root,_e.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Ks(_e.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await At(r,e.label);let a=await Ae.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=YN(a),s=await Ae.realpath(i);if(!ra(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>ra(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ta.O_RDONLY:ta.O_RDONLY|ta.O_NOFOLLOW|ta.O_NONBLOCK,l=await Ae.open(i,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!ia(o,f)||!ia(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await QN(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ia(o,m)||!ia(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:GN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var tb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),ib=new Set(["id","type","source","target","staged","backup"]),rb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),nb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var gf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var ab=256*1024,PR=1024*1024,xR=16*1024;var RR=64*1024*1024;var ob=new eb("utf-8",{fatal:!0});function aa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function oa(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 wf(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ys(e,t){if(typeof e!="string"||e.length===0||Xe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function na(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function mf(e,t){if(Ys(e,t),e.includes("\\")||e!==Xe.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 sb(e,t){let i=aa(e,`transaction operations[${t}]`);if(oa(i,ib,`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`);Ys(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ys(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 yf(e){let t=aa(e,"Native Archive transaction journal");if(oa(t,rb,"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"||!gf.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(!wf(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(na(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=aa(s,`Archive transaction operations[${c}]`);if(oa(l,nb,`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`);mf(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&mf(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&na(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(na(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`);na(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 cb(e){let t=aa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return yf(t);if(oa(t,tb,"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"||!gf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Xe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Xe.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(!wf(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(sb),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 lb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Xe.join(e.transactionsDir,t)}function Nf(e,t){let i=lb(e,t);return{directory:i,journal:Xe.join(i,"transaction.json"),events:Xe.join(i,"events.jsonl"),staged:Xe.join(i,"staged"),backups:Xe.join(i,"backups")}}async function Qs(e,t){let i=Nf(e,t);return await Promise.all(Object.values(i).map(r=>B(e.runtimeDir,r))),i}async function Zs(e,t,i={}){let r=await Qs(e,t),n=await ii({root:e.runtimeDir,file:r.journal,maxBytes:ab,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(ob.decode(n.bytes)),o=cb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function fb(e,t,i){let r;try{r=await ub.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 Zs(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(Zn(n.name))try{let a=await Us(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(pf(a))return!0}catch{return!0}return!1}async function hb(e,t){let i=Date.now()+5e3,r=db.join(e.locksDir,"root-move.lock");for(;;)try{return await Kn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Zd(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 _(e,t,i,r){let n=await hb(e,t);try{if(await Fn(e.projectRoot),await fb(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Yn(n)}}import{createHash as pb}from"crypto";function ge(e){return pb("sha256").update(e).digest("hex")}var UR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var KR=8*1024*1024;var YR=64*1024,XR=64*1024;var QR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},ZR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var eC=(1n<<256n)-1n;var bb=di(Gt(),1);var vC=4*1024*1024;var kb=null;function Sb(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function bf(e,t){return(...i)=>{let r=kb;if(r===null)return t(...i);let n=Sb(`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 bC=bf("hookWritePolicy",async e=>(await bs(e))?.hook??{allow_paths:[]});var vA=256*1024;var AA={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 ri from"node:path";var or=/^[a-f0-9]{64}$/u,Sf=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,xb=16*1024,zA=process.platform;function Rb(e,t){let i=ri.relative(e,t);return ri.isAbsolute(i)||i===".."||i.startsWith(`..${ri.sep}`)?null:i.replaceAll("\\","/")||"."}function Ef(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Pf(e,t){if(e.length===0||Ef(e)||e.includes("\\")||ri.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=ri.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Cb(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 ec(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ef(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ab(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ec(e.changeBranch,"Native workspace change branch"),ec(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 _b(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"||!Sf.test(t.baseCommit)||typeof t.targetCommit!="string"||!Sf.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ec(t.targetBranch,"Native workspace Git target branch")}function Tb(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"||!or.test(String(t.projectRootId))||!or.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Cb(t.capturedAt),Pf(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&&!or.test(String(t.projectRootPathId))||a&&!or.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!or.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&_b(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(Ab(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 Ib(e,t){return ri.join(Oe(e,t),"workspace.json")}function jb(e,t){let i=Ib(e,t),r=He(e,i),n=Rb(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Pf(n,"Native workspace file ref")}}async function $b(e,t){try{let i=jb(e,t),r=await V({root:i.root,ref:i.ref,maxBytes:xb});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function sr(e,t){let i=await $b(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Tb(i),i)}var Rf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Hb=new Set(Rf),Cf=new Set([...Rf,"minimum_runtime_version","revision"]),Db=new Set([...Cf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Bb=new Set(["capability","operation","source","base_hash"]),Lb=new Set(["shape","build","verify","archive"]),Mb=new Set(["implicit","confirmed"]),Fb=new Set(["pending","pass","fail"]),_t="comet-state.yaml",ic=/^[a-f0-9]{64}$/u,Af=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Vb=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,rc=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"},ai=class extends Error{constructor(i,r){super(i!==Ye||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},sa=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"},cr=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"},ca=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"},v_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function ur(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _f(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 ac(e){if(!Af.test(e))throw new Error(`Invalid Native change name: ${e}`)}function qb(e){if(!Af.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Tf(e,t){if(e.length===0||ni.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Wb(e,t){let i=ur(e,`spec_changes[${t}]`);if(_f(i,Bb,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(qb(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"&&Tf(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"||!ic.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"||!ic.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 zb(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 oc(e,t){if(_f(e,t,_t),typeof e.name!="string")throw new Error("Native change name is required");if(ac(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"||!Lb.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&&!Mb.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(Wb),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"||!Fb.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"&&Tf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!zb(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 rr(e){let t=ur(e,_t);if(t.schema!==Me)throw new Error(`Expected ${Me}`);return{schema:Me,...oc(t,Hb)}}function lr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function tc(e,t,i){if(e===null)return null;let r=typeof e=="string"?Vb.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function Jb(e){if(e==null)return null;if(typeof e!="string"||!ic.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Gb(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 nr(e){let t=ur(e,_t);if(t.schema!==Le)throw new Error(`Expected ${Le}`);if(lr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:lr(t.revision,"Native v2 revision"),...oc(t,Cf)}}function ar(e){let t=ur(e,_t);if(t.schema!==Ye){if(t.schema===Me||t.schema===Le){let o=t.schema===Me?rr(t):nr(t);throw new rc(o.name,o.schema)}throw new ai(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=lr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ai(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=lr(t.revision,"Native revision"),n=oc(t,Db),a=Jb(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:r,verification_protocol:Gb(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:tc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:tc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:tc(t.partial_allowance,"Native partial_allowance","allowances")}}function Ub(e){let t=ur(e,_t);if(t.schema===Me){let n=rr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema===Le){let n=nr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema!==Ye){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 ai(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=lr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ai(t.schema,i).message};let r=ar(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Fe(e,t){ac(t);let i=ni.join(e.changesDir,t);if(!X(e.changesDir,i))throw new Error("Native change path escaped");return i}var Kb=256*1024;async function Yb(e,t=ni.dirname(e)){let i=ni.relative(t,e).split(ni.sep).join("/"),r=await V({root:t,ref:i,maxBytes:Kb}),n=(0,nc.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 If(e,t){let i=ni.join(Fe(e,t),_t);await B(e.nativeRoot,i);let r=Ub(await Yb(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{randomUUID as ba}from"node:crypto";import{promises as wr}from"node:fs";import W from"node:path";import{createWriteStream as gk,promises as wk}from"node:fs";import se from"node:path";import{spawn as sc}from"node:child_process";import{existsSync as jf}from"node:fs";import Tt from"node:path";var Xb=new Set([".bat",".cmd",".ps1"]),Qb=new Set([".bat",".cmd"]),Zb=/[&|<>()^%"!\r\n]/u,ek=["$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("; ");function cc(e,t){let i=t.toLowerCase();return Object.entries(e).find(([r,n])=>r.toLowerCase()===i&&n!==void 0)?.[1]}function tk(e){let t=(cc(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function ik(e,t,i){let n=Tt.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(cc(t,"PATH")??"").split(Tt.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Tt.win32.extname(e)?[e]:tk(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Tt.join(s,c):Tt.resolve(i,c)))}function rk(e,t,i){return ik(e,t,i).find(r=>jf(r))??e}function nk(e){let t=cc(e,"SystemRoot");if(t){let i=Tt.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(jf(i))return i}return"powershell.exe"}function ak(e){if(e.some(t=>Zb.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function ok(e,t,i){let r=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(ek,"utf16le").toString("base64");return sc(nk(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:i.cwd,env:{...i.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function lc(e,t,i){let r=i.env??process.env;if(process.platform!=="win32")return sc(e,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=rk(e,r,i.cwd),a=Tt.win32.extname(n).toLowerCase();return Qb.has(a)&&ak(t),Xb.has(a)?ok(n,t,{cwd:i.cwd,env:r}):sc(n,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as sk}from"node:child_process";import uc from"node:path";var ck=1e3,lk=2;async function la(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,r=i&&uc.win32.isAbsolute(i)?uc.win32.resolve(i):"C:\\Windows",n=uc.win32.join(r,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(d,u=!1)=>{s||(s=!0,l&&clearTimeout(l),u&&c?.kill("SIGKILL"),o(d))};try{c=sk(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",d=>f(d===0)),l=setTimeout(()=>f(!1,!0),ck)}catch{f(!1)}});for(let o=0;o{if(t)return t=!1,"[REDACTED]";let r=mt(i);return yk.test(i)&&(t=!0),r})}function da(e,t){if(Of(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return ua(e,t.cwdRef)}async function fc(e){let{plan:t}=e;Of(e.operationId,"Native check operation ID");let i=da(e.projectRoot,t),r=se.join(e.runtimeDir,"logs","checks"),n=se.join(r,`${e.operationId}-${t.id}.log`);if(!$f(se.resolve(e.runtimeDir),se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await wk.mkdir(r,{recursive:!0});let a=(e.now??(()=>new Date))(),o=gk(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=lc(t.executable,t.argv,{cwd:i,env:process.env})}catch(p){o.destroy(),c(p);return}let f=!1,d=null,u=setTimeout(()=>{f=!0,la(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);u.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",p=>{d=p,o.write(` [comet] failed to start check: ${mt(p.message)} -`)}),l.once("close",(p,m)=>{clearTimeout(u);let h=(e.now??(()=>new Date))();o.end(()=>{let v=f||d!==null||m!==null;s({id:t.id,name:t.name,argvDisplay:dc(t.argv),cwdRef:t.cwdRef,status:v?"interrupted":p===0?"passed":"failed",exitCode:p,signal:m,timedOut:f,durationMs:Math.max(0,h.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:h.toISOString(),repeatable:t.repeatable,logRef:se.relative(e.runtimeDir,n).split(se.sep).join("/")})})}),o.once("error",p=>{clearTimeout(u),la(l).catch(()=>l.kill("SIGKILL")),c(p)})})}import{randomUUID as kk}from"node:crypto";var Hf=Symbol("comet.native.trusted-execution-identity"),Df=Symbol("comet.native.trusted-verifier-envelope"),q="skill-coordinated";function hc(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function fr(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){hc(t.identityProvider,"Native identity provider");let i=Object.freeze({identityProvider:q,executionRef:hc(t.executionRef,"Native execution ref"),[Hf]:!0});return e.add(i),i},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:hc(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Df]:!0})}})}function fa(e){return typeof e=="object"&&e!==null&&e[Df]===!0}function Bf(e){return typeof e=="object"&&e!==null&&e[Hf]===!0}function ha(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function pr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function It(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function yk(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,i)=>{let r=ha(t,`Native Verifier acceptance ${i}`);hr(r,["id","result","reason"],`Native Verifier acceptance ${i}`);let n=It(r.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(r.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:r.result,reason:It(r.reason,`Native Verifier acceptance ${n} reason`)}})}function Nk(e){let t=ha(e,"Native Verifier final result");if(hr(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:pr(t.iteration,"Native Verifier iteration"),attempt:pr(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:yk(t.acceptance),risks:t.risks,summary:It(t.summary,"Native Verifier summary")}}function bk(e,t){let i=ha(e,`Native Verifier check request ${t}`);if(hr(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let r=pr(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(r<1)throw new Error("Native Verifier check timeout must be positive");return{id:It(i.id,`Native Verifier check request ${t} ID`),name:It(i.name,`Native Verifier check request ${t} name`),executable:It(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:It(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:r,repeatable:i.repeatable}}function pc(e){let t=ha(e,"Native Verifier response");if(t.kind==="final-result")return hr(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:Nk(t.result)};if(t.kind==="request-checks"){if(hr(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:pr(t.iteration,"Native Verifier iteration"),attempt:pr(t.attempt,"Native Verifier attempt"),checks:t.checks.map(bk)}}throw new Error("Native Verifier response kind is invalid")}function Lf(e){if(!fa(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:i}=e;if(t.candidateId!==i.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==i.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===i.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let r=pc(t.payload),n=r.kind==="final-result"?r.result.iteration:r.iteration,a=r.kind==="final-result"?r.result.attempt:r.attempt;if(n!==i.iteration||a!==i.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(r.kind==="request-checks")return r;let o=[...i.acceptanceIds],s=r.result.acceptance.map(({id:u})=>u),c=s.filter((u,p)=>s.indexOf(u)!==p),l=s.filter(u=>!o.includes(u)),f=o.filter(u=>!s.includes(u));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!i.requiredChecksPassed&&r.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=r.result.acceptance.map(({result:u})=>u);if(r.result.verdict==="pass"&&d.some(u=>u!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(r.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(r.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return r}var mr=3,mc=2;function ce(e){return e.state_version+1}function Sk(e,t,i){let r=[...e];if(new Set(r).size!==r.length)throw new Error(`${i} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${i} contains unknown IDs: ${a.join(", ")}`);return r}function vc(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Ek(e){return(e??[]).map(t=>({name:I(t.name),result:t.result,note:t.note?I(t.note):null}))}function jt(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:I(e.summary),completed_at:e.completedAt}}function Mf(e){let t=P(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let i=e.acceptance.map(({id:r})=>r);if(new Set(i).size!==i.length)throw new Error("Native acceptance IDs must be unique");return P({...t,phase:"build",state_version:ce(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(r=>({...r,result:"pending",reason:null}))})}function gc(e){let t=P(e.state),{input:i}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Bf(i.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");let r=Sk(i.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=(i.now??new Date).toISOString();return P({...t,phase:"verify",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:vc(t.acceptance),builder_handoff:{candidate_id:i.candidateId??kk(),identity_provider:i.identity.identityProvider,builder_execution_ref:i.identity.executionRef,iteration:t.loop.iteration,summary:I(i.summary),addressed_acceptance_ids:r,checks:Ek(i.checks),checks_truncated:!1,known_limits:(i.knownLimits??[]).map(a=>I(a)),known_limits_truncated:!1,submitted_at:n},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Ff(e){let t=P(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt is not ready to dispatch");return P({...t,state_version:ce(t),loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Pk(e,t){let i=e.loop.previous_unresolved_ids;if(i.length===0)return 0;let r=new Set(i),n=new Set(t);return n.sizer.has(o))?0:e.loop.no_progress_count+1}function xk(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===q?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:I(e.response.result.summary),risks:e.response.result.risks.map(t=>I(t)),risks_truncated:!1,completed_at:e.completedAt}}function Vf(e){let t=P(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let i=Lf({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:t.acceptance.map(({id:m})=>m),requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let r=(e.now??new Date).toISOString(),n=new Map(i.result.acceptance.map(m=>[m.id,m])),a=t.acceptance.map(m=>{let h=n.get(m.id);return{...m,result:h.result,reason:I(h.reason)}}),o=a.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),s=xk({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:r});if(i.result.verdict==="pass"){let m=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"pass",summary:i.result.summary,completedAt:r})),h=t.builder_handoff.identity_provider===q;return{response:i,state:P({...m,phase:h?"verify":"archive",status:h?"await-user":"active",state_version:ce(t),verification_result:"pass",verification_report:"verification.md",blockers:h?[{owner:"user",reason:I("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:h?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:h?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"blocked",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:P({...m,status:"await-user",state_version:ce(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:I(i.result.summary),acceptance_ids:o,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:o,next_action:"resolve-verifier-blocker"}})}}let c=t.loop.failed_iteration_count+1,l=Pk(t,o),f=c>=e.maxVerifyFailures,d=l>=3,u=f||d,p=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"fail",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:P({...p,phase:u?"verify":"build",status:u?"await-user":"active",state_version:ce(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:u?[{owner:"user",reason:I(f?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:o,resolution_action:"await-user"}]:l>=2?[{owner:"builder",reason:I("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:o,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:u?"await-user":"repairing",iteration:u?t.loop.iteration:t.loop.iteration+1,attempt:u?t.loop.attempt:0,failed_iteration_count:c,no_progress_count:l,execution_failure_count:0,previous_unresolved_ids:o,next_action:u?"await-user":"repair-failed-acceptance"}})}}function qf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==q||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return P({...t,phase:"archive",status:"active",state_version:ce(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Wf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==q||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let i=(e.now??new Date).toISOString(),r=t.acceptance.map(({id:a})=>a),n=he(t,jt({state:t,outcome:"blocked",unresolvedIds:r,summary:e.summary,completedAt:i}));return P({...n,status:"await-user",state_version:ce(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:I(e.summary),risks:[I("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:i},blockers:[{owner:"user",reason:I("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:r,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:r,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function zf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let i=(e.now??new Date).toISOString(),r=I(e.summary),n=he(t,jt({state:t,outcome:"pass",summary:e.summary,completedAt:i}));return P({...n,phase:"archive",status:"active",state_version:ce(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:r,completed_at:i},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:I(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Jf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return P({...t,status:"active",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,acceptance:vc(t.acceptance),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Gf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let i=(e.now??new Date).toISOString(),r=t.loop.execution_failure_count+1,n=r>=mr,a=he(t,jt({state:t,outcome:"execution-error",summary:e.summary,completedAt:i}));return P({...a,status:n?"blocked":"active",state_version:ce(t),blockers:n?[{owner:"runtime",reason:I(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:r,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Uf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return P({...t,status:"active",state_version:ce(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function vr(e){let t=P(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=he(t,jt({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return P({...r,phase:"build",status:"active",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:vc(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 Yf}from"node:fs";import gr from"node:path";function pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ma(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 Ve(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 Kf(e,t){return e===null?null:Ve(e,t)}function ga(e,t,i=0){if(!Number.isSafeInteger(e)||eVe(l,`${i}.argv[${f}]`,!0)),a=va(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=wc(r.startedAt,`${i}.startedAt`),s=wc(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=ga(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ve(r.id,`${i}.id`),name:Ve(r.name,`${i}.name`),operationId:Ve(r.operationId,`${i}.operationId`),status:a,repeatable:Ck(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:ga(r.executionCount,`${i}.executionCount`),argv:n,cwd:yc(r.cwd,`${i}.cwd`),exitCode:Rk(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ve(r.log,`${i}.log`)}}function Nc(e){let t="Native local execution state",i=pa(e,t);if(ma(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Xi)throw new Error(`Native local execution schema must be ${Xi}`);let r=pa(i.workspace,"Native local workspace");ma(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=pa(i.execution,"Native local execution");ma(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=wc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ve(o.operationId,"Native local execution.operationId"),stage:va(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:va(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Kf(o.executionId,"Native local execution.executionId"),status:va(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ga(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(Ak);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:Xi,change:Ve(i.change,"Native local change"),basedOnStateVersion:ga(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:yc(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:yc(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Kf(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function U(e){return Nc({schema:Xi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:gr.resolve(e.projectRoot),worktreeRoot:gr.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function qe(e){let t;try{t=await Yf.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 Nc(i)}async function j(e,t,i={}){let r=Nc(t);await Yf.mkdir(gr.dirname(e),{recursive:!0}),await fe(e,r,i)}async function bc(e){let t=null,i=null;try{t=await qe(e.file),t===null&&(i="missing")}catch(n){if(n.code)throw n;i="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(i="version-mismatch"),t&&i===null)return{state:t,rebuilt:!1,reason:null};let r=U(e);return await j(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:r,rebuilt:!0,reason:i??"missing"}}import{promises as _k}from"node:fs";function vt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` -`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Qe(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"
")}function Tk(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 Ik(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===q?q:"host-attested")}function jk(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Qe(o.id)} | ${Qe(o.result)} | ${Qe(o.source)} | ${Qe(o.text)} | ${Qe(vt(o.reason))} |`).join(` +`)}),l.once("close",(p,m)=>{clearTimeout(u);let h=(e.now??(()=>new Date))();o.end(()=>{let v=f||d!==null||m!==null;s({id:t.id,name:t.name,argvDisplay:dc(t.argv),cwdRef:t.cwdRef,status:v?"interrupted":p===0?"passed":"failed",exitCode:p,signal:m,timedOut:f,durationMs:Math.max(0,h.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:h.toISOString(),repeatable:t.repeatable,logRef:se.relative(e.runtimeDir,n).split(se.sep).join("/")})})}),o.once("error",p=>{clearTimeout(u),la(l).catch(()=>l.kill("SIGKILL")),c(p)})})}import{randomUUID as Sk}from"node:crypto";var Hf=Symbol("comet.native.trusted-execution-identity"),Df=Symbol("comet.native.trusted-verifier-envelope"),q="skill-coordinated";function hc(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function fr(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){hc(t.identityProvider,"Native identity provider");let i=Object.freeze({identityProvider:q,executionRef:hc(t.executionRef,"Native execution ref"),[Hf]:!0});return e.add(i),i},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:hc(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Df]:!0})}})}function fa(e){return typeof e=="object"&&e!==null&&e[Df]===!0}function Bf(e){return typeof e=="object"&&e!==null&&e[Hf]===!0}function ha(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function pr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function It(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Nk(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,i)=>{let r=ha(t,`Native Verifier acceptance ${i}`);hr(r,["id","result","reason"],`Native Verifier acceptance ${i}`);let n=It(r.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(r.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:r.result,reason:It(r.reason,`Native Verifier acceptance ${n} reason`)}})}function bk(e){let t=ha(e,"Native Verifier final result");if(hr(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:pr(t.iteration,"Native Verifier iteration"),attempt:pr(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:Nk(t.acceptance),risks:t.risks,summary:It(t.summary,"Native Verifier summary")}}function kk(e,t){let i=ha(e,`Native Verifier check request ${t}`);if(hr(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let r=pr(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(r<1)throw new Error("Native Verifier check timeout must be positive");return{id:It(i.id,`Native Verifier check request ${t} ID`),name:It(i.name,`Native Verifier check request ${t} name`),executable:It(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:It(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:r,repeatable:i.repeatable}}function pc(e){let t=ha(e,"Native Verifier response");if(t.kind==="final-result")return hr(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:bk(t.result)};if(t.kind==="request-checks"){if(hr(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:pr(t.iteration,"Native Verifier iteration"),attempt:pr(t.attempt,"Native Verifier attempt"),checks:t.checks.map(kk)}}throw new Error("Native Verifier response kind is invalid")}function Lf(e){if(!fa(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:i}=e;if(t.candidateId!==i.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==i.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===i.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let r=pc(t.payload),n=r.kind==="final-result"?r.result.iteration:r.iteration,a=r.kind==="final-result"?r.result.attempt:r.attempt;if(n!==i.iteration||a!==i.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(r.kind==="request-checks")return r;let o=[...i.acceptanceIds],s=r.result.acceptance.map(({id:u})=>u),c=s.filter((u,p)=>s.indexOf(u)!==p),l=s.filter(u=>!o.includes(u)),f=o.filter(u=>!s.includes(u));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!i.requiredChecksPassed&&r.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=r.result.acceptance.map(({result:u})=>u);if(r.result.verdict==="pass"&&d.some(u=>u!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(r.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(r.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return r}var mr=3,mc=2;function ce(e){return e.state_version+1}function Ek(e,t,i){let r=[...e];if(new Set(r).size!==r.length)throw new Error(`${i} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${i} contains unknown IDs: ${a.join(", ")}`);return r}function vc(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Pk(e){return(e??[]).map(t=>({name:I(t.name),result:t.result,note:t.note?I(t.note):null}))}function jt(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:I(e.summary),completed_at:e.completedAt}}function Mf(e){let t=P(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let i=e.acceptance.map(({id:r})=>r);if(new Set(i).size!==i.length)throw new Error("Native acceptance IDs must be unique");return P({...t,phase:"build",state_version:ce(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(r=>({...r,result:"pending",reason:null}))})}function gc(e){let t=P(e.state),{input:i}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Bf(i.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");let r=Ek(i.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=(i.now??new Date).toISOString();return P({...t,phase:"verify",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:vc(t.acceptance),builder_handoff:{candidate_id:i.candidateId??Sk(),identity_provider:i.identity.identityProvider,builder_execution_ref:i.identity.executionRef,iteration:t.loop.iteration,summary:I(i.summary),addressed_acceptance_ids:r,checks:Pk(i.checks),checks_truncated:!1,known_limits:(i.knownLimits??[]).map(a=>I(a)),known_limits_truncated:!1,submitted_at:n},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Ff(e){let t=P(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt is not ready to dispatch");return P({...t,state_version:ce(t),loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function xk(e,t){let i=e.loop.previous_unresolved_ids;if(i.length===0)return 0;let r=new Set(i),n=new Set(t);return n.sizer.has(o))?0:e.loop.no_progress_count+1}function Rk(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===q?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:I(e.response.result.summary),risks:e.response.result.risks.map(t=>I(t)),risks_truncated:!1,completed_at:e.completedAt}}function Vf(e){let t=P(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let i=Lf({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:t.acceptance.map(({id:m})=>m),requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let r=(e.now??new Date).toISOString(),n=new Map(i.result.acceptance.map(m=>[m.id,m])),a=t.acceptance.map(m=>{let h=n.get(m.id);return{...m,result:h.result,reason:I(h.reason)}}),o=a.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),s=Rk({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:r});if(i.result.verdict==="pass"){let m=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"pass",summary:i.result.summary,completedAt:r})),h=t.builder_handoff.identity_provider===q;return{response:i,state:P({...m,phase:h?"verify":"archive",status:h?"await-user":"active",state_version:ce(t),verification_result:"pass",verification_report:"verification.md",blockers:h?[{owner:"user",reason:I("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:h?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:h?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"blocked",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:P({...m,status:"await-user",state_version:ce(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:I(i.result.summary),acceptance_ids:o,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:o,next_action:"resolve-verifier-blocker"}})}}let c=t.loop.failed_iteration_count+1,l=xk(t,o),f=c>=e.maxVerifyFailures,d=l>=3,u=f||d,p=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"fail",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:P({...p,phase:u?"verify":"build",status:u?"await-user":"active",state_version:ce(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:u?[{owner:"user",reason:I(f?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:o,resolution_action:"await-user"}]:l>=2?[{owner:"builder",reason:I("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:o,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:u?"await-user":"repairing",iteration:u?t.loop.iteration:t.loop.iteration+1,attempt:u?t.loop.attempt:0,failed_iteration_count:c,no_progress_count:l,execution_failure_count:0,previous_unresolved_ids:o,next_action:u?"await-user":"repair-failed-acceptance"}})}}function qf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==q||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return P({...t,phase:"archive",status:"active",state_version:ce(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Wf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==q||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let i=(e.now??new Date).toISOString(),r=t.acceptance.map(({id:a})=>a),n=he(t,jt({state:t,outcome:"blocked",unresolvedIds:r,summary:e.summary,completedAt:i}));return P({...n,status:"await-user",state_version:ce(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:I(e.summary),risks:[I("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:i},blockers:[{owner:"user",reason:I("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:r,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:r,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function zf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let i=(e.now??new Date).toISOString(),r=I(e.summary),n=he(t,jt({state:t,outcome:"pass",summary:e.summary,completedAt:i}));return P({...n,phase:"archive",status:"active",state_version:ce(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:r,completed_at:i},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:I(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Jf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return P({...t,status:"active",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,acceptance:vc(t.acceptance),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Gf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let i=(e.now??new Date).toISOString(),r=t.loop.execution_failure_count+1,n=r>=mr,a=he(t,jt({state:t,outcome:"execution-error",summary:e.summary,completedAt:i}));return P({...a,status:n?"blocked":"active",state_version:ce(t),blockers:n?[{owner:"runtime",reason:I(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:r,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Uf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return P({...t,status:"active",state_version:ce(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function vr(e){let t=P(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=he(t,jt({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return P({...r,phase:"build",status:"active",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:vc(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 Yf}from"node:fs";import gr from"node:path";function pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ma(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 Ve(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 Kf(e,t){return e===null?null:Ve(e,t)}function ga(e,t,i=0){if(!Number.isSafeInteger(e)||eVe(l,`${i}.argv[${f}]`,!0)),a=va(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=wc(r.startedAt,`${i}.startedAt`),s=wc(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=ga(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ve(r.id,`${i}.id`),name:Ve(r.name,`${i}.name`),operationId:Ve(r.operationId,`${i}.operationId`),status:a,repeatable:Ak(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:ga(r.executionCount,`${i}.executionCount`),argv:n,cwd:yc(r.cwd,`${i}.cwd`),exitCode:Ck(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ve(r.log,`${i}.log`)}}function Nc(e){let t="Native local execution state",i=pa(e,t);if(ma(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Xi)throw new Error(`Native local execution schema must be ${Xi}`);let r=pa(i.workspace,"Native local workspace");ma(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=pa(i.execution,"Native local execution");ma(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=wc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ve(o.operationId,"Native local execution.operationId"),stage:va(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:va(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Kf(o.executionId,"Native local execution.executionId"),status:va(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ga(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(_k);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:Xi,change:Ve(i.change,"Native local change"),basedOnStateVersion:ga(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:yc(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:yc(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Kf(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function U(e){return Nc({schema:Xi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:gr.resolve(e.projectRoot),worktreeRoot:gr.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function qe(e){let t;try{t=await Yf.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 Nc(i)}async function j(e,t,i={}){let r=Nc(t);await Yf.mkdir(gr.dirname(e),{recursive:!0}),await fe(e,r,i)}async function bc(e){let t=null,i=null;try{t=await qe(e.file),t===null&&(i="missing")}catch(n){if(n.code)throw n;i="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(i="version-mismatch"),t&&i===null)return{state:t,rebuilt:!1,reason:null};let r=U(e);return await j(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:r,rebuilt:!0,reason:i??"missing"}}import{promises as Tk}from"node:fs";function vt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` +`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Qe(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"
")}function Ik(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 jk(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===q?q:"host-attested")}function $k(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Qe(o.id)} | ${Qe(o.result)} | ${Qe(o.source)} | ${Qe(o.text)} | ${Qe(vt(o.reason))} |`).join(` `),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(vt).join(" ");return`| ${Qe(vt(o.name))} | ${Qe(s||"—")} | ${Qe(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(` `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${vt(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(` `),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${vt(o)}`).join(` @@ -163,8 +163,8 @@ generated_from_state_version: ${e.state_version} ## Current result -- Result: **${Tk(e)}** -- Assurance: **${Ik(e)}** +- Result: **${Ik(e)}** +- Assurance: **${jk(e)}** - Goal cycle: ${e.loop.goal_cycle} - Iteration: ${e.verification.iteration} - Verifier attempt: ${e.verification.attempt} @@ -198,16 +198,16 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ `:""}## Conclusion ${vt(e.verification.summary)} -`}function $k(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 Xf(e){let t;try{t=await _k.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=$k(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function oi(e){await xe(e.file,jk(e.state))}var Zf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ok="comet-state.yaml",Hk="state.json";function ye(e,t){if(!Zf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=W.join(e.changesDir,t);if(!X(e.changesDir,i))throw new Error("Native change path escaped");return i}function Te(e,t){return W.join(ye(e,t),Ok)}function T(e,t){return W.join(Ue(e,t),Hk)}async function yr(e,t){try{let i=await wr.readFile(Te(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function we(e){return ue(e).currentBranch}async function H(e,t){return Ce(Te(e,t))}async function ne(e){let t=await Qi({file:Te(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=W.join(ye(e.paths,t.name),"verification.md");await B(e.paths.nativeRoot,i),await wr.rm(i,{force:!0})}return t}async function eh(e){let t=ye(e.paths,e.state.name),i=W.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await wr.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(!Zf.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=W.join(t,...s.split("/")),l=await wr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=W.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await wr.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function th(e){let t=ye(e.paths,e.state.name),i=await V({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await V({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Xn({briefMarkdown:i.text,specs:r})}async function ih(e){return _(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await eh({paths:e.paths,state:t}),r=await th({paths:e.paths,state:t,specChanges:i}),n=await Zi({changeDir:ye(e.paths,t.name),acceptanceIds:r.map(({id:s})=>s)});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=Mf({state:{...t,spec_changes:i},acceptance:r.map(s=>({...s}))});if(delete a.children_contract_hash,n){a.children_contract_hash=Gn({acceptance:a.acceptance,children:n.contract});let s=[...t.history].reverse().find(({outcome:c})=>c==="pass"||c==="fail");if(s?.outcome==="fail"&&s.unresolved_ids.length>0){let c=await Ct({paths:e.paths,state:a}),l=new Set((c?.children??[]).filter(({status:d})=>d!=="done").flatMap(({covers:d})=>d)),f=s.unresolved_ids.filter(d=>!l.has(d));if(f.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${f.join(", ")}`)}}let o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),U({portableState:o,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}async function ka(e){let t=await eh(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 f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await th({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!af(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Zi({changeDir:ye(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Gn({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 Ze(e){let t=await ka(e);if(!t.drifted)return;let i=t.reason??"Native confirmed requirements changed";throw await gh({paths:e.paths,state:e.state,reason:i}),new Error(`${i}; Native change returned to Shape and requires confirmation`)}async function rh(e){return _(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),await Zi({changeDir:ye(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a)})||t.children_contract_hash)throw new Error("Native parent Build advances child changes instead of a parent Builder");let r=gc({state:t,input:e.input}),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),U({portableState:n,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function nh(e){return _(e.paths,`complete portable parent Build ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.phase!=="build"||t.status!=="active")throw new Error("Native parent integration can only complete from active Build");await Ze({paths:e.paths,state:t});let i=await Ct({paths:e.paths,state:t});if(!i||!t.children_contract_hash)throw new Error(`Native change ${t.name} has no confirmed child contract`);if(!i.confirmed)throw new Error("Native parent child declarations require Shape confirmation");if(!i.allDone)throw new Error("Native parent cannot enter Verify before every child is merged");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; add and confirm a repair child");let n=fr().captureExecutionIdentity({identityProvider:"skill-coordinated",executionRef:`native-parent-integration:${ba()}`}),a=gc({state:t,input:{identity:n,summary:e.summary,addressedAcceptanceIds:t.acceptance.map(({id:s})=>s),checks:[],knownLimits:[]}}),o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),U({portableState:o,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}function Sc(e,t,i){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:ua(i,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function ah(e,t,i,r){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Sc(t,i,r),executionCount:e.executionCount}}function oh(e,t){let i=W.relative(W.resolve(e),W.resolve(t));if(W.isAbsolute(i)||i===".."||i.startsWith(`..${W.sep}`))throw new Error("Native local check cwd escaped the project root");let r=i.length===0?".":i.split(W.sep).join("/");return ua(e,r),r}function kc(e,t){let[i,...r]=e.argv;if(!i)throw new Error(`Native local check ${e.id} has no executable`);return dr({id:e.id,name:e.id,executable:i,argv:r,cwdRef:oh(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Dk(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function si(e){let t=new Map;for(let i of e.supplied){if(t.has(i.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${i.id}`);t.set(i.id,i)}return e.local.checks.map(i=>{if(i.status==="planned"||i.status==="running")throw new Error(`Native Runtime check ${i.id} has not completed`);let r=e.requestedNames?.get(i.id)??i.name;return{id:i.id,name:I(r),argv_display:dc(i.argv.slice(1)).map(n=>I(n)),argv_truncated:!1,cwd_ref:oh(e.projectRoot,i.cwd),status:i.status,exit_code:i.exitCode,duration_ms:Dk(i)}})}function Bk(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Nr(e){if(e.local===null||e.local.change!==e.state.name)return U({portableState:e.state,projectRoot:e.projectRoot,branch:we(e.projectRoot)});let t=e.local.execution?.operationId??ba();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(i=>i.status==="running"||i.status==="planned"?{...i,operationId:t,status:"interrupted"}:{...i,operationId:t})}}async function ci(e){try{let t=await qe(T(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function sh(e){let{state:t,local:i,expected:r}=e;if(t.state_version!==r.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==r.iteration||t.loop.attempt!==r.attempt||t.builder_handoff===null||i===null||i.basedOnStateVersion!==t.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return i}function Lk(e){let{state:t,local:i,envelope:r}=e;if(!fa(r))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(r.candidateId!==t.builder_handoff.candidate_id||r.identityProvider!==t.builder_handoff.identity_provider||r.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(i===null||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==null&&i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return r}function Mk(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Na(e){let t=await ci({paths:e.paths,state:e.state}),i=Gf({state:e.state,summary:e.summary}),r=await ne({paths:e.paths,previous:e.state,next:i});return await j(T(e.paths,e.state.name),Nr({local:t,state:r,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),r}function Qf(e,t,i){return e.checks.length!==t.length?!1:e.checks.every((r,n)=>kc(r,i)===dr(t[n]))}async function Fk(e){return _(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let i=T(e.paths,t.name),r=(await bc({file:i,portableState:t,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(r.execution?.stage==="checking"&&r.execution.actor==="runtime"&&Qf(r,e.plans,e.paths.projectRoot)){let o=r.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=r.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:si({local:r,projectRoot:e.paths.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=vr({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await ne({paths:e.paths,previous:t,next:c});throw await j(T(e.paths,t.name),U({portableState:l,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(r.execution!==null&&r.checks.length>0){if(!(r.execution.stage==="checking"&&r.execution.actor==="runtime"&&r.checks.some(s=>s.status==="interrupted")&&Qf(r,e.plans,e.paths.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(r.execution!==null||r.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=ba(),a={...r,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=r.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?ah(s,o,n,e.paths.projectRoot):s?{...s,operationId:n}:Sc(o,n,e.paths.projectRoot)})};return await j(i,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=r.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function wa(e){return _(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let i=T(e.paths,t.name),r=await qe(i);if(r===null||r.basedOnStateVersion!==t.state_version||r.execution?.operationId!==e.operationId||r.execution.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(r);return await j(i,n,{containedRoot:e.paths.runtimeDir}),n})}async function ch(e){if(new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let t=[],i=new Set;for(let s of e.plans){da(e.paths.projectRoot,s);let c=dr(s);i.has(c)||(i.add(c),t.push(s))}let r=await Fk({...e,plans:t});if(r.kind==="reuse")return r;let n=r.local.execution.operationId,a=Ue(e.paths,r.state.name);try{for(let s of r.plans){let c=new Date().toISOString();await wa({paths:e.paths,state:r.state,operationId:n,update:f=>({...f,checks:f.checks.map(d=>d.id===s.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:c}:d)})});let l=await fc({projectRoot:e.paths.projectRoot,runtimeDir:a,operationId:n,plan:s});await wa({paths:e.paths,state:r.state,operationId:n,update:f=>({...f,checks:f.checks.map(d=>d.id===s.id?{...d,status:l.status,exitCode:l.exitCode,startedAt:l.startedAt,completedAt:l.completedAt,log:l.logRef}:d)})})}await wa({paths:e.paths,state:r.state,operationId:n,update:s=>({...s,execution:{...s.execution,status:"completed"}})})}catch(s){try{await wa({paths:e.paths,state:r.state,operationId:n,update:c=>({...c,execution:{...c.execution,status:"interrupted"},checks:c.checks.map(l=>l.status==="planned"||l.status==="running"?{...l,status:"interrupted"}:l)})})}catch{}throw s}let o=await qe(T(e.paths,r.state.name));if(o===null)throw new Error("Native Runtime check state disappeared after execution");return{state:r.state,checks:si({local:o,projectRoot:e.paths.projectRoot,supplied:[]})}}async function Vk(e){let t=T(e.paths,e.state.name),i=e.local;if(i===null||i.change!==e.state.name||i.basedOnStateVersion!==e.state.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(i.execution.executionId!==null&&i.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(i.execution.requestCheckRounds>=mc)throw new Error(`Native Verifier request-checks exceeded ${mc} rounds for this attempt`);let r=new Map,n=new Map,a=new Map;for(let p of i.checks){let m=kc(p,e.paths.projectRoot);n.set(m,p),p.status!=="interrupted"&&r.set(m,p),a.set(p.id,m)}let o=new Map,s=new Map;for(let p of e.response.checks){let m=Bk(p);da(e.paths.projectRoot,m);let h=dr(m),v=s.get(m.id);if(v!==void 0&&v!==h)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let g=a.get(m.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,m)}let c=[...o.entries()],l=c.filter(([p])=>!r.has(p));if(i.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=i.execution.requestCheckRounds+1,d=new Map(c.map(([,p])=>[p.id,p.name])),u={...i,execution:{...i.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...i.checks.map(p=>{let m=kc(p,e.paths.projectRoot),h=o.get(m);return h&&p.status==="interrupted"?ah(p,h,i.execution.operationId,e.paths.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Sc(p,i.execution.operationId,e.paths.projectRoot))]};return await j(t,u,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:u,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,p])=>p),requestedNames:d,reusedCheckIds:c.filter(([p])=>r.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function ya(e){return _(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let i=T(e.paths,t.name),r=await qe(i),n=r?.execution;if(r===null||r.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(r);return await j(i,a,{containedRoot:e.paths.runtimeDir}),a})}async function qk(e){let t;try{for(let i of e.reservation.novelPlans){let r=new Date().toISOString();t=await ya({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:r}:o)})});let n=await fc({projectRoot:e.paths.projectRoot,runtimeDir:Ue(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:i});t=await ya({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await ya({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(i){try{await ya({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,status:"interrupted"},checks:r.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw i}return{checks:si({local:t,projectRoot:e.paths.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:i})=>i)}}}async function lh(e){return _(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=(await bc({file:T(e.paths,t.name),portableState:t,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");si({local:i,projectRoot:e.paths.projectRoot,supplied:e.checks});let r=Ff(t),n=await ne({paths:e.paths,previous:t,next:r}),a=T(e.paths,t.name),o=ba();return await j(a,{...i,basedOnStateVersion:n.state_version,execution:{operationId:o,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(s=>({...s,operationId:o}))},{containedRoot:e.paths.runtimeDir}),n})}async function uh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await _(e.paths,`apply portable verifier ${e.name}`,async()=>{let i=await H(e.paths,e.name);await Ze({paths:e.paths,state:i});let r=await ci({paths:e.paths,state:i}),n=Lk({state:i,local:r,envelope:e.envelope}),a;try{a=pc(n.payload)}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,u=await Na({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${u.loop.execution_failure_count}/${mr} was recorded`,{cause:f})}let o=Mk(a);if(o.iteration!==i.loop.iteration||o.attempt!==i.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let s=[],c;try{r!==null&&(s=si({local:r,projectRoot:e.paths.projectRoot,supplied:e.checks}));let f=Vf({state:i,envelope:n,checks:s,maxVerifyFailures:e.maxVerifyFailures});if(f.response.kind==="request-checks"){if(r===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Vk({paths:e.paths,state:i,local:r,envelope:n,response:f.response,suppliedChecks:s});return{kind:"request-checks",state:i,response:f.response,reservation:d}}if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==n.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");c=f}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,u=await Na({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${u.loop.execution_failure_count}/${mr} was recorded`,{cause:f})}let l=await ne({paths:e.paths,previous:i,next:c.state});return await j(T(e.paths,i.name),l.loop.next_action==="resolve-verifier-blocker"?Nr({local:r,state:l,projectRoot:e.paths.projectRoot}):U({portableState:l,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),l.verification!==null&&await oi({file:W.join(ye(e.paths,i.name),"verification.md"),state:l}),{kind:"final-result",result:{state:l,response:c.response,checks:s,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let i=await qk({paths:e.paths,reservation:t.reservation});return{state:t.state,response:t.response,checks:i.checks,requestChecks:i.requestChecks}}catch(i){let r=`Native Verifier response was invalid: ${i.message}`,n=await _(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Na({paths:e.paths,state:a,summary:r})});throw new Error(n?`${r}; execution error ${n.loop.execution_failure_count}/${mr} was recorded`:`${r}; the portable state changed before the execution error could be recorded`,{cause:i})}}async function dh(e){return _(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await ci({paths:e.paths,state:t});if(sh({state:t,local:i,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Na({paths:e.paths,state:t,summary:e.summary})})}async function fh(e){return _(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=await ci({paths:e.paths,state:t}),r=sh({state:t,local:i,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=si({local:r,projectRoot:e.paths.projectRoot,supplied:[]}),a=Wf({state:t,checks:n,verifierExecutionRef:r.execution.executionId,summary:e.summary}),o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),Nr({local:r,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:o}),o})}async function hh(e){return _(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=qf(t),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:r}),r})}async function ph(e){return _(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=zf({state:t,summary:e.summary}),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:r}),r})}async function mh(e){return _(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=await ci({paths:e.paths,state:t}),r=Jf(t),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),Nr({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function vh(e){return _(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await ci({paths:e.paths,state:t}),r=Uf(t),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),Nr({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Sa(e){return _(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(t.phase==="build")return t;let i=vr({state:t,reason:e.reason}),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}async function Ec(e){return _(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);return t.phase==="shape"?t:gh({paths:e.paths,state:t,reason:e.reason})})}async function gh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...he(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:I(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 ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),U({portableState:n,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ea(e){if(e.state.verification===null)return"not-applicable";let t=W.join(ye(e.paths,e.state.name),"verification.md");return await Xf({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await oi({file:t,state:e.state}),"rebuilt")}var Jk=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function Gk(e,t){let i=await hf(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function wh(e,t){await br.mkdir(e.transactionsDir,{recursive:!0}),await fe(ea(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function yh(e,t){await Promise.all([br.rm(Ue(e,t),{recursive:!0,force:!0}),br.rm(Cs(e,t),{recursive:!0,force:!0}),...Jk.map(i=>br.rm(zk.join(Fe(e,t),i),{force:!0}))])}async function Nh(e,t){await j(T(e,t.name),U({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function bh(e,t){try{let i=await sr(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 kh(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=ue(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 Uk(e){let t=Fe(e.paths,e.state.name),i=await V({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 V({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Xn({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Sh(e,t){let i=await If(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Eh(e){return _(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Gk(e.paths,e.name),i=await yr(e.paths,e.name)?await Ce(Te(e.paths,e.name)):null;if(!t&&i)return await yh(e.paths,e.name),await Nh(e.paths,i),i;let r=null,n=null;for(t||(r=await Sh(e.paths,e.name),n=await bh(e.paths,e.name),kh(e.paths,n),t={schema:Qn,id:Wk(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await wh(e.paths,t));;){let a=sf(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Sh(e.paths,e.name),n??=await bh(e.paths,e.name),kh(e.paths,n),i=of({state:r,acceptance:await Uk({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Jn(Te(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await yh(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ce(Te(e.paths,e.name)),await Nh(e.paths,i)),t={...t,status:a.nextStatus},await wh(e.paths,t)}return await br.rm(ea(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ce(Te(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Ph}from"node:fs";import xh from"node:path";function Kk(e,t){let i=ue(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 Yk(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Xk(e,t){let i=new Date().toISOString(),r=e.verification===null?e:he(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:I(t),completed_at:i});return P({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:Yk(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 Qk(e){try{let t=await qe(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 Pc(e){return _(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Ea({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=Kk(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=T(e.paths,e.name),n=await Qk(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(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await j(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Ea({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(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=vr({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Qi({file:Te(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await Ph.rm(xh.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=U({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await j(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",f=c||l;if(f){let u=Xk(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 Qi({file:Te(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let d=U({portableState:t,projectRoot:e.paths.projectRoot,branch:ue(e.paths.projectRoot).currentBranch});return await Ph.mkdir(xh.dirname(T(e.paths,t.name)),{recursive:!0}),await j(r,d,{containedRoot:e.paths.runtimeDir}),await Ea({paths:e.paths,state:t}),{state:t,local:d,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"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{randomUUID as Zk}from"node:crypto";import{promises as Rh}from"node:fs";import eS from"node:path";function Rc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $t(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function We(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Ch(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,r)=>We(i,`${t}[${r}]`))}function tS(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,i)=>{let r=Rc(t,`Native Builder check ${i}`);if($t(r,["name","result","note"],`Native Builder check ${i}`),!["passed","failed","not-run"].includes(String(r.result)))throw new Error(`Native Builder check ${i} result is invalid`);if(r.note!==null&&typeof r.note!="string")throw new Error(`Native Builder check ${i} note is invalid`);return{name:We(r.name,`Native Builder check ${i} name`),result:r.result,note:r.note}})}function iS(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,i)=>{let r=Rc(t,`Native Runtime check ${i}`);if($t(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${i}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${i} argv is invalid`);if(!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1)throw new Error(`Native Runtime check ${i} timeoutMs is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Runtime check ${i} repeatable is invalid`);return{id:We(r.id,`Native Runtime check ${i} id`),name:We(r.name,`Native Runtime check ${i} name`),executable:We(r.executable,`Native Runtime check ${i} executable`),argv:[...r.argv],cwdRef:We(r.cwdRef,`Native Runtime check ${i} cwdRef`),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function Ah(e,t){let i=e.stateVersion,r=e.iteration,n=e.attempt;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:i,iteration:r,attempt:n,verifierExecutionRef:We(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function rS(e){let t=Rc(e,"Native Runner input");if(t.kind==="builder-handoff")return $t(t,["kind","summary","addressed_acceptance_ids","checks","known_limits"],"Native Runner Builder input"),{kind:"builder-handoff",summary:We(t.summary,"Native Builder summary"),addressed_acceptance_ids:Ch(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:tS(t.checks),known_limits:Ch(t.known_limits,"Native Builder known limits")};if(t.kind==="dispatch-verifier")return $t(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:iS(t.checks)};if(t.kind==="verifier-response")return $t(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return $t(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:We(t.summary,"Native Verifier execution error summary"),...Ah(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return $t(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:We(t.summary,"Native unavailable Verifier summary"),...Ah(t,"Native Runner unavailable Verifier input")};throw new Error("Native Runner input kind is invalid")}async function Ih(e,t){let i=eS.resolve(t,e),r=await Rh.lstat(i);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Rh.readFile(i,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return rS(n)}function _h(e){return`${q}:${e}:${Zk()}`}function kr(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==q)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function nS(e){return{iteration:e.iteration,summary:e.summary,addressedAcceptanceIds:[...e.addressed_acceptance_ids],checks:e.checks.map(t=>({name:t.name,result:t.result,note:t.note})),checksTruncated:e.checks_truncated,knownLimits:e.known_limits.map(t=>({...t})),knownLimitsTruncated:e.known_limits_truncated,submittedAt:e.submitted_at}}function Th(e,t,i){let r=kr(e);return{coordination:q,change:e.name,candidateId:r.candidate_id,stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:i,briefRef:e.brief,specRefs:e.spec_changes.map(({capability:n,operation:a,source:o})=>({capability:n,operation:a,ref:o})),acceptance:e.acceptance.map(({id:n,source:a,text:o})=>({id:n,source:a,text:o})),builderHandoff:nS(r),runtimeChecks:t.map(n=>({...n}))}}async function xc(e){kr(e.state);let t=await qe(T(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function jh(e){if(e.input.kind==="builder-handoff"){let c=fr().captureExecutionIdentity({identityProvider:q,executionRef:_h("builder")}),l=await rh({paths:e.paths,name:e.name,input:{identity:c,summary:e.input.summary,addressedAcceptanceIds:e.input.addressed_acceptance_ids,checks:e.input.checks,knownLimits:e.input.known_limits}});return{state:l,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(l)}}if(e.input.kind==="dispatch-verifier"){let s=await H(e.paths,e.name);if(s.builder_handoff!==null&&s.builder_handoff.identity_provider!==q){let d=await Sa({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:d,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(d)}}kr(s);let c=await ch({paths:e.paths,name:e.name,plans:e.input.checks}),l=_h("verifier"),f=await lh({paths:e.paths,name:e.name,checks:c.checks,verifierExecutionId:l});return{state:f,checks:c.checks,requestChecks:null,verifierDispatch:Th(f,c.checks,l),continuation:me(f)}}if(e.input.kind==="verifier-execution-error"){let s=await H(e.paths,e.name);kr(s),await xc({paths:e.paths,state:s});let c=await dh({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:c,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(c)}}if(e.input.kind==="verifier-unavailable"){let s=await fh({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:s,checks:s.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:me(s)}}let t=await H(e.paths,e.name),i=kr(t),r=await xc({paths:e.paths,state:t}),n=fr(),a=n.captureExecutionIdentity({identityProvider:q,executionRef:r}),o=await uh({paths:e.paths,name:e.name,envelope:n.envelopeVerifierResponse({candidateId:i.candidate_id,identity:a,payload:e.input.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures});return{...o,verifierDispatch:o.requestChecks===null?null:Th(o.state,o.checks,await xc({paths:e.paths,state:o.state})),continuation:me(o.state)}}import _c from"path";var oS=["Outcome","Scope","Non-goals","Acceptance examples"],fI=[...oS,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var sS=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 $h=1024*1024;var Hh="scoped-text-safety",cS=1,lS=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var uS="comet.native.checker-policy.v1";var CI=te(uS,{policy:Hh,version:cS,limits:lS,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var dS=["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"],AI=new Set(dS);var pS=$h,JI=3*pS;var Dh={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:[]},vS=ge("comet-native-runtime:v3:scope-reopen"),yj=[{skillVersion:"3",skillHash:ge("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ge("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ge("comet-native-runtime:v1")}];var Lh=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Zj=new Set(Lh),SS=new Set([...Lh,"minimum_runtime_version","revision"]),e$=new Set([...SS,"operation"]),t$=512*1024,ES=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),i$=new Set([...ES,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var o$={maxAcceptanceCriteria:ir.maxCriteria};var d$={maxSpecs:64,maxFileBytes:Rn,maxTotalBytes:4*1024*1024};import{execFile as jS}from"node:child_process";import{promisify as $S}from"node:util";var b$={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var V$=512*1024;var Sr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var dO=64*1024;var fO=3600*1e3;var hO=$S(jS);var Pa=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 QO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var c0=16*1024*1024,l0=256*1024,u0=16*1024;var m0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var w0=16*1024;var _0=16*1024;var NH=16*1024*1024,xa=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"},Ra=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 Ca=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Vh=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Ac=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:Vh,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] +`}function Ok(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 Xf(e){let t;try{t=await Tk.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=Ok(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function oi(e){await xe(e.file,$k(e.state))}var Zf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hk="comet-state.yaml",Dk="state.json";function ye(e,t){if(!Zf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=W.join(e.changesDir,t);if(!X(e.changesDir,i))throw new Error("Native change path escaped");return i}function Te(e,t){return W.join(ye(e,t),Hk)}function T(e,t){return W.join(Ue(e,t),Dk)}async function yr(e,t){try{let i=await wr.readFile(Te(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function we(e){return ue(e).currentBranch}async function H(e,t){return Ce(Te(e,t))}async function ne(e){let t=await Qi({file:Te(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=W.join(ye(e.paths,t.name),"verification.md");await B(e.paths.nativeRoot,i),await wr.rm(i,{force:!0})}return t}async function eh(e){let t=ye(e.paths,e.state.name),i=W.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await wr.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(!Zf.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=W.join(t,...s.split("/")),l=await wr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=W.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await wr.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function th(e){let t=ye(e.paths,e.state.name),i=await V({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await V({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Xn({briefMarkdown:i.text,specs:r})}async function ih(e){return _(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await eh({paths:e.paths,state:t}),r=await th({paths:e.paths,state:t,specChanges:i}),n=await Zi({changeDir:ye(e.paths,t.name),acceptanceIds:r.map(({id:s})=>s)});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=Mf({state:{...t,spec_changes:i},acceptance:r.map(s=>({...s}))});if(delete a.children_contract_hash,n){a.children_contract_hash=Gn({acceptance:a.acceptance,children:n.contract});let s=[...t.history].reverse().find(({outcome:c})=>c==="pass"||c==="fail");if(s?.outcome==="fail"&&s.unresolved_ids.length>0){let c=await Ct({paths:e.paths,state:a}),l=new Set((c?.children??[]).filter(({status:d})=>d!=="done").flatMap(({covers:d})=>d)),f=s.unresolved_ids.filter(d=>!l.has(d));if(f.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${f.join(", ")}`)}}let o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),U({portableState:o,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}async function ka(e){let t=await eh(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 f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await th({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!af(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Zi({changeDir:ye(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Gn({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 Ze(e){let t=await ka(e);if(!t.drifted)return;let i=t.reason??"Native confirmed requirements changed";throw await gh({paths:e.paths,state:e.state,reason:i}),new Error(`${i}; Native change returned to Shape and requires confirmation`)}async function rh(e){return _(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),await Zi({changeDir:ye(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a)})||t.children_contract_hash)throw new Error("Native parent Build advances child changes instead of a parent Builder");let r=gc({state:t,input:e.input}),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),U({portableState:n,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function nh(e){return _(e.paths,`complete portable parent Build ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.phase!=="build"||t.status!=="active")throw new Error("Native parent integration can only complete from active Build");await Ze({paths:e.paths,state:t});let i=await Ct({paths:e.paths,state:t});if(!i||!t.children_contract_hash)throw new Error(`Native change ${t.name} has no confirmed child contract`);if(!i.confirmed)throw new Error("Native parent child declarations require Shape confirmation");if(!i.allDone)throw new Error("Native parent cannot enter Verify before every child is merged");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; add and confirm a repair child");let n=fr().captureExecutionIdentity({identityProvider:"skill-coordinated",executionRef:`native-parent-integration:${ba()}`}),a=gc({state:t,input:{identity:n,summary:e.summary,addressedAcceptanceIds:t.acceptance.map(({id:s})=>s),checks:[],knownLimits:[]}}),o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),U({portableState:o,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}function Sc(e,t,i){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:ua(i,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function ah(e,t,i,r){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Sc(t,i,r),executionCount:e.executionCount}}function oh(e,t){let i=W.relative(W.resolve(e),W.resolve(t));if(W.isAbsolute(i)||i===".."||i.startsWith(`..${W.sep}`))throw new Error("Native local check cwd escaped the project root");let r=i.length===0?".":i.split(W.sep).join("/");return ua(e,r),r}function kc(e,t){let[i,...r]=e.argv;if(!i)throw new Error(`Native local check ${e.id} has no executable`);return dr({id:e.id,name:e.id,executable:i,argv:r,cwdRef:oh(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Bk(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function si(e){let t=new Map;for(let i of e.supplied){if(t.has(i.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${i.id}`);t.set(i.id,i)}return e.local.checks.map(i=>{if(i.status==="planned"||i.status==="running")throw new Error(`Native Runtime check ${i.id} has not completed`);let r=e.requestedNames?.get(i.id)??i.name;return{id:i.id,name:I(r),argv_display:dc(i.argv.slice(1)).map(n=>I(n)),argv_truncated:!1,cwd_ref:oh(e.projectRoot,i.cwd),status:i.status,exit_code:i.exitCode,duration_ms:Bk(i)}})}function Lk(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Nr(e){if(e.local===null||e.local.change!==e.state.name)return U({portableState:e.state,projectRoot:e.projectRoot,branch:we(e.projectRoot)});let t=e.local.execution?.operationId??ba();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(i=>i.status==="running"||i.status==="planned"?{...i,operationId:t,status:"interrupted"}:{...i,operationId:t})}}async function ci(e){try{let t=await qe(T(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function sh(e){let{state:t,local:i,expected:r}=e;if(t.state_version!==r.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==r.iteration||t.loop.attempt!==r.attempt||t.builder_handoff===null||i===null||i.basedOnStateVersion!==t.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return i}function Mk(e){let{state:t,local:i,envelope:r}=e;if(!fa(r))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(r.candidateId!==t.builder_handoff.candidate_id||r.identityProvider!==t.builder_handoff.identity_provider||r.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(i===null||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==null&&i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return r}function Fk(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Na(e){let t=await ci({paths:e.paths,state:e.state}),i=Gf({state:e.state,summary:e.summary}),r=await ne({paths:e.paths,previous:e.state,next:i});return await j(T(e.paths,e.state.name),Nr({local:t,state:r,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),r}function Qf(e,t,i){return e.checks.length!==t.length?!1:e.checks.every((r,n)=>kc(r,i)===dr(t[n]))}async function Vk(e){return _(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let i=T(e.paths,t.name),r=(await bc({file:i,portableState:t,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(r.execution?.stage==="checking"&&r.execution.actor==="runtime"&&Qf(r,e.plans,e.paths.projectRoot)){let o=r.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=r.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:si({local:r,projectRoot:e.paths.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=vr({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await ne({paths:e.paths,previous:t,next:c});throw await j(T(e.paths,t.name),U({portableState:l,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(r.execution!==null&&r.checks.length>0){if(!(r.execution.stage==="checking"&&r.execution.actor==="runtime"&&r.checks.some(s=>s.status==="interrupted")&&Qf(r,e.plans,e.paths.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(r.execution!==null||r.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=ba(),a={...r,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=r.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?ah(s,o,n,e.paths.projectRoot):s?{...s,operationId:n}:Sc(o,n,e.paths.projectRoot)})};return await j(i,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=r.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function wa(e){return _(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let i=T(e.paths,t.name),r=await qe(i);if(r===null||r.basedOnStateVersion!==t.state_version||r.execution?.operationId!==e.operationId||r.execution.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(r);return await j(i,n,{containedRoot:e.paths.runtimeDir}),n})}async function ch(e){if(new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let t=[],i=new Set;for(let s of e.plans){da(e.paths.projectRoot,s);let c=dr(s);i.has(c)||(i.add(c),t.push(s))}let r=await Vk({...e,plans:t});if(r.kind==="reuse")return r;let n=r.local.execution.operationId,a=Ue(e.paths,r.state.name);try{for(let s of r.plans){let c=new Date().toISOString();await wa({paths:e.paths,state:r.state,operationId:n,update:f=>({...f,checks:f.checks.map(d=>d.id===s.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:c}:d)})});let l=await fc({projectRoot:e.paths.projectRoot,runtimeDir:a,operationId:n,plan:s});await wa({paths:e.paths,state:r.state,operationId:n,update:f=>({...f,checks:f.checks.map(d=>d.id===s.id?{...d,status:l.status,exitCode:l.exitCode,startedAt:l.startedAt,completedAt:l.completedAt,log:l.logRef}:d)})})}await wa({paths:e.paths,state:r.state,operationId:n,update:s=>({...s,execution:{...s.execution,status:"completed"}})})}catch(s){try{await wa({paths:e.paths,state:r.state,operationId:n,update:c=>({...c,execution:{...c.execution,status:"interrupted"},checks:c.checks.map(l=>l.status==="planned"||l.status==="running"?{...l,status:"interrupted"}:l)})})}catch{}throw s}let o=await qe(T(e.paths,r.state.name));if(o===null)throw new Error("Native Runtime check state disappeared after execution");return{state:r.state,checks:si({local:o,projectRoot:e.paths.projectRoot,supplied:[]})}}async function qk(e){let t=T(e.paths,e.state.name),i=e.local;if(i===null||i.change!==e.state.name||i.basedOnStateVersion!==e.state.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(i.execution.executionId!==null&&i.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(i.execution.requestCheckRounds>=mc)throw new Error(`Native Verifier request-checks exceeded ${mc} rounds for this attempt`);let r=new Map,n=new Map,a=new Map;for(let p of i.checks){let m=kc(p,e.paths.projectRoot);n.set(m,p),p.status!=="interrupted"&&r.set(m,p),a.set(p.id,m)}let o=new Map,s=new Map;for(let p of e.response.checks){let m=Lk(p);da(e.paths.projectRoot,m);let h=dr(m),v=s.get(m.id);if(v!==void 0&&v!==h)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let g=a.get(m.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,m)}let c=[...o.entries()],l=c.filter(([p])=>!r.has(p));if(i.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=i.execution.requestCheckRounds+1,d=new Map(c.map(([,p])=>[p.id,p.name])),u={...i,execution:{...i.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...i.checks.map(p=>{let m=kc(p,e.paths.projectRoot),h=o.get(m);return h&&p.status==="interrupted"?ah(p,h,i.execution.operationId,e.paths.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Sc(p,i.execution.operationId,e.paths.projectRoot))]};return await j(t,u,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:u,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,p])=>p),requestedNames:d,reusedCheckIds:c.filter(([p])=>r.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function ya(e){return _(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let i=T(e.paths,t.name),r=await qe(i),n=r?.execution;if(r===null||r.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(r);return await j(i,a,{containedRoot:e.paths.runtimeDir}),a})}async function Wk(e){let t;try{for(let i of e.reservation.novelPlans){let r=new Date().toISOString();t=await ya({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:r}:o)})});let n=await fc({projectRoot:e.paths.projectRoot,runtimeDir:Ue(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:i});t=await ya({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await ya({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(i){try{await ya({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,status:"interrupted"},checks:r.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw i}return{checks:si({local:t,projectRoot:e.paths.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:i})=>i)}}}async function lh(e){return _(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=(await bc({file:T(e.paths,t.name),portableState:t,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");si({local:i,projectRoot:e.paths.projectRoot,supplied:e.checks});let r=Ff(t),n=await ne({paths:e.paths,previous:t,next:r}),a=T(e.paths,t.name),o=ba();return await j(a,{...i,basedOnStateVersion:n.state_version,execution:{operationId:o,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(s=>({...s,operationId:o}))},{containedRoot:e.paths.runtimeDir}),n})}async function uh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await _(e.paths,`apply portable verifier ${e.name}`,async()=>{let i=await H(e.paths,e.name);await Ze({paths:e.paths,state:i});let r=await ci({paths:e.paths,state:i}),n=Mk({state:i,local:r,envelope:e.envelope}),a;try{a=pc(n.payload)}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,u=await Na({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${u.loop.execution_failure_count}/${mr} was recorded`,{cause:f})}let o=Fk(a);if(o.iteration!==i.loop.iteration||o.attempt!==i.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let s=[],c;try{r!==null&&(s=si({local:r,projectRoot:e.paths.projectRoot,supplied:e.checks}));let f=Vf({state:i,envelope:n,checks:s,maxVerifyFailures:e.maxVerifyFailures});if(f.response.kind==="request-checks"){if(r===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await qk({paths:e.paths,state:i,local:r,envelope:n,response:f.response,suppliedChecks:s});return{kind:"request-checks",state:i,response:f.response,reservation:d}}if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==n.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");c=f}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,u=await Na({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${u.loop.execution_failure_count}/${mr} was recorded`,{cause:f})}let l=await ne({paths:e.paths,previous:i,next:c.state});return await j(T(e.paths,i.name),l.loop.next_action==="resolve-verifier-blocker"?Nr({local:r,state:l,projectRoot:e.paths.projectRoot}):U({portableState:l,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),l.verification!==null&&await oi({file:W.join(ye(e.paths,i.name),"verification.md"),state:l}),{kind:"final-result",result:{state:l,response:c.response,checks:s,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let i=await Wk({paths:e.paths,reservation:t.reservation});return{state:t.state,response:t.response,checks:i.checks,requestChecks:i.requestChecks}}catch(i){let r=`Native Verifier response was invalid: ${i.message}`,n=await _(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Na({paths:e.paths,state:a,summary:r})});throw new Error(n?`${r}; execution error ${n.loop.execution_failure_count}/${mr} was recorded`:`${r}; the portable state changed before the execution error could be recorded`,{cause:i})}}async function dh(e){return _(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await ci({paths:e.paths,state:t});if(sh({state:t,local:i,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Na({paths:e.paths,state:t,summary:e.summary})})}async function fh(e){return _(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=await ci({paths:e.paths,state:t}),r=sh({state:t,local:i,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=si({local:r,projectRoot:e.paths.projectRoot,supplied:[]}),a=Wf({state:t,checks:n,verifierExecutionRef:r.execution.executionId,summary:e.summary}),o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),Nr({local:r,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:o}),o})}async function hh(e){return _(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=qf(t),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:r}),r})}async function ph(e){return _(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=zf({state:t,summary:e.summary}),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:r}),r})}async function mh(e){return _(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=await ci({paths:e.paths,state:t}),r=Jf(t),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),Nr({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function vh(e){return _(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await ci({paths:e.paths,state:t}),r=Uf(t),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),Nr({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Sa(e){return _(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(t.phase==="build")return t;let i=vr({state:t,reason:e.reason}),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}async function Ec(e){return _(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);return t.phase==="shape"?t:gh({paths:e.paths,state:t,reason:e.reason})})}async function gh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...he(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:I(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 ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),U({portableState:n,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ea(e){if(e.state.verification===null)return"not-applicable";let t=W.join(ye(e.paths,e.state.name),"verification.md");return await Xf({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await oi({file:t,state:e.state}),"rebuilt")}var wh=["evidence.md","repair.md","archive.md","checkpoint.md"],Gk="verification.md";async function Uk(e,t){let i=await hf(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function yh(e,t){await br.mkdir(e.transactionsDir,{recursive:!0}),await fe(ea(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Nh(e,t,i={}){let r=i.removeVerificationReport===!1?wh:[...wh,Gk];await Promise.all([br.rm(Ue(e,t),{recursive:!0,force:!0}),br.rm(Cs(e,t),{recursive:!0,force:!0}),...r.map(n=>br.rm(Jk.join(Fe(e,t),n),{force:!0}))])}async function bh(e,t){await j(T(e,t.name),U({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function kh(e,t){try{let i=await sr(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 Sh(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=ue(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 Kk(e){let t=Fe(e.paths,e.state.name),i=await V({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 V({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Xn({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Eh(e,t){let i=await If(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Ph(e){return _(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Uk(e.paths,e.name),i=await yr(e.paths,e.name)?await Ce(Te(e.paths,e.name)):null;if(!t&&i)return await Nh(e.paths,e.name,{removeVerificationReport:!1}),await bh(e.paths,i),i;let r=null,n=null;for(t||(r=await Eh(e.paths,e.name),n=await kh(e.paths,e.name),Sh(e.paths,n),t={schema:Qn,id:zk(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await yh(e.paths,t));;){let a=sf(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Eh(e.paths,e.name),n??=await kh(e.paths,e.name),Sh(e.paths,n),i=of({state:r,acceptance:await Kk({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Jn(Te(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Nh(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ce(Te(e.paths,e.name)),await bh(e.paths,i)),t={...t,status:a.nextStatus},await yh(e.paths,t)}return await br.rm(ea(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ce(Te(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as xh}from"node:fs";import Rh from"node:path";function Yk(e,t){let i=ue(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 Xk(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Qk(e,t){let i=new Date().toISOString(),r=e.verification===null?e:he(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:I(t),completed_at:i});return P({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:Xk(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 Zk(e){try{let t=await qe(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 Pc(e){return _(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Ea({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=Yk(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=T(e.paths,e.name),n=await Zk(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(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await j(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Ea({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(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=vr({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Qi({file:Te(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await xh.rm(Rh.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=U({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await j(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",f=c||l;if(f){let u=Qk(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 Qi({file:Te(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let d=U({portableState:t,projectRoot:e.paths.projectRoot,branch:ue(e.paths.projectRoot).currentBranch});return await xh.mkdir(Rh.dirname(T(e.paths,t.name)),{recursive:!0}),await j(r,d,{containedRoot:e.paths.runtimeDir}),await Ea({paths:e.paths,state:t}),{state:t,local:d,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"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{randomUUID as eS}from"node:crypto";import{promises as Ch}from"node:fs";import tS from"node:path";function Rc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $t(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function We(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Ah(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,r)=>We(i,`${t}[${r}]`))}function iS(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,i)=>{let r=Rc(t,`Native Builder check ${i}`);if($t(r,["name","result","note"],`Native Builder check ${i}`),!["passed","failed","not-run"].includes(String(r.result)))throw new Error(`Native Builder check ${i} result is invalid`);if(r.note!==null&&typeof r.note!="string")throw new Error(`Native Builder check ${i} note is invalid`);return{name:We(r.name,`Native Builder check ${i} name`),result:r.result,note:r.note}})}function rS(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,i)=>{let r=Rc(t,`Native Runtime check ${i}`);if($t(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${i}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${i} argv is invalid`);if(!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1)throw new Error(`Native Runtime check ${i} timeoutMs is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Runtime check ${i} repeatable is invalid`);return{id:We(r.id,`Native Runtime check ${i} id`),name:We(r.name,`Native Runtime check ${i} name`),executable:We(r.executable,`Native Runtime check ${i} executable`),argv:[...r.argv],cwdRef:We(r.cwdRef,`Native Runtime check ${i} cwdRef`),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function _h(e,t){let i=e.stateVersion,r=e.iteration,n=e.attempt;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:i,iteration:r,attempt:n,verifierExecutionRef:We(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function nS(e){let t=Rc(e,"Native Runner input");if(t.kind==="builder-handoff")return $t(t,["kind","summary","addressed_acceptance_ids","checks","known_limits"],"Native Runner Builder input"),{kind:"builder-handoff",summary:We(t.summary,"Native Builder summary"),addressed_acceptance_ids:Ah(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:iS(t.checks),known_limits:Ah(t.known_limits,"Native Builder known limits")};if(t.kind==="dispatch-verifier")return $t(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:rS(t.checks)};if(t.kind==="verifier-response")return $t(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return $t(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:We(t.summary,"Native Verifier execution error summary"),..._h(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return $t(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:We(t.summary,"Native unavailable Verifier summary"),..._h(t,"Native Runner unavailable Verifier input")};throw new Error("Native Runner input kind is invalid")}async function jh(e,t){let i=tS.resolve(t,e),r=await Ch.lstat(i);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Ch.readFile(i,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return nS(n)}function Th(e){return`${q}:${e}:${eS()}`}function kr(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==q)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function aS(e){return{iteration:e.iteration,summary:e.summary,addressedAcceptanceIds:[...e.addressed_acceptance_ids],checks:e.checks.map(t=>({name:t.name,result:t.result,note:t.note})),checksTruncated:e.checks_truncated,knownLimits:e.known_limits.map(t=>({...t})),knownLimitsTruncated:e.known_limits_truncated,submittedAt:e.submitted_at}}function Ih(e,t,i){let r=kr(e);return{coordination:q,change:e.name,candidateId:r.candidate_id,stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:i,briefRef:e.brief,specRefs:e.spec_changes.map(({capability:n,operation:a,source:o})=>({capability:n,operation:a,ref:o})),acceptance:e.acceptance.map(({id:n,source:a,text:o})=>({id:n,source:a,text:o})),builderHandoff:aS(r),runtimeChecks:t.map(n=>({...n}))}}async function xc(e){kr(e.state);let t=await qe(T(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function $h(e){if(e.input.kind==="builder-handoff"){let c=fr().captureExecutionIdentity({identityProvider:q,executionRef:Th("builder")}),l=await rh({paths:e.paths,name:e.name,input:{identity:c,summary:e.input.summary,addressedAcceptanceIds:e.input.addressed_acceptance_ids,checks:e.input.checks,knownLimits:e.input.known_limits}});return{state:l,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(l)}}if(e.input.kind==="dispatch-verifier"){let s=await H(e.paths,e.name);if(s.builder_handoff!==null&&s.builder_handoff.identity_provider!==q){let d=await Sa({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:d,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(d)}}kr(s);let c=await ch({paths:e.paths,name:e.name,plans:e.input.checks}),l=Th("verifier"),f=await lh({paths:e.paths,name:e.name,checks:c.checks,verifierExecutionId:l});return{state:f,checks:c.checks,requestChecks:null,verifierDispatch:Ih(f,c.checks,l),continuation:me(f)}}if(e.input.kind==="verifier-execution-error"){let s=await H(e.paths,e.name);kr(s),await xc({paths:e.paths,state:s});let c=await dh({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:c,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(c)}}if(e.input.kind==="verifier-unavailable"){let s=await fh({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:s,checks:s.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:me(s)}}let t=await H(e.paths,e.name),i=kr(t),r=await xc({paths:e.paths,state:t}),n=fr(),a=n.captureExecutionIdentity({identityProvider:q,executionRef:r}),o=await uh({paths:e.paths,name:e.name,envelope:n.envelopeVerifierResponse({candidateId:i.candidate_id,identity:a,payload:e.input.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures});return{...o,verifierDispatch:o.requestChecks===null?null:Ih(o.state,o.checks,await xc({paths:e.paths,state:o.state})),continuation:me(o.state)}}import _c from"path";var sS=["Outcome","Scope","Non-goals","Acceptance examples"],hI=[...sS,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var cS=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 Dh="scoped-text-safety",lS=1,uS=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var dS="comet.native.checker-policy.v1";var AI=te(dS,{policy:Dh,version:lS,limits:uS,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var fS=["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"],_I=new Set(fS);var mS=Oh,GI=3*mS;var Bh={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:[]},gS=ge("comet-native-runtime:v3:scope-reopen"),Nj=[{skillVersion:"3",skillHash:ge("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ge("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ge("comet-native-runtime:v1")}];var Mh=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],e$=new Set(Mh),ES=new Set([...Mh,"minimum_runtime_version","revision"]),t$=new Set([...ES,"operation"]),i$=512*1024,PS=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),r$=new Set([...PS,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var s$={maxAcceptanceCriteria:ir.maxCriteria};var f$={maxSpecs:64,maxFileBytes:Rn,maxTotalBytes:4*1024*1024};import{execFile as $S}from"node:child_process";import{promisify as OS}from"node:util";var k$={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var q$=512*1024;var Sr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var fO=64*1024;var hO=3600*1e3;var pO=OS($S);var Pa=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 ZO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var l0=16*1024*1024,u0=256*1024,d0=16*1024;var v0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var y0=16*1024;var T0=16*1024;var bH=16*1024*1024,xa=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"},Ra=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 Ca=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var qh=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Ac=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:qh,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] comet native next --runner-input `,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 Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--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.","--runner-input 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 "Implementation changed" --return-to-build','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 "]},archive:{usage:`comet native archive --dry-run [--finish merge|push|pull-request|keep] comet native archive [--confirmed] [--serial-first ]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first During execution only, confirm that this change archives before detected capability peers; the value must equal .","--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 [] [--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 Cc(e,t){return`${e}: ${t.map(i=>` ${i}`).join(` -`)}`}function MS(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Ac[i]||t.length>1&&Ac[t[0]]?.subcommands?i:t[0]}function FS(e=[]){let t=MS(e),i=Ac[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Cc("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Vh];return n&&n.length>0&&r.push("",Cc("Options",n)),r.push("",`Output: +`)}`}function FS(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Ac[i]||t.length>1&&Ac[t[0]]?.subcommands?i:t[0]}function VS(e=[]){let t=FS(e),i=Ac[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Cc("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...qh];return n&&n.length>0&&r.push("",Cc("Options",n)),r.push("",`Output: ${i.output}`),i.examples&&r.push("",Cc("Examples",i.examples)),t===""&&r.push("","Run `comet native --help` for command-specific details."),{topic:t,usage:`${r.join(` `)} -`}}var VS=FS().usage;var VH=10*1024*1024,Y=class extends Error{};function Ot(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Y(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Er(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Y(`${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 Y(`${t} requires a value`);return e.splice(r,2),n}function Wh(e){if(e.length>0)throw new Y(`Unexpected argument: ${e[0]}`)}function zh(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Y(`${t} is required`);return i}function qh(e,t){let i=_c.normalize(e),r=_c.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function qS(e){let t=_c.resolve(e),i=ue(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=ue(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!qh(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||qh(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function Jh(e){return e?qS(e):Ln(process.cwd())}async function Gh(e){let t=await $d({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function et(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` -`}}function Uh(e,t){if(t instanceof Y)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof xa)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 Ra)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof sa)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 cr)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 Ca)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ca)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 Pa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Sr)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 Kh(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` -`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function ui(e,t){let i=await Ct({paths:e,state:t});return{...i?{children:i.children,readyChildren:i.readyChildren}:{},continuation:me(t,i)}}async function Yh(e,t){let i=zh(e,"change name"),r=Er(e,"--summary"),n=Er(e,"--runner-input"),a=Ot(e,"--confirmed"),o=Ot(e,"--return-to-build"),s=Ot(e,"--retry-verifier"),c=Ot(e,"--resolve-verifier-blocker");if([a,o,s,c].filter(Boolean).length>1)throw new Y("--confirmed, --return-to-build, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");Wh(e);let l=await Gh(t);if(!await yr(l.paths,i)){if(n)throw new Y("--runner-input is only valid for portable Native changes");if(!r)throw new Y("--summary is required");let p=await Eh({paths:l.paths,name:i});return et("next",{state:p,migration:{completed:!0,summary:r},continuation:me(p)})}if(n){if(r||a||o||s||c)throw new Y("--runner-input cannot be combined with --summary or Agent transition flags");let p=await Pc({paths:l.paths,name:i,preserveRunningExecution:!0}),m=p.state;if(p.action==="await-user"||p.action==="done"||p.reason!=="available")return et("next",{state:m,recovery:p,...await ui(l.paths,m)});if(m.phase==="build"){let g=await ka({paths:l.paths,state:m});if(g.drifted){let w=await Ec({paths:l.paths,name:i,reason:g.reason??"Native confirmed requirements changed"});return et("next",{state:w,...await ui(l.paths,w)})}if(await Ct({paths:l.paths,state:m}))throw new Y("Native parent Build advances child changes and does not accept a Builder handoff")}let h=await Ih(n,t),v=await jh({paths:l.paths,name:i,input:h,maxVerifyFailures:l.config.native.max_verify_failures});return et("next",{...v,...await ui(l.paths,v.state),coordination:q})}let f=await Pc({paths:l.paths,name:i}),d=f.state;if(!r)throw new Y("--summary is required");let u;if(a)if(d.phase==="shape")u=await ih({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-skill-coordinated-pass")u=await hh({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-verifier-unavailable")u=await ph({paths:l.paths,name:i,summary:r});else throw new Y("--confirmed is only valid in Shape, for an accepted Skill-coordinated pass, or for a user-accepted degraded verification fallback");else if(o)u=await Sa({paths:l.paths,name:i,reason:r});else if(s)u=await vh({paths:l.paths,name:i});else if(c)u=await mh({paths:l.paths,name:i});else{if(f.reason!=="available")return et("next",{state:d,recovery:f,...await ui(l.paths,d)});if(d.phase==="build"){let p=await ka({paths:l.paths,state:d});if(p.drifted)u=await Ec({paths:l.paths,name:i,reason:p.reason??"Native confirmed requirements changed"});else{let m=await Ct({paths:l.paths,state:d});if(m)if(m.allDone&&!(d.loop.stage==="repairing"&&d.verification_result==="fail"))u=await nh({paths:l.paths,name:i,summary:r});else return et("next",{state:d,children:m.children,readyChildren:m.readyChildren,continuation:me(d,m)})}}return u?et("next",{state:u,...await ui(l.paths,u)}):{command:"next",exitCode:65,data:{state:d,continuation:me(d)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return et("next",{state:u,...await ui(l.paths,u)})}function WS(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}})+` -`}}async function Xh(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{Ot(n,"--json"),s=Er(n,"--project-root");let f=[...n,...a],d=await Jh(s);c=await t(f,d)}catch(f){c=Uh(e,f)}let l=o?WS(c):Kh(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` +`}}var qS=VS().usage;var qH=10*1024*1024,Y=class extends Error{};function Ot(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Y(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Er(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Y(`${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 Y(`${t} requires a value`);return e.splice(r,2),n}function zh(e){if(e.length>0)throw new Y(`Unexpected argument: ${e[0]}`)}function Jh(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Y(`${t} is required`);return i}function Wh(e,t){let i=_c.normalize(e),r=_c.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function WS(e){let t=_c.resolve(e),i=ue(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=ue(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Wh(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Wh(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function Gh(e){return e?WS(e):Ln(process.cwd())}async function Uh(e){let t=await $d({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function et(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` +`}}function Kh(e,t){if(t instanceof Y)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof xa)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 Ra)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof sa)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 cr)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 Ca)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ca)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 Pa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Sr)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 Yh(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` +`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function ui(e,t){let i=await Ct({paths:e,state:t});return{...i?{children:i.children,readyChildren:i.readyChildren}:{},continuation:me(t,i)}}async function Xh(e,t){let i=Jh(e,"change name"),r=Er(e,"--summary"),n=Er(e,"--runner-input"),a=Ot(e,"--confirmed"),o=Ot(e,"--return-to-build"),s=Ot(e,"--retry-verifier"),c=Ot(e,"--resolve-verifier-blocker");if([a,o,s,c].filter(Boolean).length>1)throw new Y("--confirmed, --return-to-build, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");zh(e);let l=await Uh(t);if(!await yr(l.paths,i)){if(n)throw new Y("--runner-input is only valid for portable Native changes");if(!r)throw new Y("--summary is required");let p=await Ph({paths:l.paths,name:i});return et("next",{state:p,migration:{completed:!0,summary:r},continuation:me(p)})}if(n){if(r||a||o||s||c)throw new Y("--runner-input cannot be combined with --summary or Agent transition flags");let p=await Pc({paths:l.paths,name:i,preserveRunningExecution:!0}),m=p.state;if(p.action==="await-user"||p.action==="done"||p.reason!=="available")return et("next",{state:m,recovery:p,...await ui(l.paths,m)});if(m.phase==="build"){let g=await ka({paths:l.paths,state:m});if(g.drifted){let w=await Ec({paths:l.paths,name:i,reason:g.reason??"Native confirmed requirements changed"});return et("next",{state:w,...await ui(l.paths,w)})}if(await Ct({paths:l.paths,state:m}))throw new Y("Native parent Build advances child changes and does not accept a Builder handoff")}let h=await jh(n,t),v=await $h({paths:l.paths,name:i,input:h,maxVerifyFailures:l.config.native.max_verify_failures});return et("next",{...v,...await ui(l.paths,v.state),coordination:q})}let f=await Pc({paths:l.paths,name:i}),d=f.state;if(!r)throw new Y("--summary is required");let u;if(a)if(d.phase==="shape")u=await ih({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-skill-coordinated-pass")u=await hh({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-verifier-unavailable")u=await ph({paths:l.paths,name:i,summary:r});else throw new Y("--confirmed is only valid in Shape, for an accepted Skill-coordinated pass, or for a user-accepted degraded verification fallback");else if(o)u=await Sa({paths:l.paths,name:i,reason:r});else if(s)u=await vh({paths:l.paths,name:i});else if(c)u=await mh({paths:l.paths,name:i});else{if(f.reason!=="available")return et("next",{state:d,recovery:f,...await ui(l.paths,d)});if(d.phase==="build"){let p=await ka({paths:l.paths,state:d});if(p.drifted)u=await Ec({paths:l.paths,name:i,reason:p.reason??"Native confirmed requirements changed"});else{let m=await Ct({paths:l.paths,state:d});if(m)if(m.allDone&&!(d.loop.stage==="repairing"&&d.verification_result==="fail"))u=await nh({paths:l.paths,name:i,summary:r});else return et("next",{state:d,children:m.children,readyChildren:m.readyChildren,continuation:me(d,m)})}}return u?et("next",{state:u,...await ui(l.paths,u)}):{command:"next",exitCode:65,data:{state:d,continuation:me(d)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return et("next",{state:u,...await ui(l.paths,u)})}function zS(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}})+` +`}}async function Qh(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{Ot(n,"--json"),s=Er(n,"--project-root");let f=[...n,...a],d=await Gh(s);c=await t(f,d)}catch(f){c=Kh(e,f)}let l=o?zS(c):Yh(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` `)?"":` -`)),l.exitCode}process.exitCode=await Xh("next",Yh); +`)),l.exitCode}process.exitCode=await Qh("next",Xh); diff --git a/assets/skills/comet-native/scripts/comet-native-runtime.mjs b/assets/skills/comet-native/scripts/comet-native-runtime.mjs index e3ace3adb..2d2cea3bb 100644 --- a/assets/skills/comet-native/scripts/comet-native-runtime.mjs +++ b/assets/skills/comet-native/scripts/comet-native-runtime.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var jC=Object.create;var cg=Object.defineProperty;var $C=Object.getOwnPropertyDescriptor;var OC=Object.getOwnPropertyNames;var HC=Object.getPrototypeOf,DC=Object.prototype.hasOwnProperty;var zc=(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 C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var FC=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of OC(t))!DC.call(e,n)&&n!==i&&cg(e,n,{get:()=>t[n],enumerable:!(r=$C(t,n))||r.enumerable});return e};var ma=(e,t,i)=>(i=e!=null?jC(HC(e)):{},FC(t||!e||!e.__esModule?cg(i,"default",{value:e,enumerable:!0}):i,e));var Q=C(Xe=>{"use strict";var vf=Symbol.for("yaml.alias"),pg=Symbol.for("yaml.document"),Uc=Symbol.for("yaml.map"),mg=Symbol.for("yaml.pair"),gf=Symbol.for("yaml.scalar"),Kc=Symbol.for("yaml.seq"),ar=Symbol.for("yaml.node.type"),ex=e=>!!e&&typeof e=="object"&&e[ar]===vf,tx=e=>!!e&&typeof e=="object"&&e[ar]===pg,ix=e=>!!e&&typeof e=="object"&&e[ar]===Uc,rx=e=>!!e&&typeof e=="object"&&e[ar]===mg,vg=e=>!!e&&typeof e=="object"&&e[ar]===gf,nx=e=>!!e&&typeof e=="object"&&e[ar]===Kc;function gg(e){if(e&&typeof e=="object")switch(e[ar]){case Uc:case Kc:return!0}return!1}function ax(e){if(e&&typeof e=="object")switch(e[ar]){case vf:case Uc:case gf:case Kc:return!0}return!1}var ox=e=>(vg(e)||gg(e))&&!!e.anchor;Xe.ALIAS=vf;Xe.DOC=pg;Xe.MAP=Uc;Xe.NODE_TYPE=ar;Xe.PAIR=mg;Xe.SCALAR=gf;Xe.SEQ=Kc;Xe.hasAnchor=ox;Xe.isAlias=ex;Xe.isCollection=gg;Xe.isDocument=tx;Xe.isMap=ix;Xe.isNode=ax;Xe.isPair=rx;Xe.isScalar=vg;Xe.isSeq=nx});var Oo=C(wf=>{"use strict";var qe=Q(),xt=Symbol("break visit"),wg=Symbol("skip children"),Di=Symbol("remove node");function Yc(e,t){let i=yg(t);qe.isDocument(e)?va(null,e.contents,i,Object.freeze([e]))===Di&&(e.contents=null):va(null,e,i,Object.freeze([]))}Yc.BREAK=xt;Yc.SKIP=wg;Yc.REMOVE=Di;function va(e,t,i,r){let n=Ng(e,t,i,r);if(qe.isNode(n)||qe.isPair(n))return bg(e,r,n),va(e,n,i,r);if(typeof n!="symbol"){if(qe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var kg=Q(),sx=Oo(),cx={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},lx=e=>e.replace(/[!,[\]{}]/g,t=>cx[t]),Ho=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+lx(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&&kg.isNode(t.contents)){let a={};sx.visit(t.contents,(o,s)=>{kg.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(` -`)}};Ho.defaultYaml={explicit:!1,version:"1.2"};Ho.defaultTags={"!!":"tag:yaml.org,2002:"};Sg.Directives=Ho});var Qc=C(Do=>{"use strict";var Eg=Q(),ux=Oo();function dx(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 Pg(e){let t=new Set;return ux.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Rg(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function fx(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Pg(e));let o=Rg(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Eg.isScalar(o.node)||Eg.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}}Do.anchorIsValid=dx;Do.anchorNames=Pg;Do.createNodeAnchors=fx;Do.findNewAnchor=Rg});var Nf=C(Cg=>{"use strict";function Fo(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var hx=Q();function xg(e,t,i){if(Array.isArray(e))return e.map((r,n)=>xg(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!hx.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}Ag.toJS=xg});var Zc=C(Tg=>{"use strict";var px=Nf(),_g=Q(),mx=Ar(),bf=class{constructor(t){Object.defineProperty(this,_g.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(!_g.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=mx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?px.applyReviver(a,{"":s},"",s):s}};Tg.NodeBase=bf});var Mo=C(Ig=>{"use strict";var vx=Qc(),gx=Oo(),wa=Q(),wx=Zc(),yx=Ar(),kf=class extends wx.NodeBase{constructor(t){super(wa.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=[],gx.visit(t,{Node:(a,o)=>{(wa.isAlias(o)||wa.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||(yx.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=el(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(vx.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 el(e,t,i){if(wa.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(wa.isCollection(t)){let r=0;for(let n of t.items){let a=el(e,n,i);a>r&&(r=a)}return r}else if(wa.isPair(t)){let r=el(e,t.key,i),n=el(e,t.value,i);return Math.max(r,n)}return 1}Ig.Alias=kf});var De=C(Sf=>{"use strict";var Nx=Q(),bx=Zc(),kx=Ar(),Sx=e=>!e||typeof e!="function"&&typeof e!="object",_r=class extends bx.NodeBase{constructor(t){super(Nx.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:kx.toJS(this.value,t,i)}toString(){return String(this.value)}};_r.BLOCK_FOLDED="BLOCK_FOLDED";_r.BLOCK_LITERAL="BLOCK_LITERAL";_r.PLAIN="PLAIN";_r.QUOTE_DOUBLE="QUOTE_DOUBLE";_r.QUOTE_SINGLE="QUOTE_SINGLE";Sf.Scalar=_r;Sf.isScalarValue=Sx});var Bo=C($g=>{"use strict";var Ex=Mo(),En=Q(),jg=De(),Px="tag:yaml.org,2002:";function Rx(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 Cx(e,t,i){if(En.isDocument(e)&&(e=e.contents),En.isNode(e))return e;if(En.isPair(e)){let d=i.schema[En.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 Ex.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Px+t.slice(2));let l=Rx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new jg.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[En.MAP]:Symbol.iterator in Object(e)?o[En.SEQ]:o[En.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 jg.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}$g.createNode=Cx});var il=C(tl=>{"use strict";var xx=Bo(),Fi=Q(),Ax=Zc();function Ef(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 xx.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 Og=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Pf=class extends Ax.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=>Fi.isNode(r)||Fi.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Og(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Fi.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ef(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(Fi.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&&Fi.isScalar(a)?a.value:a:Fi.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Fi.isPair(i))return!1;let r=i.value;return r==null||t&&Fi.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 Fi.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(Fi.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ef(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};tl.Collection=Pf;tl.collectionFromPath=Ef;tl.isEmptyPath=Og});var Lo=C(rl=>{"use strict";var _x=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Rf(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Tx=(e,t,i)=>e.endsWith(` +var $C=Object.create;var lg=Object.defineProperty;var OC=Object.getOwnPropertyDescriptor;var HC=Object.getOwnPropertyNames;var DC=Object.getPrototypeOf,FC=Object.prototype.hasOwnProperty;var zc=(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 C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var MC=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of HC(t))!FC.call(e,n)&&n!==i&&lg(e,n,{get:()=>t[n],enumerable:!(r=OC(t,n))||r.enumerable});return e};var ma=(e,t,i)=>(i=e!=null?$C(DC(e)):{},MC(t||!e||!e.__esModule?lg(i,"default",{value:e,enumerable:!0}):i,e));var Q=C(Xe=>{"use strict";var vf=Symbol.for("yaml.alias"),mg=Symbol.for("yaml.document"),Uc=Symbol.for("yaml.map"),vg=Symbol.for("yaml.pair"),gf=Symbol.for("yaml.scalar"),Kc=Symbol.for("yaml.seq"),ar=Symbol.for("yaml.node.type"),tx=e=>!!e&&typeof e=="object"&&e[ar]===vf,ix=e=>!!e&&typeof e=="object"&&e[ar]===mg,rx=e=>!!e&&typeof e=="object"&&e[ar]===Uc,nx=e=>!!e&&typeof e=="object"&&e[ar]===vg,gg=e=>!!e&&typeof e=="object"&&e[ar]===gf,ax=e=>!!e&&typeof e=="object"&&e[ar]===Kc;function wg(e){if(e&&typeof e=="object")switch(e[ar]){case Uc:case Kc:return!0}return!1}function ox(e){if(e&&typeof e=="object")switch(e[ar]){case vf:case Uc:case gf:case Kc:return!0}return!1}var sx=e=>(gg(e)||wg(e))&&!!e.anchor;Xe.ALIAS=vf;Xe.DOC=mg;Xe.MAP=Uc;Xe.NODE_TYPE=ar;Xe.PAIR=vg;Xe.SCALAR=gf;Xe.SEQ=Kc;Xe.hasAnchor=sx;Xe.isAlias=tx;Xe.isCollection=wg;Xe.isDocument=ix;Xe.isMap=rx;Xe.isNode=ox;Xe.isPair=nx;Xe.isScalar=gg;Xe.isSeq=ax});var Oo=C(wf=>{"use strict";var qe=Q(),xt=Symbol("break visit"),yg=Symbol("skip children"),Di=Symbol("remove node");function Yc(e,t){let i=Ng(t);qe.isDocument(e)?va(null,e.contents,i,Object.freeze([e]))===Di&&(e.contents=null):va(null,e,i,Object.freeze([]))}Yc.BREAK=xt;Yc.SKIP=yg;Yc.REMOVE=Di;function va(e,t,i,r){let n=bg(e,t,i,r);if(qe.isNode(n)||qe.isPair(n))return kg(e,r,n),va(e,n,i,r);if(typeof n!="symbol"){if(qe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a{"use strict";var Sg=Q(),cx=Oo(),lx={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ux=e=>e.replace(/[!,[\]{}]/g,t=>lx[t]),Ho=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+ux(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&&Sg.isNode(t.contents)){let a={};cx.visit(t.contents,(o,s)=>{Sg.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(` +`)}};Ho.defaultYaml={explicit:!1,version:"1.2"};Ho.defaultTags={"!!":"tag:yaml.org,2002:"};Eg.Directives=Ho});var Qc=C(Do=>{"use strict";var Pg=Q(),dx=Oo();function fx(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 Rg(e){let t=new Set;return dx.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Cg(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function hx(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Rg(e));let o=Cg(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Pg.isScalar(o.node)||Pg.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}}Do.anchorIsValid=fx;Do.anchorNames=Rg;Do.createNodeAnchors=hx;Do.findNewAnchor=Cg});var Nf=C(xg=>{"use strict";function Fo(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var px=Q();function Ag(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Ag(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!px.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}_g.toJS=Ag});var Zc=C(Ig=>{"use strict";var mx=Nf(),Tg=Q(),vx=Ar(),bf=class{constructor(t){Object.defineProperty(this,Tg.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(!Tg.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=vx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?mx.applyReviver(a,{"":s},"",s):s}};Ig.NodeBase=bf});var Mo=C(jg=>{"use strict";var gx=Qc(),wx=Oo(),wa=Q(),yx=Zc(),Nx=Ar(),kf=class extends yx.NodeBase{constructor(t){super(wa.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=[],wx.visit(t,{Node:(a,o)=>{(wa.isAlias(o)||wa.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||(Nx.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=el(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(gx.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 el(e,t,i){if(wa.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(wa.isCollection(t)){let r=0;for(let n of t.items){let a=el(e,n,i);a>r&&(r=a)}return r}else if(wa.isPair(t)){let r=el(e,t.key,i),n=el(e,t.value,i);return Math.max(r,n)}return 1}jg.Alias=kf});var De=C(Sf=>{"use strict";var bx=Q(),kx=Zc(),Sx=Ar(),Ex=e=>!e||typeof e!="function"&&typeof e!="object",_r=class extends kx.NodeBase{constructor(t){super(bx.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Sx.toJS(this.value,t,i)}toString(){return String(this.value)}};_r.BLOCK_FOLDED="BLOCK_FOLDED";_r.BLOCK_LITERAL="BLOCK_LITERAL";_r.PLAIN="PLAIN";_r.QUOTE_DOUBLE="QUOTE_DOUBLE";_r.QUOTE_SINGLE="QUOTE_SINGLE";Sf.Scalar=_r;Sf.isScalarValue=Ex});var Bo=C(Og=>{"use strict";var Px=Mo(),En=Q(),$g=De(),Rx="tag:yaml.org,2002:";function Cx(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 xx(e,t,i){if(En.isDocument(e)&&(e=e.contents),En.isNode(e))return e;if(En.isPair(e)){let d=i.schema[En.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 Px.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Rx+t.slice(2));let l=Cx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new $g.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[En.MAP]:Symbol.iterator in Object(e)?o[En.SEQ]:o[En.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 $g.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Og.createNode=xx});var il=C(tl=>{"use strict";var Ax=Bo(),Fi=Q(),_x=Zc();function Ef(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 Ax.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 Hg=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Pf=class extends _x.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=>Fi.isNode(r)||Fi.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Hg(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Fi.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ef(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(Fi.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&&Fi.isScalar(a)?a.value:a:Fi.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Fi.isPair(i))return!1;let r=i.value;return r==null||t&&Fi.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 Fi.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(Fi.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ef(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};tl.Collection=Pf;tl.collectionFromPath=Ef;tl.isEmptyPath=Hg});var Lo=C(rl=>{"use strict";var Tx=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Rf(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ix=(e,t,i)=>e.endsWith(` `)?Rf(i,t):i.includes(` `)?` -`+Rf(i,t):(e.endsWith(" ")?"":" ")+i;rl.indentComment=Rf;rl.lineComment=Tx;rl.stringifyComment=_x});var Dg=C(qo=>{"use strict";var Ix="flow",Cf="block",nl="quoted";function jx(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):d=n-r);let f,h,m=!1,p=-1,v=-1,g=-1;i===Cf&&(p=Hg(e,p,t.length),p!==-1&&(d=p+c));for(let E;E=e[p+=1];){if(i===nl&&E==="\\"){switch(v=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(E===` -`)i===Cf&&(p=Hg(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(E===" "&&h&&h!==" "&&h!==` +`+Rf(i,t):(e.endsWith(" ")?"":" ")+i;rl.indentComment=Rf;rl.lineComment=Ix;rl.stringifyComment=Tx});var Fg=C(qo=>{"use strict";var jx="flow",Cf="block",nl="quoted";function $x(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;nn-Math.max(2,a)?l.push(0):d=n-r);let f,h,m=!1,p=-1,v=-1,g=-1;i===Cf&&(p=Dg(e,p,t.length),p!==-1&&(d=p+c));for(let E;E=e[p+=1];){if(i===nl&&E==="\\"){switch(v=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(E===` +`)i===Cf&&(p=Dg(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(E===" "&&h&&h!==" "&&h!==` `&&h!==" "){let S=e[p+1];S&&S!==" "&&S!==` `&&S!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===nl){for(;h===" "||h===" ";)h=E,E=e[p+=1],m=!0;let S=p>g+1?p-2:v-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+c,f=void 0}else m=!0}h=E}if(m&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let E=0;E{"use strict";var yi=De(),Tr=Dg(),ol=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),sl=e=>/^(%|---|\.\.\.)/m.test(e);function $x(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{"use strict";var yi=De(),Tr=Fg(),ol=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),sl=e=>/^(%|---|\.\.\.)/m.test(e);function Ox(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;ar)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Vo(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(sl(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 `;let d,f;for(f=i.length;f>0;--f){let k=i[f-1];if(k!==` `&&k!==" "&&k!==" ")break}let h=i.substring(f),m=h.indexOf(` @@ -29,13 +29,13 @@ ${i}`)+"'";return t.implicitKey?r:Tr.foldFlowLines(r,i,Tr.FOLD_FLOW,ol(t,!1))}fu `)g=v;else break}let y=i.substring(0,g{b=!0});let N=Tr.foldFlowLines(`${y}${k}${h}`,l,Tr.FOLD_BLOCK,R);if(!b)return`>${S} ${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S} -${l}${y}${i}${h}`}function Ox(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(` +${l}${y}${i}${h}`}function Hx(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(` `)||u&&/[[\]{},]/.test(a))return ya(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(` `)?ya(a,t):al(e,t,i,r);if(!s&&!u&&n!==yi.Scalar.PLAIN&&a.includes(` `))return al(e,t,i,r);if(sl(a)){if(c==="")return t.forceBlockIndent=!0,al(e,t,i,r);if(s&&c===l)return ya(a,t)}let d=a.replace(/\n+/g,`$& -${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return ya(a,t)}return s?d:Tr.foldFlowLines(d,c,Tr.FOLD_FLOW,ol(t,!1))}function Hx(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!==yi.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=yi.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case yi.Scalar.BLOCK_FOLDED:case yi.Scalar.BLOCK_LITERAL:return n||a?ya(o.value,t):al(o,t,i,r);case yi.Scalar.QUOTE_DOUBLE:return Vo(o.value,t);case yi.Scalar.QUOTE_SINGLE:return xf(o.value,t);case yi.Scalar.PLAIN:return Ox(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Fg.stringifyString=Hx});var zo=C(_f=>{"use strict";var Dx=Qc(),Ir=Q(),Fx=Lo(),Mx=Wo();function Bx(e,t){let i=Object.assign({blockQuote:!0,commentString:Fx.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 Lx(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(Ir.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 qx(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Ir.isScalar(e)||Ir.isCollection(e))&&e.anchor;a&&Dx.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 Vx(e,t,i,r){if(Ir.isPair(e))return e.toString(t,i,r);if(Ir.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=Ir.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Lx(t.doc.schema.tags,a));let o=qx(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):Ir.isScalar(a)?Mx.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Ir.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} -${t.indent}${s}`:s}_f.createStringifyContext=Bx;_f.stringify=Vx});var qg=C(Lg=>{"use strict";var or=Q(),Mg=De(),Bg=zo(),Jo=Lo();function Wx({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=or.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(or.isCollection(e)||!or.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||or.isCollection(e)||(or.isScalar(e)?e.type===Mg.Scalar.BLOCK_FOLDED||e.type===Mg.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let m=!1,p=!1,v=Bg.stringify(e,i,()=>m=!0,()=>p=!0);if(!h&&!i.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return m&&r&&r(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||t==null&&h)return v=`? ${v}`,f&&!m?v+=Jo.lineComment(v,i.indent,l(f)):p&&n&&n(),v;m&&(f=null),h?(f&&(v+=Jo.lineComment(v,i.indent,l(f))),v=`? ${v} -${s}:`):(v=`${v}:`,f&&(v+=Jo.lineComment(v,i.indent,l(f))));let g,y,E;or.isNode(t)?(g=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(g=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&or.isScalar(t)&&(i.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&or.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Bg.stringify(t,i,()=>S=!0,()=>p=!0),b=" ";if(f||g||y){if(b=g?` +${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return ya(a,t)}return s?d:Tr.foldFlowLines(d,c,Tr.FOLD_FLOW,ol(t,!1))}function Dx(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!==yi.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=yi.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case yi.Scalar.BLOCK_FOLDED:case yi.Scalar.BLOCK_LITERAL:return n||a?ya(o.value,t):al(o,t,i,r);case yi.Scalar.QUOTE_DOUBLE:return Vo(o.value,t);case yi.Scalar.QUOTE_SINGLE:return xf(o.value,t);case yi.Scalar.PLAIN:return Hx(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Mg.stringifyString=Dx});var zo=C(_f=>{"use strict";var Fx=Qc(),Ir=Q(),Mx=Lo(),Bx=Wo();function Lx(e,t){let i=Object.assign({blockQuote:!0,commentString:Mx.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 qx(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(Ir.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 Vx(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Ir.isScalar(e)||Ir.isCollection(e))&&e.anchor;a&&Fx.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 Wx(e,t,i,r){if(Ir.isPair(e))return e.toString(t,i,r);if(Ir.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=Ir.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=qx(t.doc.schema.tags,a));let o=Vx(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):Ir.isScalar(a)?Bx.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Ir.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} +${t.indent}${s}`:s}_f.createStringifyContext=Lx;_f.stringify=Wx});var Vg=C(qg=>{"use strict";var or=Q(),Bg=De(),Lg=zo(),Jo=Lo();function zx({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=or.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(or.isCollection(e)||!or.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||or.isCollection(e)||(or.isScalar(e)?e.type===Bg.Scalar.BLOCK_FOLDED||e.type===Bg.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let m=!1,p=!1,v=Lg.stringify(e,i,()=>m=!0,()=>p=!0);if(!h&&!i.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return m&&r&&r(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||t==null&&h)return v=`? ${v}`,f&&!m?v+=Jo.lineComment(v,i.indent,l(f)):p&&n&&n(),v;m&&(f=null),h?(f&&(v+=Jo.lineComment(v,i.indent,l(f))),v=`? ${v} +${s}:`):(v=`${v}:`,f&&(v+=Jo.lineComment(v,i.indent,l(f))));let g,y,E;or.isNode(t)?(g=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(g=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&or.isScalar(t)&&(i.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&or.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Lg.stringify(t,i,()=>S=!0,()=>p=!0),b=" ";if(f||g||y){if(b=g?` `:"",y){let R=l(y);b+=` ${Jo.indentComment(R,i.indent)}`}k===""&&!i.inFlow?b===` `&&E&&(b=` @@ -44,32 +44,32 @@ ${Jo.indentComment(R,i.indent)}`}k===""&&!i.inFlow?b===` ${i.indent}`}else if(!h&&or.isCollection(t)){let R=k[0],N=k.indexOf(` `),w=N!==-1,P=i.inFlow??t.flow??t.items.length===0;if(w||!P){let L=!1;if(w&&(R==="&"||R==="!")){let H=k.indexOf(" ");R==="&"&&H!==-1&&H{"use strict";var Vg=zc("process");function zx(e,...t){e==="debug"&&console.log(...t)}function Jx(e,t){(e==="debug"||e==="warn")&&(typeof Vg.emitWarning=="function"?Vg.emitWarning(t):console.warn(t))}Tf.debug=zx;Tf.warn=Jx});var fl=C(dl=>{"use strict";var ul=Q(),Wg=De(),cl="<<",ll={identify:e=>e===cl||typeof e=="symbol"&&e.description===cl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Wg.Scalar(Symbol(cl)),{addToJSMap:zg}),stringify:()=>cl},Gx=(e,t)=>(ll.identify(t)||ul.isScalar(t)&&(!t.type||t.type===Wg.Scalar.PLAIN)&&ll.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===ll.tag&&i.default);function zg(e,t,i){let r=Jg(e,i);if(ul.isSeq(r))for(let n of r.items)jf(e,t,n);else if(Array.isArray(r))for(let n of r)jf(e,t,n);else jf(e,t,r)}function jf(e,t,i){let r=Jg(e,i);if(!ul.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 Jg(e,t){return e&&ul.isAlias(t)?t.resolve(e.doc,e):t}dl.addMergeToJSMap=zg;dl.isMergeKey=Gx;dl.merge=ll});var Of=C(Kg=>{"use strict";var Ux=If(),Gg=fl(),Kx=zo(),Ug=Q(),$f=Ar();function Yx(e,t,{key:i,value:r}){if(Ug.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Gg.isMergeKey(e,i))Gg.addMergeToJSMap(e,t,r);else{let n=$f.toJS(i,"",e);if(t instanceof Map)t.set(n,$f.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=Xx(i,n,e),o=$f.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 Xx(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Ug.isNode(e)&&i?.doc){let r=Kx.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)+'..."'),Ux.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)}Kg.addPairToJSMap=Yx});var jr=C(Hf=>{"use strict";var Yg=Bo(),Qx=qg(),Zx=Of(),hl=Q();function eA(e,t,i){let r=Yg.createNode(e,void 0,i),n=Yg.createNode(t,void 0,i);return new pl(r,n)}var pl=class e{constructor(t,i=null){Object.defineProperty(this,hl.NODE_TYPE,{value:hl.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return hl.isNode(i)&&(i=i.clone(t)),hl.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return Zx.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?Qx.stringifyPair(this,t,i,r):JSON.stringify(this)}};Hf.Pair=pl;Hf.createPair=eA});var Df=C(Qg=>{"use strict";var Pn=Q(),Xg=zo(),ml=Lo();function tA(e,t,i){return(t.inFlow??e.flow?rA:iA)(e,t,i)}function iA({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}),d=!1,f=[];for(let m=0;mv=null,()=>d=!0);v&&(g+=ml.lineComment(g,a,l(v))),d&&v&&(d=!1),f.push(r+g)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let m=1;m{"use strict";var Wg=zc("process");function Jx(e,...t){e==="debug"&&console.log(...t)}function Gx(e,t){(e==="debug"||e==="warn")&&(typeof Wg.emitWarning=="function"?Wg.emitWarning(t):console.warn(t))}Tf.debug=Jx;Tf.warn=Gx});var fl=C(dl=>{"use strict";var ul=Q(),zg=De(),cl="<<",ll={identify:e=>e===cl||typeof e=="symbol"&&e.description===cl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new zg.Scalar(Symbol(cl)),{addToJSMap:Jg}),stringify:()=>cl},Ux=(e,t)=>(ll.identify(t)||ul.isScalar(t)&&(!t.type||t.type===zg.Scalar.PLAIN)&&ll.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===ll.tag&&i.default);function Jg(e,t,i){let r=Gg(e,i);if(ul.isSeq(r))for(let n of r.items)jf(e,t,n);else if(Array.isArray(r))for(let n of r)jf(e,t,n);else jf(e,t,r)}function jf(e,t,i){let r=Gg(e,i);if(!ul.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 Gg(e,t){return e&&ul.isAlias(t)?t.resolve(e.doc,e):t}dl.addMergeToJSMap=Jg;dl.isMergeKey=Ux;dl.merge=ll});var Of=C(Yg=>{"use strict";var Kx=If(),Ug=fl(),Yx=zo(),Kg=Q(),$f=Ar();function Xx(e,t,{key:i,value:r}){if(Kg.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Ug.isMergeKey(e,i))Ug.addMergeToJSMap(e,t,r);else{let n=$f.toJS(i,"",e);if(t instanceof Map)t.set(n,$f.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=Qx(i,n,e),o=$f.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 Qx(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Kg.isNode(e)&&i?.doc){let r=Yx.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)+'..."'),Kx.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)}Yg.addPairToJSMap=Xx});var jr=C(Hf=>{"use strict";var Xg=Bo(),Zx=Vg(),eA=Of(),hl=Q();function tA(e,t,i){let r=Xg.createNode(e,void 0,i),n=Xg.createNode(t,void 0,i);return new pl(r,n)}var pl=class e{constructor(t,i=null){Object.defineProperty(this,hl.NODE_TYPE,{value:hl.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return hl.isNode(i)&&(i=i.clone(t)),hl.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return eA.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?Zx.stringifyPair(this,t,i,r):JSON.stringify(this)}};Hf.Pair=pl;Hf.createPair=tA});var Df=C(Zg=>{"use strict";var Pn=Q(),Qg=zo(),ml=Lo();function iA(e,t,i){return(t.inFlow??e.flow?nA:rA)(e,t,i)}function rA({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}),d=!1,f=[];for(let m=0;mv=null,()=>d=!0);v&&(g+=ml.lineComment(g,a,l(v))),d&&v&&(d=!1),f.push(r+g)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let m=1;mv=null);l||(l=d.length>u||g.includes(` +`+ml.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function nA({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,d=[];for(let m=0;mv=null);l||(l=d.length>u||g.includes(` `)),m0&&(l||(l=d.reduce((y,E)=>y+E.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=ml.lineComment(g,r,s(v))),d.push(g),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let m=d.reduce((p,v)=>p+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let p of d)m+=p?` ${a}${n}${p}`:` `;return`${m} -${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function vl({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ml.indentComment(t(r),e);i.push(a.trimStart())}}Qg.stringifyCollection=tA});var Or=C(Mf=>{"use strict";var nA=Df(),aA=Of(),oA=il(),$r=Q(),gl=jr(),sA=De();function Go(e,t){let i=$r.isScalar(t)?t.value:t;for(let r of e)if($r.isPair(r)&&(r.key===t||r.key===i||$r.isScalar(r.key)&&r.key.value===i))return r}var Ff=class extends oA.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super($r.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(gl.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;$r.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new gl.Pair(t,t?.value):r=new gl.Pair(t.key,t.value);let n=Go(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);$r.isScalar(n.value)&&sA.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=Go(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Go(this.items,t)?.value;return(!i&&$r.isScalar(n)?n.value:n)??void 0}has(t){return!!Go(this.items,t)}set(t,i){this.add(new gl.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)aA.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!$r.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})),nA.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Mf.YAMLMap=Ff;Mf.findPair=Go});var Na=C(ew=>{"use strict";var cA=Q(),Zg=Or(),lA={collection:"map",default:!0,nodeClass:Zg.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return cA.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Zg.YAMLMap.from(e,t,i)};ew.map=lA});var Hr=C(tw=>{"use strict";var uA=Bo(),dA=Df(),fA=il(),yl=Q(),hA=De(),pA=Ar(),Bf=class extends fA.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(yl.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=wl(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=wl(t);if(typeof r!="number")return;let n=this.items[r];return!i&&yl.isScalar(n)?n.value:n}has(t){let i=wl(t);return typeof i=="number"&&i=0?t:null}tw.YAMLSeq=Bf});var ba=C(rw=>{"use strict";var mA=Q(),iw=Hr(),vA={collection:"seq",default:!0,nodeClass:iw.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return mA.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>iw.YAMLSeq.from(e,t,i)};rw.seq=vA});var Uo=C(nw=>{"use strict";var gA=Wo(),wA={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),gA.stringifyString(e,t,i,r)}};nw.string=wA});var Nl=C(sw=>{"use strict";var aw=De(),ow={identify:e=>e==null,createNode:()=>new aw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new aw.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&ow.test.test(e)?e:t.options.nullStr};sw.nullTag=ow});var Lf=C(lw=>{"use strict";var yA=De(),cw={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new yA.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&cw.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};lw.boolTag=cw});var ka=C(uw=>{"use strict";function NA({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}uw.stringifyNumber=NA});var Vf=C(bl=>{"use strict";var bA=De(),qf=ka(),kA={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:qf.stringifyNumber},SA={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():qf.stringifyNumber(e)}},EA={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 bA.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:qf.stringifyNumber};bl.float=EA;bl.floatExp=SA;bl.floatNaN=kA});var zf=C(Sl=>{"use strict";var dw=ka(),kl=e=>typeof e=="bigint"||Number.isInteger(e),Wf=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function fw(e,t,i){let{value:r}=e;return kl(r)&&r>=0?i+r.toString(t):dw.stringifyNumber(e)}var PA={identify:e=>kl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Wf(e,2,8,i),stringify:e=>fw(e,8,"0o")},RA={identify:kl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Wf(e,0,10,i),stringify:dw.stringifyNumber},CA={identify:e=>kl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Wf(e,2,16,i),stringify:e=>fw(e,16,"0x")};Sl.int=RA;Sl.intHex=CA;Sl.intOct=PA});var pw=C(hw=>{"use strict";var xA=Na(),AA=Nl(),_A=ba(),TA=Uo(),IA=Lf(),Jf=Vf(),Gf=zf(),jA=[xA.map,_A.seq,TA.string,AA.nullTag,IA.boolTag,Gf.intOct,Gf.int,Gf.intHex,Jf.floatNaN,Jf.floatExp,Jf.float];hw.schema=jA});var gw=C(vw=>{"use strict";var $A=De(),OA=Na(),HA=ba();function mw(e){return typeof e=="bigint"||Number.isInteger(e)}var El=({value:e})=>JSON.stringify(e),DA=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:El},{identify:e=>e==null,createNode:()=>new $A.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:El},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:El},{identify:mw,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})=>mw(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:El}],FA={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},MA=[OA.map,HA.seq].concat(DA,FA);vw.schema=MA});var Kf=C(ww=>{"use strict";var Ko=zc("buffer"),Uf=De(),BA=Wo(),LA={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ko.Buffer=="function")return Ko.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{"use strict";var Pl=Q(),Yf=jr(),qA=De(),VA=Hr();function yw(e,t){if(Pl.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Yf.Pair(new qA.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} +${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function vl({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ml.indentComment(t(r),e);i.push(a.trimStart())}}Zg.stringifyCollection=iA});var Or=C(Mf=>{"use strict";var aA=Df(),oA=Of(),sA=il(),$r=Q(),gl=jr(),cA=De();function Go(e,t){let i=$r.isScalar(t)?t.value:t;for(let r of e)if($r.isPair(r)&&(r.key===t||r.key===i||$r.isScalar(r.key)&&r.key.value===i))return r}var Ff=class extends sA.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super($r.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(gl.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;$r.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new gl.Pair(t,t?.value):r=new gl.Pair(t.key,t.value);let n=Go(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);$r.isScalar(n.value)&&cA.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=Go(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Go(this.items,t)?.value;return(!i&&$r.isScalar(n)?n.value:n)??void 0}has(t){return!!Go(this.items,t)}set(t,i){this.add(new gl.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)oA.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!$r.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})),aA.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Mf.YAMLMap=Ff;Mf.findPair=Go});var Na=C(tw=>{"use strict";var lA=Q(),ew=Or(),uA={collection:"map",default:!0,nodeClass:ew.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return lA.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>ew.YAMLMap.from(e,t,i)};tw.map=uA});var Hr=C(iw=>{"use strict";var dA=Bo(),fA=Df(),hA=il(),yl=Q(),pA=De(),mA=Ar(),Bf=class extends hA.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(yl.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=wl(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=wl(t);if(typeof r!="number")return;let n=this.items[r];return!i&&yl.isScalar(n)?n.value:n}has(t){let i=wl(t);return typeof i=="number"&&i=0?t:null}iw.YAMLSeq=Bf});var ba=C(nw=>{"use strict";var vA=Q(),rw=Hr(),gA={collection:"seq",default:!0,nodeClass:rw.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return vA.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>rw.YAMLSeq.from(e,t,i)};nw.seq=gA});var Uo=C(aw=>{"use strict";var wA=Wo(),yA={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),wA.stringifyString(e,t,i,r)}};aw.string=yA});var Nl=C(cw=>{"use strict";var ow=De(),sw={identify:e=>e==null,createNode:()=>new ow.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ow.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&sw.test.test(e)?e:t.options.nullStr};cw.nullTag=sw});var Lf=C(uw=>{"use strict";var NA=De(),lw={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new NA.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&lw.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};uw.boolTag=lw});var ka=C(dw=>{"use strict";function bA({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}dw.stringifyNumber=bA});var Vf=C(bl=>{"use strict";var kA=De(),qf=ka(),SA={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:qf.stringifyNumber},EA={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():qf.stringifyNumber(e)}},PA={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 kA.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:qf.stringifyNumber};bl.float=PA;bl.floatExp=EA;bl.floatNaN=SA});var zf=C(Sl=>{"use strict";var fw=ka(),kl=e=>typeof e=="bigint"||Number.isInteger(e),Wf=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function hw(e,t,i){let{value:r}=e;return kl(r)&&r>=0?i+r.toString(t):fw.stringifyNumber(e)}var RA={identify:e=>kl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Wf(e,2,8,i),stringify:e=>hw(e,8,"0o")},CA={identify:kl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Wf(e,0,10,i),stringify:fw.stringifyNumber},xA={identify:e=>kl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Wf(e,2,16,i),stringify:e=>hw(e,16,"0x")};Sl.int=CA;Sl.intHex=xA;Sl.intOct=RA});var mw=C(pw=>{"use strict";var AA=Na(),_A=Nl(),TA=ba(),IA=Uo(),jA=Lf(),Jf=Vf(),Gf=zf(),$A=[AA.map,TA.seq,IA.string,_A.nullTag,jA.boolTag,Gf.intOct,Gf.int,Gf.intHex,Jf.floatNaN,Jf.floatExp,Jf.float];pw.schema=$A});var ww=C(gw=>{"use strict";var OA=De(),HA=Na(),DA=ba();function vw(e){return typeof e=="bigint"||Number.isInteger(e)}var El=({value:e})=>JSON.stringify(e),FA=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:El},{identify:e=>e==null,createNode:()=>new OA.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:El},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:El},{identify:vw,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})=>vw(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:El}],MA={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},BA=[HA.map,DA.seq].concat(FA,MA);gw.schema=BA});var Kf=C(yw=>{"use strict";var Ko=zc("buffer"),Uf=De(),LA=Wo(),qA={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ko.Buffer=="function")return Ko.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{"use strict";var Pl=Q(),Yf=jr(),VA=De(),WA=Hr();function Nw(e,t){if(Pl.isSeq(e))for(let i=0;i1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Yf.Pair(new VA.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment} -${a.comment}`:r.comment}r=n}e.items[i]=Pl.isPair(r)?r:new Yf.Pair(r)}}else t("Expected a sequence for this tag");return e}function Nw(e,t,i){let{replacer:r}=i,n=new VA.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(Yf.createPair(s,c,i))}return n}var WA={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yw,createNode:Nw};Rl.createPairs=Nw;Rl.pairs=WA;Rl.resolvePairs=yw});var Zf=C(Qf=>{"use strict";var bw=Q(),Xf=Ar(),Yo=Or(),zA=Hr(),kw=Cl(),Rn=class e extends zA.YAMLSeq{constructor(){super(),this.add=Yo.YAMLMap.prototype.add.bind(this),this.delete=Yo.YAMLMap.prototype.delete.bind(this),this.get=Yo.YAMLMap.prototype.get.bind(this),this.has=Yo.YAMLMap.prototype.has.bind(this),this.set=Yo.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(bw.isPair(n)?(a=Xf.toJS(n.key,"",i),o=Xf.toJS(n.value,a,i)):a=Xf.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=kw.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Rn.tag="tag:yaml.org,2002:omap";var JA={collection:"seq",identify:e=>e instanceof Map,nodeClass:Rn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=kw.resolvePairs(e,t),r=[];for(let{key:n}of i.items)bw.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Rn,i)},createNode:(e,t,i)=>Rn.from(e,t,i)};Qf.YAMLOMap=Rn;Qf.omap=JA});var Cw=C(eh=>{"use strict";var Sw=De();function Ew({value:e,source:t},i){return t&&(e?Pw:Rw).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Pw={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 Sw.Scalar(!0),stringify:Ew},Rw={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 Sw.Scalar(!1),stringify:Ew};eh.falseTag=Rw;eh.trueTag=Pw});var xw=C(xl=>{"use strict";var GA=De(),th=ka(),UA={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:th.stringifyNumber},KA={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():th.stringifyNumber(e)}},YA={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 GA.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:th.stringifyNumber};xl.float=YA;xl.floatExp=KA;xl.floatNaN=UA});var _w=C(Qo=>{"use strict";var Aw=ka(),Xo=e=>typeof e=="bigint"||Number.isInteger(e);function Al(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 ih(e,t,i){let{value:r}=e;if(Xo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Aw.stringifyNumber(e)}var XA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Al(e,2,2,i),stringify:e=>ih(e,2,"0b")},QA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Al(e,1,8,i),stringify:e=>ih(e,8,"0")},ZA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Al(e,0,10,i),stringify:Aw.stringifyNumber},e_={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Al(e,2,16,i),stringify:e=>ih(e,16,"0x")};Qo.int=ZA;Qo.intBin=XA;Qo.intHex=e_;Qo.intOct=QA});var nh=C(rh=>{"use strict";var Il=Q(),_l=jr(),Tl=Or(),Cn=class e extends Tl.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Il.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new _l.Pair(t.key,null):i=new _l.Pair(t,null),Tl.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Tl.findPair(this.items,t);return!i&&Il.isPair(r)?Il.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=Tl.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new _l.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(_l.createPair(o,null,r));return a}};Cn.tag="tag:yaml.org,2002:set";var t_={collection:"map",identify:e=>e instanceof Set,nodeClass:Cn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Cn.from(e,t,i),resolve(e,t){if(Il.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Cn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};rh.YAMLSet=Cn;rh.set=t_});var oh=C(jl=>{"use strict";var i_=ka();function ah(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 Tw(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return i_.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 r_={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})=>ah(e,i),stringify:Tw},n_={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=>ah(e,!1),stringify:Tw},Iw={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(Iw.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 d=ah(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};jl.floatTime=n_;jl.intTime=r_;jl.timestamp=Iw});var Ow=C($w=>{"use strict";var a_=Na(),o_=Nl(),s_=ba(),c_=Uo(),l_=Kf(),jw=Cw(),sh=xw(),$l=_w(),u_=fl(),d_=Zf(),f_=Cl(),h_=nh(),ch=oh(),p_=[a_.map,s_.seq,c_.string,o_.nullTag,jw.trueTag,jw.falseTag,$l.intBin,$l.intOct,$l.int,$l.intHex,sh.floatNaN,sh.floatExp,sh.float,l_.binary,u_.merge,d_.omap,f_.pairs,h_.set,ch.intTime,ch.floatTime,ch.timestamp];$w.schema=p_});var zw=C(dh=>{"use strict";var Mw=Na(),m_=Nl(),Bw=ba(),v_=Uo(),g_=Lf(),lh=Vf(),uh=zf(),w_=pw(),y_=gw(),Lw=Kf(),Zo=fl(),qw=Zf(),Vw=Cl(),Hw=Ow(),Ww=nh(),Ol=oh(),Dw=new Map([["core",w_.schema],["failsafe",[Mw.map,Bw.seq,v_.string]],["json",y_.schema],["yaml11",Hw.schema],["yaml-1.1",Hw.schema]]),Fw={binary:Lw.binary,bool:g_.boolTag,float:lh.float,floatExp:lh.floatExp,floatNaN:lh.floatNaN,floatTime:Ol.floatTime,int:uh.int,intHex:uh.intHex,intOct:uh.intOct,intTime:Ol.intTime,map:Mw.map,merge:Zo.merge,null:m_.nullTag,omap:qw.omap,pairs:Vw.pairs,seq:Bw.seq,set:Ww.set,timestamp:Ol.timestamp},N_={"tag:yaml.org,2002:binary":Lw.binary,"tag:yaml.org,2002:merge":Zo.merge,"tag:yaml.org,2002:omap":qw.omap,"tag:yaml.org,2002:pairs":Vw.pairs,"tag:yaml.org,2002:set":Ww.set,"tag:yaml.org,2002:timestamp":Ol.timestamp};function b_(e,t,i){let r=Dw.get(t);if(r&&!e)return i&&!r.includes(Zo.merge)?r.concat(Zo.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Dw.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(Zo.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Fw[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Fw).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},[])}dh.coreKnownTags=N_;dh.getTags=b_});var ph=C(Jw=>{"use strict";var fh=Q(),k_=Na(),S_=ba(),E_=Uo(),Hl=zw(),P_=(e,t)=>e.keyt.key?1:0,hh=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Hl.getTags(t,"compat"):t?Hl.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Hl.coreKnownTags:{},this.tags=Hl.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,fh.MAP,{value:k_.map}),Object.defineProperty(this,fh.SCALAR,{value:E_.string}),Object.defineProperty(this,fh.SEQ,{value:S_.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?P_:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Jw.Schema=hh});var Uw=C(Gw=>{"use strict";var R_=Q(),mh=zo(),es=Lo();function C_(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=mh.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(es.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(R_.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(es.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=mh.stringify(e.contents,n,()=>s=null,c);s&&(l+=es.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(mh.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` +${a.comment}`:r.comment}r=n}e.items[i]=Pl.isPair(r)?r:new Yf.Pair(r)}}else t("Expected a sequence for this tag");return e}function bw(e,t,i){let{replacer:r}=i,n=new WA.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(Yf.createPair(s,c,i))}return n}var zA={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Nw,createNode:bw};Rl.createPairs=bw;Rl.pairs=zA;Rl.resolvePairs=Nw});var Zf=C(Qf=>{"use strict";var kw=Q(),Xf=Ar(),Yo=Or(),JA=Hr(),Sw=Cl(),Rn=class e extends JA.YAMLSeq{constructor(){super(),this.add=Yo.YAMLMap.prototype.add.bind(this),this.delete=Yo.YAMLMap.prototype.delete.bind(this),this.get=Yo.YAMLMap.prototype.get.bind(this),this.has=Yo.YAMLMap.prototype.has.bind(this),this.set=Yo.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(kw.isPair(n)?(a=Xf.toJS(n.key,"",i),o=Xf.toJS(n.value,a,i)):a=Xf.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=Sw.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Rn.tag="tag:yaml.org,2002:omap";var GA={collection:"seq",identify:e=>e instanceof Map,nodeClass:Rn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Sw.resolvePairs(e,t),r=[];for(let{key:n}of i.items)kw.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Rn,i)},createNode:(e,t,i)=>Rn.from(e,t,i)};Qf.YAMLOMap=Rn;Qf.omap=GA});var xw=C(eh=>{"use strict";var Ew=De();function Pw({value:e,source:t},i){return t&&(e?Rw:Cw).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Rw={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 Ew.Scalar(!0),stringify:Pw},Cw={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 Ew.Scalar(!1),stringify:Pw};eh.falseTag=Cw;eh.trueTag=Rw});var Aw=C(xl=>{"use strict";var UA=De(),th=ka(),KA={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:th.stringifyNumber},YA={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():th.stringifyNumber(e)}},XA={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 UA.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:th.stringifyNumber};xl.float=XA;xl.floatExp=YA;xl.floatNaN=KA});var Tw=C(Qo=>{"use strict";var _w=ka(),Xo=e=>typeof e=="bigint"||Number.isInteger(e);function Al(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 ih(e,t,i){let{value:r}=e;if(Xo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return _w.stringifyNumber(e)}var QA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Al(e,2,2,i),stringify:e=>ih(e,2,"0b")},ZA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Al(e,1,8,i),stringify:e=>ih(e,8,"0")},e_={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Al(e,0,10,i),stringify:_w.stringifyNumber},t_={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Al(e,2,16,i),stringify:e=>ih(e,16,"0x")};Qo.int=e_;Qo.intBin=QA;Qo.intHex=t_;Qo.intOct=ZA});var nh=C(rh=>{"use strict";var Il=Q(),_l=jr(),Tl=Or(),Cn=class e extends Tl.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Il.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new _l.Pair(t.key,null):i=new _l.Pair(t,null),Tl.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Tl.findPair(this.items,t);return!i&&Il.isPair(r)?Il.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=Tl.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new _l.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(_l.createPair(o,null,r));return a}};Cn.tag="tag:yaml.org,2002:set";var i_={collection:"map",identify:e=>e instanceof Set,nodeClass:Cn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Cn.from(e,t,i),resolve(e,t){if(Il.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Cn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};rh.YAMLSet=Cn;rh.set=i_});var oh=C(jl=>{"use strict";var r_=ka();function ah(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 Iw(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return r_.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 n_={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})=>ah(e,i),stringify:Iw},a_={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=>ah(e,!1),stringify:Iw},jw={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(jw.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 d=ah(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};jl.floatTime=a_;jl.intTime=n_;jl.timestamp=jw});var Hw=C(Ow=>{"use strict";var o_=Na(),s_=Nl(),c_=ba(),l_=Uo(),u_=Kf(),$w=xw(),sh=Aw(),$l=Tw(),d_=fl(),f_=Zf(),h_=Cl(),p_=nh(),ch=oh(),m_=[o_.map,c_.seq,l_.string,s_.nullTag,$w.trueTag,$w.falseTag,$l.intBin,$l.intOct,$l.int,$l.intHex,sh.floatNaN,sh.floatExp,sh.float,u_.binary,d_.merge,f_.omap,h_.pairs,p_.set,ch.intTime,ch.floatTime,ch.timestamp];Ow.schema=m_});var Jw=C(dh=>{"use strict";var Bw=Na(),v_=Nl(),Lw=ba(),g_=Uo(),w_=Lf(),lh=Vf(),uh=zf(),y_=mw(),N_=ww(),qw=Kf(),Zo=fl(),Vw=Zf(),Ww=Cl(),Dw=Hw(),zw=nh(),Ol=oh(),Fw=new Map([["core",y_.schema],["failsafe",[Bw.map,Lw.seq,g_.string]],["json",N_.schema],["yaml11",Dw.schema],["yaml-1.1",Dw.schema]]),Mw={binary:qw.binary,bool:w_.boolTag,float:lh.float,floatExp:lh.floatExp,floatNaN:lh.floatNaN,floatTime:Ol.floatTime,int:uh.int,intHex:uh.intHex,intOct:uh.intOct,intTime:Ol.intTime,map:Bw.map,merge:Zo.merge,null:v_.nullTag,omap:Vw.omap,pairs:Ww.pairs,seq:Lw.seq,set:zw.set,timestamp:Ol.timestamp},b_={"tag:yaml.org,2002:binary":qw.binary,"tag:yaml.org,2002:merge":Zo.merge,"tag:yaml.org,2002:omap":Vw.omap,"tag:yaml.org,2002:pairs":Ww.pairs,"tag:yaml.org,2002:set":zw.set,"tag:yaml.org,2002:timestamp":Ol.timestamp};function k_(e,t,i){let r=Fw.get(t);if(r&&!e)return i&&!r.includes(Zo.merge)?r.concat(Zo.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Fw.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(Zo.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Mw[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Mw).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},[])}dh.coreKnownTags=b_;dh.getTags=k_});var ph=C(Gw=>{"use strict";var fh=Q(),S_=Na(),E_=ba(),P_=Uo(),Hl=Jw(),R_=(e,t)=>e.keyt.key?1:0,hh=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Hl.getTags(t,"compat"):t?Hl.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Hl.coreKnownTags:{},this.tags=Hl.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,fh.MAP,{value:S_.map}),Object.defineProperty(this,fh.SCALAR,{value:P_.string}),Object.defineProperty(this,fh.SEQ,{value:E_.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?R_:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Gw.Schema=hh});var Kw=C(Uw=>{"use strict";var C_=Q(),mh=zo(),es=Lo();function x_(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=mh.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(es.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(C_.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(es.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=mh.stringify(e.contents,n,()=>s=null,c);s&&(l+=es.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(mh.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(` `)?(i.push("..."),i.push(es.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(es.indentComment(a(c),"")))}return i.join(` `)+` -`}Gw.stringifyDocument=C_});var ts=C(Kw=>{"use strict";var x_=Mo(),Sa=il(),ti=Q(),A_=jr(),__=Ar(),T_=ph(),I_=Uw(),vh=Qc(),j_=Nf(),$_=Bo(),gh=yf(),wh=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ti.NODE_TYPE,{value:ti.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 gh.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,{[ti.NODE_TYPE]:{value:ti.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=ti.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ea(this.contents)&&this.contents.add(t)}addIn(t,i){Ea(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=vh.anchorNames(this);t.anchor=!i||r.has(i)?vh.findNewAnchor(i||"a",r):i}return new x_.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 v=y=>typeof y=="number"||y instanceof String||y instanceof Number,g=i.filter(v).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:d,setAnchors:f,sourceObjects:h}=vh.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=$_.createNode(t,u,m);return s&&ti.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new A_.Pair(n,a)}delete(t){return Ea(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Sa.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ea(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return ti.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Sa.isEmptyPath(t)?!i&&ti.isScalar(this.contents)?this.contents.value:this.contents:ti.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return ti.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Sa.isEmptyPath(t)?this.contents!==void 0:ti.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Sa.collectionFromPath(this.schema,[t],i):Ea(this.contents)&&this.contents.set(t,i)}setIn(t,i){Sa.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Sa.collectionFromPath(this.schema,Array.from(t),i):Ea(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 gh.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 gh.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 T_.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=__.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"?j_.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 I_.stringifyDocument(this,t)}};function Ea(e){if(ti.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Kw.Document=wh});var ns=C(rs=>{"use strict";var is=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},yh=class extends is{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Nh=class extends is{constructor(t,i,r){super("YAMLWarning",t,i,r)}},O_=(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)+`… +`}Uw.stringifyDocument=x_});var ts=C(Yw=>{"use strict";var A_=Mo(),Sa=il(),ti=Q(),__=jr(),T_=Ar(),I_=ph(),j_=Kw(),vh=Qc(),$_=Nf(),O_=Bo(),gh=yf(),wh=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ti.NODE_TYPE,{value:ti.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 gh.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,{[ti.NODE_TYPE]:{value:ti.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=ti.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ea(this.contents)&&this.contents.add(t)}addIn(t,i){Ea(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=vh.anchorNames(this);t.anchor=!i||r.has(i)?vh.findNewAnchor(i||"a",r):i}return new A_.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 v=y=>typeof y=="number"||y instanceof String||y instanceof Number,g=i.filter(v).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:d,setAnchors:f,sourceObjects:h}=vh.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=O_.createNode(t,u,m);return s&&ti.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new __.Pair(n,a)}delete(t){return Ea(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Sa.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ea(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return ti.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Sa.isEmptyPath(t)?!i&&ti.isScalar(this.contents)?this.contents.value:this.contents:ti.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return ti.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Sa.isEmptyPath(t)?this.contents!==void 0:ti.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Sa.collectionFromPath(this.schema,[t],i):Ea(this.contents)&&this.contents.set(t,i)}setIn(t,i){Sa.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Sa.collectionFromPath(this.schema,Array.from(t),i):Ea(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 gh.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 gh.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 I_.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=T_.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"?$_.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 j_.stringifyDocument(this,t)}};function Ea(e){if(ti.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Yw.Document=wh});var ns=C(rs=>{"use strict";var is=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},yh=class extends is{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Nh=class extends is{constructor(t,i,r){super("YAMLWarning",t,i,r)}},H_=(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)+`… `),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+=`: ${o} ${l} -`}};rs.YAMLError=is;rs.YAMLParseError=yh;rs.YAMLWarning=Nh;rs.prettifyError=O_});var as=C(Yw=>{"use strict";function H_(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,m=!1,p=null,v=null,g=null,y=null,E=null,S=null,k=null;for(let N of e)switch(m&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),p&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),N.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(p=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=N.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=N.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=N.source,l=!0,h=!0,(v||g)&&(y=N),u=!0;break;case"anchor":v&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=N,k??(k=N.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),g=N,k??(k=N.offset),l=!1,u=!1,m=!0;break}case i:(v||g)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),S=N,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){E&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let b=e[e.length-1],R=b?b.offset+b.source.length:n;return m&&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"),p&&(l&&p.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:S,spaceBefore:c,comment:d,hasNewline:h,anchor:v,tag:g,newlineAfterProp:y,end:R,start:k??R}}Yw.resolveProps=H_});var Dl=C(Xw=>{"use strict";function bh(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` -`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(bh(t.key)||bh(t.value))return!0}return!1;default:return!0}}Xw.containsNewline=bh});var kh=C(Qw=>{"use strict";var D_=Dl();function F_(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&D_.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Qw.flowIndentCheck=F_});var Sh=C(ey=>{"use strict";var Zw=Q();function M_(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Zw.isScalar(a)&&Zw.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}ey.mapIncludes=M_});var oy=C(ay=>{"use strict";var ty=jr(),B_=Or(),iy=as(),L_=Dl(),ry=kh(),q_=Sh(),ny="All mapping items must start at the same column";function V_({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??B_.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:d,key:f,sep:h,value:m}=u,p=iy.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),v=!p.found;if(v){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",ny)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=` -`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||L_.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==r.indent&&n(c,"BAD_INDENT",ny);i.atKey=!0;let g=p.end,y=f?e(i,f,p,n):t(i,g,d,null,p,n);i.schema.compat&&ry.flowIndentCheck(r.indent,f,n),i.atKey=!1,q_.mapIncludes(i,s.items,y)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let E=iy.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=E.end,E.found){v&&(m?.type==="block-map"&&!E.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&p.start{"use strict";var W_=Hr(),z_=as(),J_=kh();function G_({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??W_.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:d}of r.items){let f=z_.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&J_.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}sy.resolveBlockSeq=G_});var Pa=C(ly=>{"use strict";function U_(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}}ly.resolveEnd=U_});var hy=C(fy=>{"use strict";var K_=Q(),Y_=jr(),uy=Or(),X_=Hr(),Q_=Pa(),dy=as(),Z_=Dl(),eT=Sh(),Eh="Block collections are not allowed within flow collections",Ph=e=>e&&(e.type==="block-map"||e.type==="block-seq");function tT({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?uy.YAMLMap:X_.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let v=0;v0){let v=Q_.resolveEnd(m,p,i.options.strict,n);v.comment&&(l.comment?l.comment+=` -`+v.comment:l.comment=v.comment),l.range=[r.offset,p,v.offset]}else l.range=[r.offset,p,p];return l}fy.resolveFlowCollection=tT});var my=C(py=>{"use strict";var iT=Q(),rT=De(),nT=Or(),aT=Hr(),oT=oy(),sT=cy(),cT=hy();function Rh(e,t,i,r,n,a){let o=i.type==="block-map"?oT.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?sT.resolveBlockSeq(e,t,i,r,a):cT.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function lT(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!h||h.offsetf.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Rh(e,t,i,n,o)}let l=Rh(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=iT.isNode(u)?u:new rT.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}py.composeCollection=lT});var xh=C(vy=>{"use strict";var Ch=De();function uT(e,t,i){let r=t.offset,n=dT(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Ch.Scalar.BLOCK_FOLDED:Ch.Scalar.BLOCK_LITERAL,o=t.source?fT(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let v=o[p][1];if(v===""||v==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?` +`}};rs.YAMLError=is;rs.YAMLParseError=yh;rs.YAMLWarning=Nh;rs.prettifyError=H_});var as=C(Xw=>{"use strict";function D_(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,m=!1,p=null,v=null,g=null,y=null,E=null,S=null,k=null;for(let N of e)switch(m&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),p&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),N.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(p=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=N.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=N.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=N.source,l=!0,h=!0,(v||g)&&(y=N),u=!0;break;case"anchor":v&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=N,k??(k=N.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),g=N,k??(k=N.offset),l=!1,u=!1,m=!0;break}case i:(v||g)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),S=N,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){E&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let b=e[e.length-1],R=b?b.offset+b.source.length:n;return m&&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"),p&&(l&&p.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:S,spaceBefore:c,comment:d,hasNewline:h,anchor:v,tag:g,newlineAfterProp:y,end:R,start:k??R}}Xw.resolveProps=D_});var Dl=C(Qw=>{"use strict";function bh(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(` +`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(bh(t.key)||bh(t.value))return!0}return!1;default:return!0}}Qw.containsNewline=bh});var kh=C(Zw=>{"use strict";var F_=Dl();function M_(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&F_.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Zw.flowIndentCheck=M_});var Sh=C(ty=>{"use strict";var ey=Q();function B_(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||ey.isScalar(a)&&ey.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}ty.mapIncludes=B_});var sy=C(oy=>{"use strict";var iy=jr(),L_=Or(),ry=as(),q_=Dl(),ny=kh(),V_=Sh(),ay="All mapping items must start at the same column";function W_({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??L_.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:d,key:f,sep:h,value:m}=u,p=ry.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),v=!p.found;if(v){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",ay)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=` +`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||q_.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==r.indent&&n(c,"BAD_INDENT",ay);i.atKey=!0;let g=p.end,y=f?e(i,f,p,n):t(i,g,d,null,p,n);i.schema.compat&&ny.flowIndentCheck(r.indent,f,n),i.atKey=!1,V_.mapIncludes(i,s.items,y)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let E=ry.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=E.end,E.found){v&&(m?.type==="block-map"&&!E.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&p.start{"use strict";var z_=Hr(),J_=as(),G_=kh();function U_({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??z_.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:d}of r.items){let f=J_.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&G_.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}cy.resolveBlockSeq=U_});var Pa=C(uy=>{"use strict";function K_(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}}uy.resolveEnd=K_});var py=C(hy=>{"use strict";var Y_=Q(),X_=jr(),dy=Or(),Q_=Hr(),Z_=Pa(),fy=as(),eT=Dl(),tT=Sh(),Eh="Block collections are not allowed within flow collections",Ph=e=>e&&(e.type==="block-map"||e.type==="block-seq");function iT({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?dy.YAMLMap:Q_.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let v=0;v0){let v=Z_.resolveEnd(m,p,i.options.strict,n);v.comment&&(l.comment?l.comment+=` +`+v.comment:l.comment=v.comment),l.range=[r.offset,p,v.offset]}else l.range=[r.offset,p,p];return l}hy.resolveFlowCollection=iT});var vy=C(my=>{"use strict";var rT=Q(),nT=De(),aT=Or(),oT=Hr(),sT=sy(),cT=ly(),lT=py();function Rh(e,t,i,r,n,a){let o=i.type==="block-map"?sT.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?cT.resolveBlockSeq(e,t,i,r,a):lT.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function uT(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!h||h.offsetf.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Rh(e,t,i,n,o)}let l=Rh(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=rT.isNode(u)?u:new nT.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}my.composeCollection=uT});var xh=C(gy=>{"use strict";var Ch=De();function dT(e,t,i){let r=t.offset,n=fT(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Ch.Scalar.BLOCK_FOLDED:Ch.Scalar.BLOCK_LITERAL,o=t.source?hT(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let v=o[p][1];if(v===""||v==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",v=r+n.length;return t.source&&(v+=t.source.length),{value:p,type:a,comment:n.comment,range:[r,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let p=0;pc&&(c=v.length);else{v.length=s;--p)o[p][0].length>c&&(s=p+1);let d="",f="",h=!1;for(let p=0;pc||g[0]===" "?(f===" "?f=` @@ -84,41 +84,41 @@ ${l} `+o[p][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let m=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,m,m]}}function dT({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f{"use strict";var Ah=De(),hT=Pa();function pT(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,m)=>i(r+f,h,m);switch(n){case"scalar":s=Ah.Scalar.PLAIN,c=mT(a,l);break;case"single-quoted-scalar":s=Ah.Scalar.QUOTE_SINGLE,c=vT(a,l);break;case"double-quoted-scalar":s=Ah.Scalar.QUOTE_DOUBLE,c=gT(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=hT.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function mT(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),gy(e)}function vT(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),gy(e.slice(1,-1)).replace(/''/g,"'")}function gy(e){let t,i;try{t=new RegExp(`(.*?)(?{"use strict";var Ah=De(),pT=Pa();function mT(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,m)=>i(r+f,h,m);switch(n){case"scalar":s=Ah.Scalar.PLAIN,c=vT(a,l);break;case"single-quoted-scalar":s=Ah.Scalar.QUOTE_SINGLE,c=gT(a,l);break;case"double-quoted-scalar":s=Ah.Scalar.QUOTE_DOUBLE,c=wT(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=pT.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function vT(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),wy(e)}function gT(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),wy(e.slice(1,-1)).replace(/''/g,"'")}function wy(e){let t,i;try{t=new RegExp(`(.*?)(?a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function wT(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===` +`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function yT(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===` `||r==="\r")&&!(r==="\r"&&e[t+2]!==` `);)r===` `&&(i+=` -`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var yT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function NT(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}}wy.resolveFlowScalar=pT});var by=C(Ny=>{"use strict";var xn=Q(),yy=De(),bT=xh(),kT=_h();function ST(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?bT.resolveBlockScalar(e,t,r):kT.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[xn.SCALAR]:c?l=ET(e.schema,n,c,i,r):t.type==="scalar"?l=PT(e,n,t,r):l=e.schema[xn.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=xn.isScalar(d)?d:new yy.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new yy.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 ET(e,t,i,r,n){if(i==="!")return e[xn.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[xn.SCALAR])}function PT({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[xn.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[xn.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}Ny.composeScalar=ST});var Sy=C(ky=>{"use strict";function RT(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}ky.emptyScalarPosition=RT});var Ry=C(Ih=>{"use strict";var CT=Mo(),xT=Q(),AT=my(),Ey=by(),_T=Pa(),TT=Sy(),IT={composeNode:Py,composeEmptyNode:Th};function Py(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=jT(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=Ey.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=AT.composeCollection(IT,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Th(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&&(!xT.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 Th(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:TT.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Ey.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function jT({options:e},{offset:t,source:i,end:r},n){let a=new CT.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=_T.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ih.composeEmptyNode=Th;Ih.composeNode=Py});var Ay=C(xy=>{"use strict";var $T=ts(),Cy=Ry(),OT=Pa(),HT=as();function DT(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new $T.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=HT.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?Cy.composeNode(l,n,u,o):Cy.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=OT.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}xy.composeDoc=DT});var $h=C(Iy=>{"use strict";var FT=zc("process"),MT=yf(),BT=ts(),os=ns(),_y=Q(),LT=Ay(),qT=Pa();function ss(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 Ty(e){let t="",i=!1,r=!1;for(let n=0;n{"use strict";var xn=Q(),Ny=De(),kT=xh(),ST=_h();function ET(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?kT.resolveBlockScalar(e,t,r):ST.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[xn.SCALAR]:c?l=PT(e.schema,n,c,i,r):t.type==="scalar"?l=RT(e,n,t,r):l=e.schema[xn.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=xn.isScalar(d)?d:new Ny.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Ny.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 PT(e,t,i,r,n){if(i==="!")return e[xn.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[xn.SCALAR])}function RT({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[xn.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[xn.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}by.composeScalar=ET});var Ey=C(Sy=>{"use strict";function CT(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}Sy.emptyScalarPosition=CT});var Cy=C(Ih=>{"use strict";var xT=Mo(),AT=Q(),_T=vy(),Py=ky(),TT=Pa(),IT=Ey(),jT={composeNode:Ry,composeEmptyNode:Th};function Ry(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=$T(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=Py.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=_T.composeCollection(jT,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Th(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&&(!AT.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 Th(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:IT.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Py.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function $T({options:e},{offset:t,source:i,end:r},n){let a=new xT.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=TT.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ih.composeEmptyNode=Th;Ih.composeNode=Ry});var _y=C(Ay=>{"use strict";var OT=ts(),xy=Cy(),HT=Pa(),DT=as();function FT(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new OT.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=DT.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?xy.composeNode(l,n,u,o):xy.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=HT.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Ay.composeDoc=FT});var $h=C(jy=>{"use strict";var MT=zc("process"),BT=yf(),LT=ts(),os=ns(),Ty=Q(),qT=_y(),VT=Pa();function ss(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 Iy(e){let t="",i=!1,r=!1;for(let n=0;n{let o=ss(i);a?this.warnings.push(new os.YAMLWarning(o,r,n)):this.errors.push(new os.YAMLParseError(o,r,n))},this.directives=new MT.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Ty(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} -${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(_y.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];_y.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r} +`)+(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 jh=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ss(i);a?this.warnings.push(new os.YAMLWarning(o,r,n)):this.errors.push(new os.YAMLParseError(o,r,n))},this.directives=new BT.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Iy(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment} +${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ty.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ty.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r} ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r} -${o}`:r}}if(i){for(let a=0;a{let a=ss(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=LT.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 os.YAMLParseError(ss(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 os.YAMLParseError(ss(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=qT.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} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new os.YAMLParseError(ss(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 BT.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}}};Iy.Composer=jh});var Oy=C(Fl=>{"use strict";var VT=xh(),WT=_h(),zT=ns(),jy=Wo();function JT(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 zT.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return WT.resolveFlowScalar(e,t,r);case"block-scalar":return VT.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function GT(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=jy.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:` +${o}`:r}}if(i){for(let a=0;a{let a=ss(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=qT.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 os.YAMLParseError(ss(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 os.YAMLParseError(ss(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=VT.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} +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new os.YAMLParseError(ss(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 LT.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}}};jy.Composer=jh});var Hy=C(Fl=>{"use strict";var WT=xh(),zT=_h(),JT=ns(),$y=Wo();function GT(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 JT.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return zT.resolveFlowScalar(e,t,r);case"block-scalar":return WT.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function UT(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=$y.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:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),u=s.substring(0,l),d=s.substring(l+1)+` -`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return $y(f,c)||f.push({type:"newline",offset:-1,indent:r,source:` -`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function UT(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=jy.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":KT(e,c);break;case'"':Oh(e,c,"double-quoted-scalar");break;case"'":Oh(e,c,"single-quoted-scalar");break;default:Oh(e,c,"scalar")}}function KT(e,t){let i=t.indexOf(` +`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return Oy(f,c)||f.push({type:"newline",offset:-1,indent:r,source:` +`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function KT(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=$y.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":YT(e,c);break;case'"':Oh(e,c,"double-quoted-scalar");break;case"'":Oh(e,c,"single-quoted-scalar");break;default:Oh(e,c,"scalar")}}function YT(e,t){let i=t.indexOf(` `),r=t.substring(0,i),n=t.substring(i+1)+` -`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];$y(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` -`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function $y(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 Oh(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:` -`};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})}}}Fl.createScalarToken=GT;Fl.resolveAsScalar=JT;Fl.setScalarValue=UT});var Dy=C(Hy=>{"use strict";var YT=e=>"type"in e?Bl(e):Ml(e);function Bl(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Bl(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ml(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ml(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ml(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 Ml({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Bl(t)),i)for(let a of i)n+=a.source;return r&&(n+=Bl(r)),n}Hy.stringify=YT});var Ly=C(By=>{"use strict";var Hh=Symbol("break visit"),XT=Symbol("skip children"),Fy=Symbol("remove item");function An(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),My(Object.freeze([]),e,t)}An.BREAK=Hh;An.SKIP=XT;An.REMOVE=Fy;An.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};An.parentCollection=(e,t)=>{let i=An.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 My(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{"use strict";var Dh=Oy(),QT=Dy(),ZT=Ly(),Fh="\uFEFF",Mh="",Bh="",Lh="",eI=e=>!!e&&"items"in e,tI=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function iI(e){switch(e){case Fh:return"";case Mh:return"";case Bh:return"";case Lh:return"";default:return JSON.stringify(e)}}function rI(e){switch(e){case Fh:return"byte-order-mark";case Mh:return"doc-mode";case Bh:return"flow-error-end";case Lh:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];Oy(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` +`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Oy(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 Oh(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:` +`};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})}}}Fl.createScalarToken=UT;Fl.resolveAsScalar=GT;Fl.setScalarValue=KT});var Fy=C(Dy=>{"use strict";var XT=e=>"type"in e?Bl(e):Ml(e);function Bl(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Bl(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ml(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ml(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ml(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 Ml({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Bl(t)),i)for(let a of i)n+=a.source;return r&&(n+=Bl(r)),n}Dy.stringify=XT});var qy=C(Ly=>{"use strict";var Hh=Symbol("break visit"),QT=Symbol("skip children"),My=Symbol("remove item");function An(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),By(Object.freeze([]),e,t)}An.BREAK=Hh;An.SKIP=QT;An.REMOVE=My;An.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};An.parentCollection=(e,t)=>{let i=An.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 By(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{"use strict";var Dh=Hy(),ZT=Fy(),eI=qy(),Fh="\uFEFF",Mh="",Bh="",Lh="",tI=e=>!!e&&"items"in e,iI=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function rI(e){switch(e){case Fh:return"";case Mh:return"";case Bh:return"";case Lh:return"";default:return JSON.stringify(e)}}function nI(e){switch(e){case Fh:return"byte-order-mark";case Mh:return"doc-mode";case Bh:return"flow-error-end";case Lh:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}At.createScalarToken=Dh.createScalarToken;At.resolveAsScalar=Dh.resolveAsScalar;At.setScalarValue=Dh.setScalarValue;At.stringify=QT.stringify;At.visit=ZT.visit;At.BOM=Fh;At.DOCUMENT=Mh;At.FLOW_END=Bh;At.SCALAR=Lh;At.isCollection=eI;At.isScalar=tI;At.prettyToken=iI;At.tokenType=rI});var Wh=C(Vy=>{"use strict";var cs=Ll();function Ni(e){switch(e){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var qy=new Set("0123456789ABCDEFabcdef"),nI=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ql=new Set(",[]{}"),aI=new Set(` ,[]{} -\r `),qh=e=>!e||aI.has(e),Vh=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===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}At.createScalarToken=Dh.createScalarToken;At.resolveAsScalar=Dh.resolveAsScalar;At.setScalarValue=Dh.setScalarValue;At.stringify=ZT.stringify;At.visit=eI.visit;At.BOM=Fh;At.DOCUMENT=Mh;At.FLOW_END=Bh;At.SCALAR=Lh;At.isCollection=tI;At.isScalar=iI;At.prettyToken=rI;At.tokenType=nI});var Wh=C(Wy=>{"use strict";var cs=Ll();function Ni(e){switch(e){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var Vy=new Set("0123456789ABCDEFabcdef"),aI=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ql=new Set(",[]{}"),oI=new Set(` ,[]{} +\r `),qh=e=>!e||oI.has(e),Vh=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===` `?!0:i==="\r"?this.buffer[t+1]===` `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===` `||!n&&!this.atEnd)return t+r+1}return i===` @@ -133,14 +133,14 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield cs.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(Ni(a)||t&&ql.has(a))break;i=r}else if(Ni(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===` `?(r+=1,n=` `,a=this.buffer[r+1]):i=r),a==="#"||t&&ql.has(a))break;if(n===` -`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&ql.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield cs.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(qh),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ni(r)||i&&ql.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(;!Ni(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(nI.has(i))i=this.buffer[++t];else if(i==="%"&&qy.has(this.buffer[t+1])&&qy.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` +`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&ql.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield cs.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(qh),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ni(r)||i&&ql.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(;!Ni(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(aI.has(i))i=this.buffer[++t];else if(i==="%"&&Vy.has(this.buffer[t+1])&&Vy.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===` `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,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)}};Vy.Lexer=Vh});var Jh=C(Wy=>{"use strict";var zh=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var oI=zc("process"),zy=Ll(),sI=Wh();function Dr(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Wl(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&Gy(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&&Jy(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent0&&(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)}};Wy.Lexer=Vh});var Jh=C(zy=>{"use strict";var zh=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var sI=zc("process"),Jy=Ll(),cI=Wh();function Dr(e,t){for(let i=0;i=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Wl(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&Uy(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&&Gy(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.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;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":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(Dr(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(Uy(i.key)&&!Dr(i.sep,"newline")){let o=Ra(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(Dr(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ra(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]}):Dr(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&&!Dr(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)){Wl(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||Dr(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=Vl(r),a=Ra(n);Gy(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` +`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let 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)){Wl(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;st.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":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(Dr(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(Ky(i.key)&&!Dr(i.sep,"newline")){let o=Ra(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(Dr(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ra(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]}):Dr(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&&!Dr(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)){Wl(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||Dr(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=Vl(r),a=Ra(n);Uy(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Vl(t),r=Ra(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=Vl(t),r=Ra(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())}}};Ky.Parser=Gh});var eN=C(us=>{"use strict";var Yy=$h(),cI=ts(),ls=ns(),lI=If(),uI=Q(),dI=Jh(),Xy=Uh();function Qy(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new dI.LineCounter||null,prettyErrors:t}}function fI(e,t={}){let{lineCounter:i,prettyErrors:r}=Qy(t),n=new Xy.Parser(i?.addNewLine),a=new Yy.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(ls.prettifyError(e,i)),s.warnings.forEach(ls.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Zy(e,t={}){let{lineCounter:i,prettyErrors:r}=Qy(t),n=new Xy.Parser(i?.addNewLine),a=new Yy.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 ls.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(ls.prettifyError(e,i)),o.warnings.forEach(ls.prettifyError(e,i))),o}function hI(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Zy(e,i);if(!n)return null;if(n.warnings.forEach(a=>lI.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 pI(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 uI.isDocument(e)&&!r?e.toString(i):new cI.Document(e,r,i).toString(i)}us.parse=hI;us.parseAllDocuments=fI;us.parseDocument=Zy;us.stringify=pI});var _n=C(oe=>{"use strict";var mI=$h(),vI=ts(),gI=ph(),Kh=ns(),wI=Mo(),Fr=Q(),yI=jr(),NI=De(),bI=Or(),kI=Hr(),SI=Ll(),EI=Wh(),PI=Jh(),RI=Uh(),zl=eN(),tN=Oo();oe.Composer=mI.Composer;oe.Document=vI.Document;oe.Schema=gI.Schema;oe.YAMLError=Kh.YAMLError;oe.YAMLParseError=Kh.YAMLParseError;oe.YAMLWarning=Kh.YAMLWarning;oe.Alias=wI.Alias;oe.isAlias=Fr.isAlias;oe.isCollection=Fr.isCollection;oe.isDocument=Fr.isDocument;oe.isMap=Fr.isMap;oe.isNode=Fr.isNode;oe.isPair=Fr.isPair;oe.isScalar=Fr.isScalar;oe.isSeq=Fr.isSeq;oe.Pair=yI.Pair;oe.Scalar=NI.Scalar;oe.YAMLMap=bI.YAMLMap;oe.YAMLSeq=kI.YAMLSeq;oe.CST=SI;oe.Lexer=EI.Lexer;oe.LineCounter=PI.LineCounter;oe.Parser=RI.Parser;oe.parse=zl.parse;oe.parseAllDocuments=zl.parseAllDocuments;oe.parseDocument=zl.parseDocument;oe.stringify=zl.stringify;oe.visit=tN.visit;oe.visitAsync=tN.visitAsync});import{pathToFileURL as b1}from"url";import{randomUUID as nD}from"node:crypto";import{promises as tt}from"node:fs";import Pt from"node:path";import{execFileSync as MC}from"child_process";import To from"path";function Cr(e,t){return MC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function BC(e,t){let i=To.normalize(e),r=To.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function me(e){try{let t=To.resolve(Cr(e,["rev-parse","--show-toplevel"])),r=Cr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?To.resolve(r.slice(9)):t,a=null;try{a=Cr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!BC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Jc(e){try{Cr(e,["rev-parse","--is-inside-work-tree"]);let t=Cr(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:To.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 Zt(e){return Jc(e).map(t=>t.root)}function Io(e,t){try{return Cr(e,["check-ref-format","--branch",t]),Cr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function uf(e,t){try{let i=Cr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{randomUUID as LC}from"crypto";import{promises as ot}from"fs";import gi from"path";function xr(e){return e!==0&&e!==0n&&e!=="0"}function Ye(e,t){return xr(e.dev)&&xr(t.dev)&&xr(e.ino)&&xr(t.ino)}function q(e,t){let i=xr(e.dev)&&xr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=xr(e.ino)&&xr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ff(e,t){let i=gi.relative(e,t);return i===""||!gi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gi.sep}`)}function qC(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function df(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lg(e){let t=await ot.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 ot.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function jo(e){for(let t of e){let i=await ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!qC(t,i)||await ot.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function VC(e,t){let i=gi.resolve(e),r=gi.resolve(t);if(!ff(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await lg(i)],a=gi.relative(i,r).split(gi.sep).filter(Boolean),o=i;for(let s of a){await jo(n),o=gi.join(o,s);try{await ot.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await lg(o);if(!ff(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await jo(n),n}async function WC(e){let t;try{t=await ot.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 ug(e,t,i={}){let r=gi.dirname(e),n=i.containedRoot?await VC(i.containedRoot,r):null;n||await ot.mkdir(r,{recursive:!0});let a=gi.join(r,`.${gi.basename(e)}.${LC()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await ot.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([ot.lstat(a),ot.realpath(a)]);if(await jo(n),!c.isFile()||c.isSymbolicLink()||!df(s,c)||!ff(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!df(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await jo(n);let c=await ot.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!df(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await ot.link(a,e),await ot.unlink(a)):await ot.rename(a,e),await WC(r)}catch(c){if(await o?.close(),!n)await ot.rm(a,{force:!0});else try{await jo(n),await ot.rm(a,{force:!0})}catch{}throw c}}async function Ne(e,t,i={}){await ug(e,t,i)}async function dg(e,t,i={}){await ug(e,t,i)}async function ve(e,t,i={}){await Ne(e,JSON.stringify(t,null,2)+` -`,i)}import{createHash as UC}from"node:crypto";import{promises as wi}from"node:fs";import ei from"node:path";import{TextDecoder as KC}from"node:util";import hf from"path";var zC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),JC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function GC(e){return e.toLowerCase().startsWith(".env")}function Hi(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>GC(r))?"environment-file":i.some(r=>JC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>zC.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function pf(e,t){let i=Hi(t);if(i)return i;let r=hf.resolve(e.projectRoot,...t.split("/")),n=hf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===hf.resolve(e.configFile)?"native-runtime":null}var $o=1024*1024;function mf(e,t){let i=ei.relative(e,t);return i===""||!ei.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ei.sep}`)}function YC(e){let t=ei.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})||ei.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=Hi(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 XC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function QC(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function fg(e){let t=await wi.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await wi.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ZC(e,t){let i=ei.resolve(e),r=ei.resolve(t);if(!mf(i,r))throw new Error("Native artifact path is outside its root");let n=[await fg(i)],a=i;for(let o of ei.relative(i,r).split(ei.sep).filter(Boolean)){a=ei.join(a,o);let s=await fg(a);if(!mf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function hg(e){for(let t of e){let i=await wi.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!QC(t,i)||await wi.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ee(e){let t=YC(e.ref),i=e.maxBytes===null?null:XC(e.maxBytes??$o),r=ei.resolve(e.root,...t.split("/")),n=await ZC(e.root,ei.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await wi.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 wi.realpath(r);if(!mf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await wi.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),wi.lstat(r),wi.realpath(r)]);if(await hg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Gc(a,c)||!Gc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let E=i===null?h.length:i+1-f,S=await s.read(h,0,Math.min(h.length,E),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),wi.lstat(r),wi.realpath(r)]);if(await hg(n),!p.isFile()||p.isSymbolicLink()||v!==o||!Gc(c,m)||!Gc(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),y;try{y=new KC("utf-8",{fatal:!0}).decode(g)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:UC("sha256").update(g).digest("hex"),text:y}}finally{await s.close()}}var Xu=ma(_n(),1);import{promises as Ls}from"fs";import ut from"path";import ZI from"path";var ds=ma(_n(),1);import Gl from"path";var fs=64*1024,Ul=1024,Kl=64,Xh=5,CI=[".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/**",".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/**"],xI=["**/.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"],rN=[...CI,...xI].sort((e,t)=>e.localeCompare(t,"en"));function nN(e){let t=[...e],i=new Set(e);for(let r of rN)i.has(r)||(i.add(r),t.push(r));return t}var _t={include:["**/*"],exclude:[...rN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Jl={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it. +`,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=Vl(t),r=Ra(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=Vl(t),r=Ra(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())}}};Yy.Parser=Gh});var tN=C(us=>{"use strict";var Xy=$h(),lI=ts(),ls=ns(),uI=If(),dI=Q(),fI=Jh(),Qy=Uh();function Zy(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new fI.LineCounter||null,prettyErrors:t}}function hI(e,t={}){let{lineCounter:i,prettyErrors:r}=Zy(t),n=new Qy.Parser(i?.addNewLine),a=new Xy.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(ls.prettifyError(e,i)),s.warnings.forEach(ls.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function eN(e,t={}){let{lineCounter:i,prettyErrors:r}=Zy(t),n=new Qy.Parser(i?.addNewLine),a=new Xy.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 ls.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(ls.prettifyError(e,i)),o.warnings.forEach(ls.prettifyError(e,i))),o}function pI(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=eN(e,i);if(!n)return null;if(n.warnings.forEach(a=>uI.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 mI(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 dI.isDocument(e)&&!r?e.toString(i):new lI.Document(e,r,i).toString(i)}us.parse=pI;us.parseAllDocuments=hI;us.parseDocument=eN;us.stringify=mI});var _n=C(oe=>{"use strict";var vI=$h(),gI=ts(),wI=ph(),Kh=ns(),yI=Mo(),Fr=Q(),NI=jr(),bI=De(),kI=Or(),SI=Hr(),EI=Ll(),PI=Wh(),RI=Jh(),CI=Uh(),zl=tN(),iN=Oo();oe.Composer=vI.Composer;oe.Document=gI.Document;oe.Schema=wI.Schema;oe.YAMLError=Kh.YAMLError;oe.YAMLParseError=Kh.YAMLParseError;oe.YAMLWarning=Kh.YAMLWarning;oe.Alias=yI.Alias;oe.isAlias=Fr.isAlias;oe.isCollection=Fr.isCollection;oe.isDocument=Fr.isDocument;oe.isMap=Fr.isMap;oe.isNode=Fr.isNode;oe.isPair=Fr.isPair;oe.isScalar=Fr.isScalar;oe.isSeq=Fr.isSeq;oe.Pair=NI.Pair;oe.Scalar=bI.Scalar;oe.YAMLMap=kI.YAMLMap;oe.YAMLSeq=SI.YAMLSeq;oe.CST=EI;oe.Lexer=PI.Lexer;oe.LineCounter=RI.LineCounter;oe.Parser=CI.Parser;oe.parse=zl.parse;oe.parseAllDocuments=zl.parseAllDocuments;oe.parseDocument=zl.parseDocument;oe.stringify=zl.stringify;oe.visit=iN.visit;oe.visitAsync=iN.visitAsync});import{pathToFileURL as P1}from"url";import{randomUUID as aD}from"node:crypto";import{promises as tt}from"node:fs";import Pt from"node:path";import{execFileSync as BC}from"child_process";import To from"path";function Cr(e,t){return BC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function LC(e,t){let i=To.normalize(e),r=To.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function me(e){try{let t=To.resolve(Cr(e,["rev-parse","--show-toplevel"])),r=Cr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?To.resolve(r.slice(9)):t,a=null;try{a=Cr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!LC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Jc(e){try{Cr(e,["rev-parse","--is-inside-work-tree"]);let t=Cr(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:To.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 Zt(e){return Jc(e).map(t=>t.root)}function Io(e,t){try{return Cr(e,["check-ref-format","--branch",t]),Cr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function uf(e,t){try{let i=Cr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{randomUUID as qC}from"crypto";import{promises as ot}from"fs";import gi from"path";function xr(e){return e!==0&&e!==0n&&e!=="0"}function Ye(e,t){return xr(e.dev)&&xr(t.dev)&&xr(e.ino)&&xr(t.ino)}function q(e,t){let i=xr(e.dev)&&xr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=xr(e.ino)&&xr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ff(e,t){let i=gi.relative(e,t);return i===""||!gi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gi.sep}`)}function VC(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function df(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ug(e){let t=await ot.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 ot.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function jo(e){for(let t of e){let i=await ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!VC(t,i)||await ot.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function WC(e,t){let i=gi.resolve(e),r=gi.resolve(t);if(!ff(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await ug(i)],a=gi.relative(i,r).split(gi.sep).filter(Boolean),o=i;for(let s of a){await jo(n),o=gi.join(o,s);try{await ot.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await ug(o);if(!ff(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await jo(n),n}async function zC(e){let t;try{t=await ot.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 dg(e,t,i={}){let r=gi.dirname(e),n=i.containedRoot?await WC(i.containedRoot,r):null;n||await ot.mkdir(r,{recursive:!0});let a=gi.join(r,`.${gi.basename(e)}.${qC()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await ot.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([ot.lstat(a),ot.realpath(a)]);if(await jo(n),!c.isFile()||c.isSymbolicLink()||!df(s,c)||!ff(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!df(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await jo(n);let c=await ot.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!df(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await ot.link(a,e),await ot.unlink(a)):await ot.rename(a,e),await zC(r)}catch(c){if(await o?.close(),!n)await ot.rm(a,{force:!0});else try{await jo(n),await ot.rm(a,{force:!0})}catch{}throw c}}async function Ne(e,t,i={}){await dg(e,t,i)}async function fg(e,t,i={}){await dg(e,t,i)}async function ve(e,t,i={}){await Ne(e,JSON.stringify(t,null,2)+` +`,i)}import{createHash as KC}from"node:crypto";import{promises as wi}from"node:fs";import ei from"node:path";import{TextDecoder as YC}from"node:util";import hf from"path";var JC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),GC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function UC(e){return e.toLowerCase().startsWith(".env")}function Hi(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>UC(r))?"environment-file":i.some(r=>GC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>JC.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function pf(e,t){let i=Hi(t);if(i)return i;let r=hf.resolve(e.projectRoot,...t.split("/")),n=hf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===hf.resolve(e.configFile)?"native-runtime":null}var $o=1024*1024;function mf(e,t){let i=ei.relative(e,t);return i===""||!ei.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ei.sep}`)}function XC(e){let t=ei.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})||ei.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=Hi(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 QC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ZC(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function hg(e){let t=await wi.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await wi.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ex(e,t){let i=ei.resolve(e),r=ei.resolve(t);if(!mf(i,r))throw new Error("Native artifact path is outside its root");let n=[await hg(i)],a=i;for(let o of ei.relative(i,r).split(ei.sep).filter(Boolean)){a=ei.join(a,o);let s=await hg(a);if(!mf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function pg(e){for(let t of e){let i=await wi.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!ZC(t,i)||await wi.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ee(e){let t=XC(e.ref),i=e.maxBytes===null?null:QC(e.maxBytes??$o),r=ei.resolve(e.root,...t.split("/")),n=await ex(e.root,ei.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await wi.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 wi.realpath(r);if(!mf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await wi.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),wi.lstat(r),wi.realpath(r)]);if(await pg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Gc(a,c)||!Gc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let E=i===null?h.length:i+1-f,S=await s.read(h,0,Math.min(h.length,E),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),wi.lstat(r),wi.realpath(r)]);if(await pg(n),!p.isFile()||p.isSymbolicLink()||v!==o||!Gc(c,m)||!Gc(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),y;try{y=new YC("utf-8",{fatal:!0}).decode(g)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:KC("sha256").update(g).digest("hex"),text:y}}finally{await s.close()}}var Xu=ma(_n(),1);import{promises as Ls}from"fs";import ut from"path";import ej from"path";var ds=ma(_n(),1);import Gl from"path";var fs=64*1024,Ul=1024,Kl=64,Xh=5,xI=[".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/**",".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/**"],AI=["**/.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"],nN=[...xI,...AI].sort((e,t)=>e.localeCompare(t,"en"));function aN(e){let t=[...e],i=new Set(e);for(let r of nN)i.has(r)||(i.add(r),t.push(r));return t}var _t={include:["**/*"],exclude:[...nN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Jl={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it. # ambient_resume: true | false`,hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents. # language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time. # clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation. @@ -158,43 +158,43 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。 # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。 # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。 -# 可选值:true | false`}};function aN(e,t){return Jl[t][e]}function AI(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Jl.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Jl.en)return o}if(n===2&&t===null&&a==="hook")return"hook";if(n===2&&t==="hook"&&a==="allow_paths")return"hook.allow_paths";if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Jl.en)return o}return null}function hs(e,t){let i=[],r=null,n=null;for(let a of(0,ds.stringify)(e).trimEnd().split(` -`)){let o=AI(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of aN(o,t).split(` +# 可选值:true | false`}};function oN(e,t){return Jl[t][e]}function _I(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Jl.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Jl.en)return o}if(n===2&&t===null&&a==="hook")return"hook";if(n===2&&t==="hook"&&a==="allow_paths")return"hook.allow_paths";if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Jl.en)return o}return null}function hs(e,t){let i=[],r=null,n=null;for(let a of(0,ds.stringify)(e).trimEnd().split(` +`)){let o=_I(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of oN(o,t).split(` `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":a.startsWith("hook:")?r="hook":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(` -`)}function _I(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Gl.posix.isAbsolute(i)||Gl.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 Tn(e){let t=_I(e,"native.artifact_root");return t.length===0?".":t.join("/")}function oN(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 Yl(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||Gl.posix.isAbsolute(r)||Gl.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 xa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sN(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 Xl(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>Ul)throw new Error(`${t} exceeds ${Ul} characters`);let i=0;for(let r=0;rKl)throw new Error(`${t} contains more than ${Kl} wildcard tokens`);return e}function iN(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=>Xl(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Yh(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 TI(e){if(e===void 0)return{..._t,include:[..._t.include],exclude:[..._t.exclude]};let t=xa(e,"native.snapshot");return{include:iN(t.include,"native.snapshot.include",_t.include),exclude:iN(t.exclude,"native.snapshot.exclude",_t.exclude),max_files:Yh(t.max_files,_t.max_files,"native.snapshot.max_files"),max_total_bytes:Yh(t.max_total_bytes,_t.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Yh(t.max_duration_ms,_t.max_duration_ms,"native.snapshot.max_duration_ms")}}function II(e){if(e===void 0)return;let t=xa(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=xa(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:Tn(r),toArtifactRoot:Tn(n),stage:a,...o?{cleanup:o}:{}}}function jI(e,t={}){let i=xa(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??Xh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=II(i.pending_root_move);return{artifact_root:Tn(r),language:sN(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:TI(i.snapshot),...s?{pending_root_move:s}:{}}}function $I(e){let t=xa(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:oN(t.artifact_layout),language:sN(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function OI(e){let i=xa(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)=>Yl(r,`hook.allow_paths[${n}]`)))]}}function HI(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function DI(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 Aa(e,t={}){let i=(0,ds.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=HI(n.ambient_resume),o=n.hook===void 0?void 0:OI(n.hook),s=n.native===void 0?void 0:jI(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:$I(n.classic),l=DI(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 cN(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function lN(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.pending_root_move?{pending_root_move:cN(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function Ca(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ps(e,t){let i=lN(t),r=Aa((0,ds.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...Ca(e.hook),allow_paths:[...r.hook.allow_paths]}),r.native){let a=Ca(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=Ca(a.pending_root_move),c=cN(r.native.pending_root_move),l=Ca(s.cleanup),u=Ca(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...Ca(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}function Ql(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Tn(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Xh,snapshot:{..._t,include:[..._t.include],exclude:[..._t.exclude]}}}}import{createHash as MI}from"crypto";import{promises as tu}from"fs";import Mr from"path";import{constants as Zl,promises as In}from"fs";var bi=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Qh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function uN(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ms(e){return{dev:e.dev,ino:e.ino,birthtime:Qh(e)}}function eu(e,t){let i=ms(e),r=ms(t);return Ye(i,r)?q(i,r):q(i,r)&&Qh(e)===Qh(t)&&uN(e)===uN(t)&&e.size===t.size}async function jn(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 In.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new bi("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new bi("too-large",`${r} exceeds ${t} bytes`);let o=await In.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:ms(a)});let s=process.platform==="win32"?Zl.O_RDONLY:Zl.O_RDONLY|Zl.O_NOFOLLOW|Zl.O_NONBLOCK,c;try{c=await In.open(e,s)}catch(l){throw l.code==="ELOOP"?new bi("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),In.lstat(e,{bigint:n}),In.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!eu(a,l)||!eu(a,u))throw new bi("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:ms(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:E}=await c.read(m,0,Math.min(m.length,y),null);if(E===0)break;if(h+=E,h>t)throw new bi("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([c.stat({bigint:n}),In.lstat(e,{bigint:n}),In.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!eu(a,p)||!eu(a,v))throw new bi("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:ms(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:g}}finally{await c.close()}}function FI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Zh(e,t){let i=Mr.relative(e,t);return i===""||!Mr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Mr.sep}`)}async function dN(e,t){let i=Mr.resolve(e),r=await tu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return tu.realpath(i)}async function fN(e,t,i,r){let n=e;for(let a=0;a{if(!Zh(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await fN(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var vs=".comet/config.yaml";function ep(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function BI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function iu(e,t={}){return(await gs(e,t)).document}async function hN(e){try{return(await Mi(e,vs,fs,{label:vs})).bytes}catch(t){if(BI(t))return null;throw t}}function pN(e){return e?{exists:!0,sha256:MI("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ru(e){return pN(await hN(e))}async function gs(e,t={}){let i=await hN(e);return{document:i?Aa(i.toString("utf8"),t):null,identity:pN(i)}}async function tp(e){return(await iu(e))?.config??null}import{randomUUID as LI}from"crypto";import{constants as qI,promises as gt}from"fs";import ki from"path";async function np(e,t){try{return await gt.link(e,t),{linked:!0}}catch(i){let r=i.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw i}return await gt.copyFile(e,t,qI.COPYFILE_EXCL),{linked:!1}}function rp(e,t){let i=ki.relative(e,t);return i===""||!ki.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ki.sep}`)}function nu(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function VI(e,t){return q(e,nu(t))}function ip(e,t){let i=nu(e),r=nu(t);return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mN(e){let t=await gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await gt.realpath(e),...nu(t)}}async function ws(e){for(let t of e){let i=await gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!VI(t,i)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function WI(e,t){let i=ki.resolve(e),r=ki.resolve(t);if(!rp(i,r))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await mN(i)],a=ki.relative(i,r).split(ki.sep).filter(Boolean),o=i;for(let s of a){await ws(n),o=ki.join(o,s);try{await gt.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await mN(o);if(!rp(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ws(n),n}async function zI(e){let t;try{t=await gt.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 JI(e,t,i){let r=ki.dirname(e),n=await WI(i.containedRoot,r),a=ki.join(r,`.${ki.basename(e)}.${LI()}.tmp`),o,s;try{await i.beforeTemporaryOpen?.(),o=await gt.open(a,"wx"),s=await o.stat();let[c,l]=await Promise.all([gt.lstat(a),gt.realpath(a)]);if(await ws(n),!c.isFile()||c.isSymbolicLink()||!ip(s,c)||!rp(n[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!ip(s,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await i.beforeCommit?.(),await ws(n);let u=await gt.lstat(a);if(!u.isFile()||u.isSymbolicLink()||!ip(u,s))throw new Error("Contained atomic write temporary file changed before commit");i.exclusive?(await np(a,e),await gt.unlink(a)):await gt.rename(a,e),await zI(r)}catch(c){await o?.close();try{await ws(n),await gt.rm(a,{force:!0})}catch{}throw c}}async function $n(e,t,i){await JI(e,t,i)}var _W=16*1024;async function ap(e,t){if(!t)return;let i=await ru(e);if(!ep(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as vN,promises as Bi}from"fs";import ie from"path";import KI from"os";var ys=".comet/config.yaml",YI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function op(e){try{return await Bi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function XI(e){try{let t=await Bi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ta(e,t){let i=ie.relative(e,t);return i===""||!ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ie.sep}`)}async function _a(e){let t=[],i=e;for(;!await op(i);){let n=ie.dirname(i);if(n===i)break;t.push(ie.basename(i)),i=n}let r=await Bi.realpath(i);return ie.resolve(r,...t.reverse())}async function sp(e){try{return(await Bi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function au(e){let t=ie.resolve(e);try{(await Bi.stat(t)).isDirectory()||(t=ie.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=ie.resolve(KI.homedir());for(;;){if(!(t===r&&i!==r)){let o=ie.join(t,...ys.split("/")),s=t===i||await XI(o);if(await op(o)&&s)return t}if(await op(ie.join(t,".git")))return t;let a=ie.dirname(t);if(a===t)return i;t=a}}function Br(e){return Tn(e)}async function QI(e,t){let i=Br(t),r=ie.resolve(e,...i.split("/")),n=await Bi.realpath(e),a=await _a(r);if(!Ta(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function re(e,t){let i=Br(t),r=await QI(e,i),n=ie.join(r,"comet");if(await sp(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_a(r),_a(n)]);if(!Ta(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=ie.resolve(e),c=ie.join(s,".comet","runtime","native");if(await sp(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Bi.realpath(s),_a(c)]);if(!Ta(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:ie.join(e,...ys.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:ie.join(n,"specs"),changesDir:ie.join(n,"changes"),archiveDir:ie.join(n,"archive"),runtimeDir:c,changesRuntimeDir:ie.join(c,"changes"),locksDir:ie.join(c,"locks"),transactionsDir:ie.join(c,"transactions")}}async function ou(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await T(e.nativeRoot,t),await Bi.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await T(e.projectRoot,t),await Bi.mkdir(t,{recursive:!0})}))}function wN(e){if(!YI.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ze(e,t){wN(t);let i=ie.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function On(e,t){wN(t);let i=ie.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function M(e,t){let i=ze(e,t);if(vN(i))return i;let r=On(e,t);return vN(r)?r:i}async function gN(e){try{let t=await Bi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ns(e,t){let i=ze(e,t),r=On(e,t),[n,a]=await Promise.all([gN(i),gN(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Lr(e,t){if(!t.startsWith("runtime/")||ie.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=ie.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=ie.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return Ta(ie.resolve(e),ie.resolve(t))}async function T(e,t){let i=ie.resolve(e),r=ie.resolve(t);if(!Ta(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await sp(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_a(i),_a(r)]);if(!Ta(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var cp=_t;var su=Xl,yN=nN;function Hn(e="docs",t="en"){return Ql(e,t)}async function Y(e){let t=(await iu(e))?.config??null;return t?.native?t:null}async function Ia(e){let t=await Y(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 Vt(e,t,i={}){let r=await gs(e,{allowPartialProject:!0}),n=ps(r.document?.value??{},t),a=ZI.join(e,...ys.split("/"));await Ne(a,hs(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ap(e,r.identity)}})}async function NN(e){let t=await au(e.startPath),i=await Y(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${ys} 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?Br(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??Hn(r??"docs"),a=await re(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Y$}from"fs";import X$ from"path";import{AsyncLocalStorage as ej}from"async_hooks";import{randomUUID as SN}from"crypto";import{promises as ii}from"fs";import EN from"os";import Ce from"path";var bN=16*1024,lp=".coordinator",tj=5e3,kN=new ej,cu=new Map;function ij(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function rj(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 PN(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 up(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ye(i,r)?q(i,r):q(i,r)&&e.size===t.size}function lu(e,t){return up(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function nj(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&lu(e.identity,t.identity)}async function Li(e){let t,i;try{let r=await jn(e,bN,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof bi?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${bN} 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:rj(JSON.parse(t.toString("utf8")),e),identity:PN(i)}}async function aj(e){return(await Li(e))?.owner??null}function dp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==EN.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=dj(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function oj(e,t){try{await ii.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ii.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function uu(e,t){let i=await Li(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lu(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ii.mkdir(t,{recursive:!0});let r=Ce.join(t,`${Ce.basename(e.file)}.${e.owner.id}.${SN()}.removed`);try{await ii.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Li(r);if(!n||n.owner.id!==e.owner.id||!up(n.identity,e.identity))throw await oj(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ii.rm(r,{force:!0}),"removed"}function RN(e){return{id:SN(),pid:process.pid,hostname:EN.hostname(),createdAt:new Date().toISOString(),operation:e}}async function CN(e,t){let i;try{i=await ii.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await aj(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)+` -`,"utf8"),await i.sync(),PN(await i.stat({bigint:!0}))}finally{await i.close()}}async function sj(e,t){let i=await T(e.runtimeDir,e.locksDir);await ii.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,Ce.join(i,lp));await ii.mkdir(r,{recursive:!0});let n=RN(t),a=Ce.join(r,`.${n.id}.tmp`),o=Ce.join(r,`${n.id}.claim`);try{let s=await CN(a,n);await ii.rename(a,o);let c=await Li(o);if(!c||!up(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 ii.rm(a,{force:!0})}}async function cj(e){let t=Ce.dirname(e.file),i=!1,r=Ce.basename(e.file);for(let n of await ii.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Ce.join(t,n.name);if(Ce.resolve(a)!==Ce.resolve(e.file))try{let o=await Li(a),s=dp(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await uu(o,t);continue}n.name=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 uj(e){let t=cu.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return cu.set(e,n),await t,()=>{i(),cu.get(e)===n&&cu.delete(e)}}async function du(e,t,i){let r=Ce.resolve(e.locksDir),n=kN.getStore();if(n?.has(r))return i();let a=await uj(r);try{let o=await lj(e,t),s=new Map(n??[]);return s.set(r,o),await kN.run(s,async()=>{try{return await i()}finally{await xN(o)}})}finally{a()}}async function Dn(e,t,i){let r=[...new Map(e.map(a=>[Ce.resolve(a.locksDir),a])).values()].sort((a,o)=>Ce.resolve(a.locksDir).localeCompare(Ce.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?du(o,t,()=>n(a+1)):i()};return n(0)}async function cr(e,t,i){return du(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await ii.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,Ce.join(r,ij(t))),a=RN(i),o=await CN(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function lr(e){await Li(e.file)&&await du({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Ce.basename(e.file)}`,async()=>{let t=await Li(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lu(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=Ce.join(e.locksDir,lp);await uu(t,i)})}function dj(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function bs(e){return dp(await Li(e))}async function fp(e,t,i){return du(e,`take over ${Ce.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(Ce.resolve(Ce.dirname(n))!==Ce.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await Li(n),o=dp(a);if(o.status==="missing")return{status:"missing"};if(i&&!nj(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=Ce.join(r,lp);return await uu(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as g$}from"node:fs";import kp from"node:path";import i$ from"node:path";import FN from"node:path";import AN from"node:path";import{createHash as fj}from"crypto";function Si(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function hj(e,t){t.has(e)&&Si("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&Si("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Si("symbol properties are not supported"),`[${e.map(r=>hp(r,t)).join(",")}]`}finally{t.delete(e)}}function pj(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Si("only plain objects are supported"),t.has(e)&&Si("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Si("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))&&Si("accessor properties are not supported"),`${JSON.stringify(o)}:${hp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function hp(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)||Si("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?hj(e,t):pj(e,t);case"bigint":case"function":case"symbol":case"undefined":return Si(`${typeof e} values are not supported`)}return Si("unsupported value type")}function ks(e){return hp(e,new Set)}function D(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 fj("sha256").update(`${e} -${ks(t)}`).digest("hex")}var mj="comet.native.acceptance.v1",vj=/^acceptance-[a-f0-9]{64}$/u,gj=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),wj=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,yj=/^[a-f0-9]{64}$/u,Nj=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function bj(e,t){return et?1:0}var ur=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Es=Object.freeze({maxCriteria:1024}),_N="",TN="";function IN(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:i,truncated:!0}}function jN(e,t){let i=t.toString(36),r=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function kj(e){if(!yj.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=Nj.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function Sj(e,t){let i=IN(e.text,ur.maxTextBytes),r=e.context.slice(0,ur.maxContextItems).map(n=>IN(n,ur.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function ON(e){let t=kj({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(bj),n=r.slice(0,ur.maxFailedCheckIds),a=e.criteria.slice(t,t+ur.maxItems);for(let c of a){let l=[...i,Sj(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:uur.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:our.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function mp(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 pp(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 $N(e){return e.includes("-->")||e.includes("--!>")}function*ja(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` +`)}function TI(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Gl.posix.isAbsolute(i)||Gl.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 Tn(e){let t=TI(e,"native.artifact_root");return t.length===0?".":t.join("/")}function sN(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 Yl(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||Gl.posix.isAbsolute(r)||Gl.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 xa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function cN(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 Xl(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>Ul)throw new Error(`${t} exceeds ${Ul} characters`);let i=0;for(let r=0;rKl)throw new Error(`${t} contains more than ${Kl} wildcard tokens`);return e}function rN(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=>Xl(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Yh(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 II(e){if(e===void 0)return{..._t,include:[..._t.include],exclude:[..._t.exclude]};let t=xa(e,"native.snapshot");return{include:rN(t.include,"native.snapshot.include",_t.include),exclude:rN(t.exclude,"native.snapshot.exclude",_t.exclude),max_files:Yh(t.max_files,_t.max_files,"native.snapshot.max_files"),max_total_bytes:Yh(t.max_total_bytes,_t.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Yh(t.max_duration_ms,_t.max_duration_ms,"native.snapshot.max_duration_ms")}}function jI(e){if(e===void 0)return;let t=xa(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=xa(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:Tn(r),toArtifactRoot:Tn(n),stage:a,...o?{cleanup:o}:{}}}function $I(e,t={}){let i=xa(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??Xh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=jI(i.pending_root_move);return{artifact_root:Tn(r),language:cN(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:II(i.snapshot),...s?{pending_root_move:s}:{}}}function OI(e){let t=xa(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:sN(t.artifact_layout),language:cN(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function HI(e){let i=xa(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)=>Yl(r,`hook.allow_paths[${n}]`)))]}}function DI(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function FI(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 Aa(e,t={}){let i=(0,ds.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=DI(n.ambient_resume),o=n.hook===void 0?void 0:HI(n.hook),s=n.native===void 0?void 0:$I(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:OI(n.classic),l=FI(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 lN(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function uN(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.pending_root_move?{pending_root_move:lN(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function Ca(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ps(e,t){let i=uN(t),r=Aa((0,ds.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...Ca(e.hook),allow_paths:[...r.hook.allow_paths]}),r.native){let a=Ca(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=Ca(a.pending_root_move),c=lN(r.native.pending_root_move),l=Ca(s.cleanup),u=Ca(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...Ca(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}function Ql(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Tn(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Xh,snapshot:{..._t,include:[..._t.include],exclude:[..._t.exclude]}}}}import{createHash as BI}from"crypto";import{promises as tu}from"fs";import Mr from"path";import{constants as Zl,promises as In}from"fs";var bi=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Qh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function dN(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ms(e){return{dev:e.dev,ino:e.ino,birthtime:Qh(e)}}function eu(e,t){let i=ms(e),r=ms(t);return Ye(i,r)?q(i,r):q(i,r)&&Qh(e)===Qh(t)&&dN(e)===dN(t)&&e.size===t.size}async function jn(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 In.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new bi("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new bi("too-large",`${r} exceeds ${t} bytes`);let o=await In.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:ms(a)});let s=process.platform==="win32"?Zl.O_RDONLY:Zl.O_RDONLY|Zl.O_NOFOLLOW|Zl.O_NONBLOCK,c;try{c=await In.open(e,s)}catch(l){throw l.code==="ELOOP"?new bi("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),In.lstat(e,{bigint:n}),In.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!eu(a,l)||!eu(a,u))throw new bi("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:ms(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:E}=await c.read(m,0,Math.min(m.length,y),null);if(E===0)break;if(h+=E,h>t)throw new bi("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([c.stat({bigint:n}),In.lstat(e,{bigint:n}),In.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!eu(a,p)||!eu(a,v))throw new bi("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:ms(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:g}}finally{await c.close()}}function MI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Zh(e,t){let i=Mr.relative(e,t);return i===""||!Mr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Mr.sep}`)}async function fN(e,t){let i=Mr.resolve(e),r=await tu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return tu.realpath(i)}async function hN(e,t,i,r){let n=e;for(let a=0;a{if(!Zh(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await hN(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var vs=".comet/config.yaml";function ep(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function LI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function iu(e,t={}){return(await gs(e,t)).document}async function pN(e){try{return(await Mi(e,vs,fs,{label:vs})).bytes}catch(t){if(LI(t))return null;throw t}}function mN(e){return e?{exists:!0,sha256:BI("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ru(e){return mN(await pN(e))}async function gs(e,t={}){let i=await pN(e);return{document:i?Aa(i.toString("utf8"),t):null,identity:mN(i)}}async function tp(e){return(await iu(e))?.config??null}import{randomUUID as qI}from"crypto";import{constants as VI,promises as gt}from"fs";import ki from"path";async function np(e,t){try{return await gt.link(e,t),{linked:!0}}catch(i){let r=i.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw i}return await gt.copyFile(e,t,VI.COPYFILE_EXCL),{linked:!1}}function rp(e,t){let i=ki.relative(e,t);return i===""||!ki.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ki.sep}`)}function nu(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function WI(e,t){return q(e,nu(t))}function ip(e,t){let i=nu(e),r=nu(t);return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function vN(e){let t=await gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await gt.realpath(e),...nu(t)}}async function ws(e){for(let t of e){let i=await gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!WI(t,i)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function zI(e,t){let i=ki.resolve(e),r=ki.resolve(t);if(!rp(i,r))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await vN(i)],a=ki.relative(i,r).split(ki.sep).filter(Boolean),o=i;for(let s of a){await ws(n),o=ki.join(o,s);try{await gt.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await vN(o);if(!rp(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ws(n),n}async function JI(e){let t;try{t=await gt.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 GI(e,t,i){let r=ki.dirname(e),n=await zI(i.containedRoot,r),a=ki.join(r,`.${ki.basename(e)}.${qI()}.tmp`),o,s;try{await i.beforeTemporaryOpen?.(),o=await gt.open(a,"wx"),s=await o.stat();let[c,l]=await Promise.all([gt.lstat(a),gt.realpath(a)]);if(await ws(n),!c.isFile()||c.isSymbolicLink()||!ip(s,c)||!rp(n[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!ip(s,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await i.beforeCommit?.(),await ws(n);let u=await gt.lstat(a);if(!u.isFile()||u.isSymbolicLink()||!ip(u,s))throw new Error("Contained atomic write temporary file changed before commit");i.exclusive?(await np(a,e),await gt.unlink(a)):await gt.rename(a,e),await JI(r)}catch(c){await o?.close();try{await ws(n),await gt.rm(a,{force:!0})}catch{}throw c}}async function $n(e,t,i){await GI(e,t,i)}var $W=16*1024;async function ap(e,t){if(!t)return;let i=await ru(e);if(!ep(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as gN,promises as Bi}from"fs";import ie from"path";import YI from"os";var ys=".comet/config.yaml",XI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function op(e){try{return await Bi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function QI(e){try{let t=await Bi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ta(e,t){let i=ie.relative(e,t);return i===""||!ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ie.sep}`)}async function _a(e){let t=[],i=e;for(;!await op(i);){let n=ie.dirname(i);if(n===i)break;t.push(ie.basename(i)),i=n}let r=await Bi.realpath(i);return ie.resolve(r,...t.reverse())}async function sp(e){try{return(await Bi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function au(e){let t=ie.resolve(e);try{(await Bi.stat(t)).isDirectory()||(t=ie.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=ie.resolve(YI.homedir());for(;;){if(!(t===r&&i!==r)){let o=ie.join(t,...ys.split("/")),s=t===i||await QI(o);if(await op(o)&&s)return t}if(await op(ie.join(t,".git")))return t;let a=ie.dirname(t);if(a===t)return i;t=a}}function Br(e){return Tn(e)}async function ZI(e,t){let i=Br(t),r=ie.resolve(e,...i.split("/")),n=await Bi.realpath(e),a=await _a(r);if(!Ta(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function re(e,t){let i=Br(t),r=await ZI(e,i),n=ie.join(r,"comet");if(await sp(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_a(r),_a(n)]);if(!Ta(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=ie.resolve(e),c=ie.join(s,".comet","runtime","native");if(await sp(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Bi.realpath(s),_a(c)]);if(!Ta(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:ie.join(e,...ys.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:ie.join(n,"specs"),changesDir:ie.join(n,"changes"),archiveDir:ie.join(n,"archive"),runtimeDir:c,changesRuntimeDir:ie.join(c,"changes"),locksDir:ie.join(c,"locks"),transactionsDir:ie.join(c,"transactions")}}async function ou(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await T(e.nativeRoot,t),await Bi.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await T(e.projectRoot,t),await Bi.mkdir(t,{recursive:!0})}))}function yN(e){if(!XI.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ze(e,t){yN(t);let i=ie.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function On(e,t){yN(t);let i=ie.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function M(e,t){let i=ze(e,t);if(gN(i))return i;let r=On(e,t);return gN(r)?r:i}async function wN(e){try{let t=await Bi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ns(e,t){let i=ze(e,t),r=On(e,t),[n,a]=await Promise.all([wN(i),wN(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Lr(e,t){if(!t.startsWith("runtime/")||ie.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=ie.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=ie.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return Ta(ie.resolve(e),ie.resolve(t))}async function T(e,t){let i=ie.resolve(e),r=ie.resolve(t);if(!Ta(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await sp(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_a(i),_a(r)]);if(!Ta(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var cp=_t;var su=Xl,NN=aN;function Hn(e="docs",t="en"){return Ql(e,t)}async function Y(e){let t=(await iu(e))?.config??null;return t?.native?t:null}async function Ia(e){let t=await Y(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 Vt(e,t,i={}){let r=await gs(e,{allowPartialProject:!0}),n=ps(r.document?.value??{},t),a=ej.join(e,...ys.split("/"));await Ne(a,hs(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ap(e,r.identity)}})}async function bN(e){let t=await au(e.startPath),i=await Y(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${ys} 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?Br(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??Hn(r??"docs"),a=await re(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as X$}from"fs";import Q$ from"path";import{AsyncLocalStorage as tj}from"async_hooks";import{randomUUID as EN}from"crypto";import{promises as ii}from"fs";import PN from"os";import Ce from"path";var kN=16*1024,lp=".coordinator",ij=5e3,SN=new tj,cu=new Map;function rj(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function nj(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 RN(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 up(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ye(i,r)?q(i,r):q(i,r)&&e.size===t.size}function lu(e,t){return up(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function aj(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&lu(e.identity,t.identity)}async function Li(e){let t,i;try{let r=await jn(e,kN,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof bi?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${kN} 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:nj(JSON.parse(t.toString("utf8")),e),identity:RN(i)}}async function oj(e){return(await Li(e))?.owner??null}function dp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==PN.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=fj(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function sj(e,t){try{await ii.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ii.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function uu(e,t){let i=await Li(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lu(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ii.mkdir(t,{recursive:!0});let r=Ce.join(t,`${Ce.basename(e.file)}.${e.owner.id}.${EN()}.removed`);try{await ii.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Li(r);if(!n||n.owner.id!==e.owner.id||!up(n.identity,e.identity))throw await sj(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ii.rm(r,{force:!0}),"removed"}function CN(e){return{id:EN(),pid:process.pid,hostname:PN.hostname(),createdAt:new Date().toISOString(),operation:e}}async function xN(e,t){let i;try{i=await ii.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await oj(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)+` +`,"utf8"),await i.sync(),RN(await i.stat({bigint:!0}))}finally{await i.close()}}async function cj(e,t){let i=await T(e.runtimeDir,e.locksDir);await ii.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,Ce.join(i,lp));await ii.mkdir(r,{recursive:!0});let n=CN(t),a=Ce.join(r,`.${n.id}.tmp`),o=Ce.join(r,`${n.id}.claim`);try{let s=await xN(a,n);await ii.rename(a,o);let c=await Li(o);if(!c||!up(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 ii.rm(a,{force:!0})}}async function lj(e){let t=Ce.dirname(e.file),i=!1,r=Ce.basename(e.file);for(let n of await ii.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Ce.join(t,n.name);if(Ce.resolve(a)!==Ce.resolve(e.file))try{let o=await Li(a),s=dp(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await uu(o,t);continue}n.name=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 dj(e){let t=cu.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return cu.set(e,n),await t,()=>{i(),cu.get(e)===n&&cu.delete(e)}}async function du(e,t,i){let r=Ce.resolve(e.locksDir),n=SN.getStore();if(n?.has(r))return i();let a=await dj(r);try{let o=await uj(e,t),s=new Map(n??[]);return s.set(r,o),await SN.run(s,async()=>{try{return await i()}finally{await AN(o)}})}finally{a()}}async function Dn(e,t,i){let r=[...new Map(e.map(a=>[Ce.resolve(a.locksDir),a])).values()].sort((a,o)=>Ce.resolve(a.locksDir).localeCompare(Ce.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?du(o,t,()=>n(a+1)):i()};return n(0)}async function cr(e,t,i){return du(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await ii.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,Ce.join(r,rj(t))),a=CN(i),o=await xN(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function lr(e){await Li(e.file)&&await du({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Ce.basename(e.file)}`,async()=>{let t=await Li(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lu(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=Ce.join(e.locksDir,lp);await uu(t,i)})}function fj(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function bs(e){return dp(await Li(e))}async function fp(e,t,i){return du(e,`take over ${Ce.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(Ce.resolve(Ce.dirname(n))!==Ce.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await Li(n),o=dp(a);if(o.status==="missing")return{status:"missing"};if(i&&!aj(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=Ce.join(r,lp);return await uu(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as w$}from"node:fs";import kp from"node:path";import r$ from"node:path";import MN from"node:path";import _N from"node:path";import{createHash as hj}from"crypto";function Si(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function pj(e,t){t.has(e)&&Si("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;rr!==String(n)))&&Si("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Si("symbol properties are not supported"),`[${e.map(r=>hp(r,t)).join(",")}]`}finally{t.delete(e)}}function mj(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Si("only plain objects are supported"),t.has(e)&&Si("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Si("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))&&Si("accessor properties are not supported"),`${JSON.stringify(o)}:${hp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function hp(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)||Si("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?pj(e,t):mj(e,t);case"bigint":case"function":case"symbol":case"undefined":return Si(`${typeof e} values are not supported`)}return Si("unsupported value type")}function ks(e){return hp(e,new Set)}function D(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 hj("sha256").update(`${e} +${ks(t)}`).digest("hex")}var vj="comet.native.acceptance.v1",gj=/^acceptance-[a-f0-9]{64}$/u,wj=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),yj=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,Nj=/^[a-f0-9]{64}$/u,bj=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function kj(e,t){return et?1:0}var ur=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Es=Object.freeze({maxCriteria:1024}),TN="",IN="";function jN(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:i,truncated:!0}}function $N(e,t){let i=t.toString(36),r=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function Sj(e){if(!Nj.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=bj.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function Ej(e,t){let i=jN(e.text,ur.maxTextBytes),r=e.context.slice(0,ur.maxContextItems).map(n=>jN(n,ur.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function HN(e){let t=Sj({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(kj),n=r.slice(0,ur.maxFailedCheckIds),a=e.criteria.slice(t,t+ur.maxItems);for(let c of a){let l=[...i,Ej(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:uur.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:our.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function mp(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 pp(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 ON(e){return e.includes("-->")||e.includes("--!>")}function*ja(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,` `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(` -`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=pp(l,t);else if(i)$N(l)&&(i=!1);else if(r!==null)new RegExp(``,"iu").test(l)&&(r=null);else{let d=pp(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith(""||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(p=>p.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(p=>p.text)},c();continue}s===null?s={parts:[h],context:a.map(p=>p.text)}:s.parts.push(h)}return c(),gp(n,"Specification mandatory requirements",r)}function Cj(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||Pj(i)||AN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=AN.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!wj.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function xj(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!gj.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function HN(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=xj(i,r),a=n.acceptance_id;if(typeof a!="string"||!vj.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return Cj(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function DN(e){let t=Ej(e);if(t.some(({line:l,body:u})=>!u&&(l===_N||l===TN)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===_N?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===TN?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(` -`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=HN(o),c=Aj(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function Aj(e){let t=HN([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var _j=/^A[1-9]\d*$/u;function MN(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||FN.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||FN.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Tj(e,t){return e.localeCompare(t,"en")}function mu(e){let t=MN(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Tj(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=fu(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=MN(a.source,`Native spec source for ${a.capability}`);r.push(...hu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...pu(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=Ss(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 BN(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}var yu=ma(_n(),1);import{promises as Ij}from"node:fs";var Fn="comet.native.v4",Ps="comet.native.local-execution.v4";function vu(){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 jj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$j=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oj=/^A[1-9][0-9]*$/u,Hj=/^[a-f0-9]{64}$/u,Dj=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"]),wu=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 Tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function It(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ze(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 yp(e,t){return e===null?null:Ze(e,t)}function Fj(e,t){let i=Ze(e,t);if(!Hj.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function $a(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function xe(e,t,i=0){if(!Number.isSafeInteger(e)||ei(r,n))}function Nu(e,t){return qi(e,t,(i,r)=>Ze(i,`${t}[${r}]`))}function Mn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Oa(e,t){let i=Ze(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Np(e,t,i=!1){let r=Ze(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 Ei(e,t){let i=Tt(e,t);return It(i,new Set(["text","truncated"]),t),{text:Ze(i.text,`${t}.text`,{empty:!0}),truncated:$a(i.truncated,`${t}.truncated`)}}function Bj(e,t){let i=`Native spec_changes[${t}]`,r=Tt(e,i);It(r,new Set(["capability","operation","source"]),i);let n=Ze(r.capability,`${i}.capability`);if(!$j.test(n))throw new Error(`${i}.capability is invalid`);let a=Qe(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Np(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 Lj(e){let t="Native workspace",i=Tt(e,t);It(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Qe(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=yp(i.change_branch,`${t}.change_branch`),a=yp(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Qe(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 qj(e){let t="Native loop",i=Tt(e,t);It(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=Nu(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Mn(r,`${t}.previous_unresolved_ids`),{stage:Qe(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:xe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:xe(i.iteration,`${t}.iteration`),attempt:xe(i.attempt,`${t}.attempt`),retry_epoch:xe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:xe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:xe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:xe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:yp(i.next_action,`${t}.next_action`)}}function Vj(e,t){let i=`Native acceptance[${t}]`,r=Tt(e,i);It(r,new Set(["id","source","text","result","reason"]),i);let n=Ze(r.id,`${i}.id`);if(!Oj.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Np(r.source,`${i}.source`),text:Ze(r.text,`${i}.text`),result:Qe(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ei(r.reason,`${i}.reason`)}}function Wj(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Tt(e,i);return It(r,new Set(["name","result","note"]),i),{name:Ei(r.name,`${i}.name`),result:Qe(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ei(r.note,`${i}.note`)}}function zj(e){let t="Native builder_handoff",i=Tt(e,t);It(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=Nu(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Mn(r,`${t}.addressed_acceptance_ids`),{candidate_id:Ze(i.candidate_id,`${t}.candidate_id`),identity_provider:Ze(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Ze(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:xe(i.iteration,`${t}.iteration`,1),summary:Ei(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:qi(i.checks,`${t}.checks`,Wj),checks_truncated:$a(i.checks_truncated,`${t}.checks_truncated`),known_limits:qi(i.known_limits,`${t}.known_limits`,(n,a)=>Ei(n,`${t}.known_limits[${a}]`)),known_limits_truncated:$a(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Oa(i.submitted_at,`${t}.submitted_at`)}}function Jj(e,t){let i=`Native blockers[${t}]`,r=Tt(e,i);It(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Nu(r.acceptance_ids,`${i}.acceptance_ids`);return Mn(n,`${i}.acceptance_ids`),{owner:Qe(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ei(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Qe(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Gj(e,t){let i=`Native verification.checks[${t}]`,r=Tt(e,i);return It(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Ze(r.id,`${i}.id`),name:Ei(r.name,`${i}.name`),argv_display:qi(r.argv_display,`${i}.argv_display`,(n,a)=>Ei(n,`${i}.argv_display[${a}]`)),argv_truncated:$a(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Np(r.cwd_ref,`${i}.cwd_ref`,!0),status:Qe(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Mj(r.exit_code,`${i}.exit_code`),duration_ms:xe(r.duration_ms,`${i}.duration_ms`)}}function Uj(e){let t="Native verification",i=Tt(e,t);It(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=qi(i.checks,`${t}.checks`,Gj);Mn(r.map(a=>a.id),`${t}.checks IDs`);let n=Ze(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Ze(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Ze(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:xe(i.iteration,`${t}.iteration`,1),attempt:xe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Qe(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Qe(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ei(i.summary,`${t}.summary`),risks:qi(i.risks,`${t}.risks`,(a,o)=>Ei(a,`${t}.risks[${o}]`)),risks_truncated:$a(i.risks_truncated,`${t}.risks_truncated`),completed_at:Oa(i.completed_at,`${t}.completed_at`)}}function qN(e,t){let i=`Native history[${t}]`,r=Tt(e,i);It(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Nu(r.unresolved_ids,`${i}.unresolved_ids`);return Mn(n,`${i}.unresolved_ids`),{goal_cycle:xe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:xe(r.iteration,`${i}.iteration`),attempt:xe(r.attempt,`${i}.attempt`),outcome:Qe(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ei(r.summary,`${i}.summary`),completed_at:Oa(r.completed_at,`${i}.completed_at`)}}function Kj(e){let t="Native history_overflow.outcome_counts",i=Tt(e,t),r=["pass","fail","blocked","execution-error","recovery"];return It(i,new Set(r),t),{pass:xe(i.pass,`${t}.pass`),fail:xe(i.fail,`${t}.fail`),blocked:xe(i.blocked,`${t}.blocked`),"execution-error":xe(i["execution-error"],`${t}.execution-error`),recovery:xe(i.recovery,`${t}.recovery`)}}function Yj(e){let t="Native history_overflow",i=Tt(e,t);It(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=xe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Oa(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Oa(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=Kj(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 Xj(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 Qj(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 X(e){let t=Tt(e,"Native portable state");if(It(t,Dj,"Native portable state"),t.schema!==Fn)throw new Error(`Native portable state schema must be ${Fn}`);let i=Ze(t.name,"Native state name");if(!jj.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=qi(t.spec_changes,"Native spec_changes",Bj);Mn(r.map(s=>s.capability),"Native spec change capabilities");let n=qi(t.acceptance,"Native acceptance",Vj);Mn(n.map(s=>s.id),"Native acceptance IDs");let a=qi(t.history,"Native history",qN);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Fn,name:i,language:Qe(t.language,["en","zh-CN"],"Native state language"),phase:Qe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Qe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:xe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Fj(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Lj(t.workspace),loop:qj(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:zj(t.builder_handoff),blockers:qi(t.blockers,"Native blockers",Jj),verification:t.verification===null?null:Uj(t.verification),history:a,history_overflow:Yj(t.history_overflow),verification_result:Qe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Qe(t.verification_report,["verification.md"],"Native verification_report"),archived:$a(t.archived,"Native archived"),created_at:Oa(t.created_at,"Native created_at")};return Xj(o),Qj(o),o}function VN(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return X({schema:Fn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",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:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:vu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ri(e,t){let i=X(e),r=qN(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 X({...i,history:n,history_overflow:a})}function Zj(e,t){let i=(0,yu.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 wt(e){let t=await Ij.readFile(e,"utf8");return X(Zj(t,"Native portable state"))}async function Rs(e,t,i={}){let r=X(t);await Ne(e,(0,yu.stringify)(r),i)}var gu=new Map;async function e$(e,t){let i=gu.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);gu.set(e,a),await i;try{return await t()}finally{r(),gu.get(e)===a&&gu.delete(e)}}async function Bn(e){return e$(e.file,async()=>{let t=xe(e.expectedStateVersion,"Native expected state version",1),i=X(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await wt(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new wu(t,r.state_version);return await Rs(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await wt(e.file);if(n.state_version!==t)throw new wu(t,n.state_version)}}),i})}function t$(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ue(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(t$(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 $e="comet.native.v3",Oe="comet.native.v2",yt="comet.native.v1",qr="comet.native.transition.v3",dr="comet.native.transition.v2",Ln="comet.native.transition.v1";var bu="comet.native.portable-migration.v1",r$=new Set(["schema","id","change","fromSchema","status","createdAt"]),n$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,a$=/^[a-z0-9][a-z0-9-]{7,127}$/u,o$=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),s$=new Set([yt,Oe,$e]);function c$(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function l$(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 u$(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 d$(e){return e.schema===yt?qn(e):e.schema===Oe?Vi(e):jt(e)}function f$(e){return i$.posix.normalize(e.replaceAll("\\","/"))}function h$(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:f$(t.source)})}function p$(e){return e==="shape"?"shape":"build"}function m$(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function v$(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 WN(e){let t=d$(e.state);BN(e.acceptance);let i=p$(t.phase),r=i==="shape"?0:1,n=l$(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 X({schema:Fn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:h$(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:m$(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:ue(v$(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:vu(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function bp(e){let t=c$(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!r$.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==bu)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!a$.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!n$.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!s$.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!o$.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:bu,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:u$(t.createdAt,"Native portable migration transaction createdAt")}}function zN(e){switch(bp(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 ku="comet.native.archive-transaction.v4",JN="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",w$=new RegExp(`^portable-archive-(${JN})\\.json$`,"u"),y$=new RegExp(`^portable-migration-(${JN})\\.json$`,"u"),N$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,b$=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,k$=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),S$=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),E$=new Set(["capability","operation","source","content"]),GN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;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(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function P$(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=UN(e,i);if(KN(r,E$,i),typeof r.capability!="string"||!GN.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 R$(e){let t=UN(e,"Native portable Archive transaction");if(KN(t,S$,"Native portable Archive transaction"),t.schema!==ku)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!N$.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!GN.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"||!b$.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"||!k$.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(P$);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:ku,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=w$.exec(e);if(t)return{kind:"archive",change:t[1]};let i=y$.exec(e);return i?{kind:"migration",change:i[1]}:null}function Vr(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 kp.join(e.transactionsDir,i)}async function Cs(e,t){let i=Vn(t);if(!i)return null;let r=await ee({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=kp.join(e.transactionsDir,t);if(i.kind==="archive"){let s=R$(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=bp(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 Ha(e,t){let i=Vr(e,t);try{return await Cs(e,kp.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function YN(e){let t;try{t=await g$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Vn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function XN(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as xs}from"fs";import ni from"path";import{TextDecoder as T$}from"util";import{createHash as C$}from"node:crypto";import{constants as Su,promises as U}from"node:fs";import ne from"node:path";import{TextDecoder as x$}from"node:util";function st(e,t){let i=ne.relative(e,t);return i===""||!ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ne.sep}`)}function QN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Fa(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ZN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Da(e,t){return q({...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 Wr(e,t){let i=await U.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await U.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function zr(e,t,i){let r=ne.resolve(e),n=ne.resolve(t);if(!st(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Wr(r,i)],o=r;for(let s of ne.relative(r,n).split(ne.sep).filter(Boolean)){await Ie(a,i),o=ne.join(o,s);let c=await Wr(o,i);if(!st(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ie(a,i),a}async function Ie(e,t){for(let i of e){let r=await U.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Fa(i,r)||await U.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function A$(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 ge(e){let t=QN(e.maxBytes),i=ne.resolve(e.file),r=await zr(e.root,ne.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Wr(ne.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ie(r,e.label);let a=await U.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=ZN(a),s=await U.realpath(i);if(!st(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>st(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Su.O_RDONLY:Su.O_RDONLY|Su.O_NOFOLLOW|Su.O_NONBLOCK,l=await U.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([U.lstat(i),U.realpath(i)]);if(await Ie(r,e.label),await Ie(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Da(o,u)||!Da(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await A$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),U.lstat(i),U.realpath(i)]);if(await Ie(r,e.label),await Ie(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Da(o,m)||!Da(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:C$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Eu(e){let t=await ge(e),i;try{i=new x$("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function $t(e){let t=await zr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await U.readdir(e.directory,{withFileTypes:!0});else{let r=QN(e.maxEntries);i=[];let n=await U.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Ie(t,e.label),{entries:i,verify:()=>Ie(t,e.label)}}async function Wt(e){let t=await zr(e.root,e.directory,e.label);return{verify:()=>Ie(t,e.label)}}async function _$(e){let t=ne.resolve(e.directory),i=ne.resolve(e.quarantine);if(ne.dirname(i)!==ne.dirname(t)||!st(ne.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await zr(e.root,ne.dirname(t),e.label),n=await Wr(t,e.label);if(!st(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await Ie(r,e.label);let a=await U.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Fa(n,a)||await U.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await U.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await U.rename(t,i),await Ie(r,e.label);let o=await U.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Fa(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await U.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function eb(e){await _$(e)}async function Pu(e){let t=ne.resolve(e.file),i=await zr(e.root,ne.dirname(t),e.label),r=await U.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=ZN(r),a=await U.realpath(t);if(!st(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ge({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([U.lstat(t),U.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Da(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await Ie(i,e.label);let[l,u]=await Promise.all([U.lstat(t),U.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Da(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await U.rm(t),await Ie(i,e.label)}async function Sp(e){let t=ne.resolve(e.directory),i=await zr(e.root,ne.dirname(t),e.label),r=await Wr(t,e.label);if(!st(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await Ie(i,e.label);let n=await U.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Fa(r,n)||await U.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await U.rmdir(t),await Ie(i,e.label)}async function Wi(e){let t=ne.resolve(e.root),i=ne.resolve(e.directory);if(!st(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await Wr(t,e.label)],n=t;for(let a of ne.relative(t,i).split(ne.sep).filter(Boolean)){await Ie(r,e.label),n=ne.join(n,a);try{await U.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Wr(n,e.label);if(!st(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await Ie(r,e.label)}async function Ep(e){let t=ne.resolve(e.root),i=ne.resolve(e.source),r=ne.resolve(e.target);if(i===r||!st(t,i)||!st(t,r)||st(i,r)||st(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Wi({root:t,directory:ne.dirname(r),label:`${e.label} target parent`});let n=await zr(t,ne.dirname(i),e.label),a=await zr(t,ne.dirname(r),e.label),o=await Wr(i,e.label);if(!st(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await U.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Ie(n,e.label),Ie(a,e.label)]);let s=await U.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Fa(o,s)||await U.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await U.rename(i,r),await Promise.all([Ie(n,e.label),Ie(a,e.label)]);let c=await U.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Fa(o,c)||!st(n[0].realPath,await U.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await U.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Jr(e){let t=await ge({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await dg(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await U.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ge({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ge({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var I$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),j$=new Set(["id","type","source","target","staged","backup"]),$$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),O$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),H$=new Set(["sequence","timestamp","type","operationId"]),nb=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),ab=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),D$=256*1024,F$=1024*1024,ob=16*1024,Cu=1024,Cp=64*1024*1024,M$=2e4,sb=new T$("utf-8",{fatal:!0});function As(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _s(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 Ba(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Pp(e,t){if(typeof e!="string"||e.length===0||ni.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ru(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function tb(e,t){if(Pp(e,t),e.includes("\\")||e!==ni.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 B$(e,t){let i=As(e,`transaction operations[${t}]`);if(_s(i,j$,`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`);Pp(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Pp(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 Au(e){let t=As(e,"Native Archive transaction journal");if(_s(t,$$,"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"||!nb.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(!Ba(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ru(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=As(s,`Archive transaction operations[${c}]`);if(_s(l,O$,`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`);tb(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&tb(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ru(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(Ru(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`);Ru(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 xp(e){let t=As(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Au(t);if(_s(t,I$,"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"||!nb.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ni.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ni.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(!Ba(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(B$),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 cb(e,t){let i=As(e,`Native transaction event at line ${t}`);if(_s(i,H$,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Ba(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!ab.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function L$(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;rString(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Ba(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Ba(e)}function Ma(e,t){return e.lengthob)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Ma(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!L$(n))return!1;if(r.length<24)return!0;if(!Ba(n))return!1;let a='","type":"',o=r.slice(24);if(Ma(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of ab){if(Ma(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(q$(l))return!0}else if(Ma(l,'"}'))return!0}return!1}function W$(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>ob)throw new Error(`Native transaction event at line ${t} is too large`);return cb(JSON.parse(e),t)}function z$(e){let t=e.split(` -`),i=t.at(-1)==="";if(i&&t.pop(),t.length>Cu)throw new Error(`Native transaction event log exceeds ${Cu} events`);let r=[];for(let n=0;nJSON.stringify(t)).join(` +`),o.context,r)),o=null}};for(let{line:c,body:l}of ja(e)){let u=l?mp(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Ss(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.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(),gp(n,"Specification",r)}function pu(e,t="spec.md",i=Es.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(vp("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:d}of ja(e)){let f=d?mp(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||pp(u,null)!==null||h.startsWith(""||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(p=>p.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(p=>p.text)},c();continue}s===null?s={parts:[h],context:a.map(p=>p.text)}:s.parts.push(h)}return c(),gp(n,"Specification mandatory requirements",r)}function xj(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||Rj(i)||_N.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=_N.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!yj.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function Aj(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!wj.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function DN(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=Aj(i,r),a=n.acceptance_id;if(typeof a!="string"||!gj.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return xj(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function FN(e){let t=Pj(e);if(t.some(({line:l,body:u})=>!u&&(l===TN||l===IN)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===TN?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===IN?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(` +`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=DN(o),c=_j(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function _j(e){let t=DN([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var Tj=/^A[1-9]\d*$/u;function BN(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||MN.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||MN.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Ij(e,t){return e.localeCompare(t,"en")}function mu(e){let t=BN(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Ij(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=fu(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=BN(a.source,`Native spec source for ${a.capability}`);r.push(...hu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...pu(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=Ss(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 LN(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;ii.source===t[r]?.source&&i.text===t[r]?.text)}var yu=ma(_n(),1);import{promises as jj}from"node:fs";var Fn="comet.native.v4",Ps="comet.native.local-execution.v4";function vu(){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 $j=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hj=/^A[1-9][0-9]*$/u,Dj=/^[a-f0-9]{64}$/u,Fj=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"]),wu=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 Tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function It(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ze(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 yp(e,t){return e===null?null:Ze(e,t)}function Mj(e,t){let i=Ze(e,t);if(!Dj.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function $a(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function xe(e,t,i=0){if(!Number.isSafeInteger(e)||ei(r,n))}function Nu(e,t){return qi(e,t,(i,r)=>Ze(i,`${t}[${r}]`))}function Mn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Oa(e,t){let i=Ze(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Np(e,t,i=!1){let r=Ze(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 Ei(e,t){let i=Tt(e,t);return It(i,new Set(["text","truncated"]),t),{text:Ze(i.text,`${t}.text`,{empty:!0}),truncated:$a(i.truncated,`${t}.truncated`)}}function Lj(e,t){let i=`Native spec_changes[${t}]`,r=Tt(e,i);It(r,new Set(["capability","operation","source"]),i);let n=Ze(r.capability,`${i}.capability`);if(!Oj.test(n))throw new Error(`${i}.capability is invalid`);let a=Qe(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Np(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 qj(e){let t="Native workspace",i=Tt(e,t);It(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Qe(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=yp(i.change_branch,`${t}.change_branch`),a=yp(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Qe(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 Vj(e){let t="Native loop",i=Tt(e,t);It(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=Nu(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Mn(r,`${t}.previous_unresolved_ids`),{stage:Qe(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:xe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:xe(i.iteration,`${t}.iteration`),attempt:xe(i.attempt,`${t}.attempt`),retry_epoch:xe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:xe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:xe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:xe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:yp(i.next_action,`${t}.next_action`)}}function Wj(e,t){let i=`Native acceptance[${t}]`,r=Tt(e,i);It(r,new Set(["id","source","text","result","reason"]),i);let n=Ze(r.id,`${i}.id`);if(!Hj.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Np(r.source,`${i}.source`),text:Ze(r.text,`${i}.text`),result:Qe(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ei(r.reason,`${i}.reason`)}}function zj(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Tt(e,i);return It(r,new Set(["name","result","note"]),i),{name:Ei(r.name,`${i}.name`),result:Qe(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ei(r.note,`${i}.note`)}}function Jj(e){let t="Native builder_handoff",i=Tt(e,t);It(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=Nu(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Mn(r,`${t}.addressed_acceptance_ids`),{candidate_id:Ze(i.candidate_id,`${t}.candidate_id`),identity_provider:Ze(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Ze(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:xe(i.iteration,`${t}.iteration`,1),summary:Ei(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:qi(i.checks,`${t}.checks`,zj),checks_truncated:$a(i.checks_truncated,`${t}.checks_truncated`),known_limits:qi(i.known_limits,`${t}.known_limits`,(n,a)=>Ei(n,`${t}.known_limits[${a}]`)),known_limits_truncated:$a(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Oa(i.submitted_at,`${t}.submitted_at`)}}function Gj(e,t){let i=`Native blockers[${t}]`,r=Tt(e,i);It(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Nu(r.acceptance_ids,`${i}.acceptance_ids`);return Mn(n,`${i}.acceptance_ids`),{owner:Qe(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ei(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Qe(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Uj(e,t){let i=`Native verification.checks[${t}]`,r=Tt(e,i);return It(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Ze(r.id,`${i}.id`),name:Ei(r.name,`${i}.name`),argv_display:qi(r.argv_display,`${i}.argv_display`,(n,a)=>Ei(n,`${i}.argv_display[${a}]`)),argv_truncated:$a(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Np(r.cwd_ref,`${i}.cwd_ref`,!0),status:Qe(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Bj(r.exit_code,`${i}.exit_code`),duration_ms:xe(r.duration_ms,`${i}.duration_ms`)}}function Kj(e){let t="Native verification",i=Tt(e,t);It(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=qi(i.checks,`${t}.checks`,Uj);Mn(r.map(a=>a.id),`${t}.checks IDs`);let n=Ze(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Ze(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Ze(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:xe(i.iteration,`${t}.iteration`,1),attempt:xe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Qe(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Qe(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ei(i.summary,`${t}.summary`),risks:qi(i.risks,`${t}.risks`,(a,o)=>Ei(a,`${t}.risks[${o}]`)),risks_truncated:$a(i.risks_truncated,`${t}.risks_truncated`),completed_at:Oa(i.completed_at,`${t}.completed_at`)}}function VN(e,t){let i=`Native history[${t}]`,r=Tt(e,i);It(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Nu(r.unresolved_ids,`${i}.unresolved_ids`);return Mn(n,`${i}.unresolved_ids`),{goal_cycle:xe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:xe(r.iteration,`${i}.iteration`),attempt:xe(r.attempt,`${i}.attempt`),outcome:Qe(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ei(r.summary,`${i}.summary`),completed_at:Oa(r.completed_at,`${i}.completed_at`)}}function Yj(e){let t="Native history_overflow.outcome_counts",i=Tt(e,t),r=["pass","fail","blocked","execution-error","recovery"];return It(i,new Set(r),t),{pass:xe(i.pass,`${t}.pass`),fail:xe(i.fail,`${t}.fail`),blocked:xe(i.blocked,`${t}.blocked`),"execution-error":xe(i["execution-error"],`${t}.execution-error`),recovery:xe(i.recovery,`${t}.recovery`)}}function Xj(e){let t="Native history_overflow",i=Tt(e,t);It(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=xe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Oa(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Oa(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=Yj(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 Qj(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 Zj(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 X(e){let t=Tt(e,"Native portable state");if(It(t,Fj,"Native portable state"),t.schema!==Fn)throw new Error(`Native portable state schema must be ${Fn}`);let i=Ze(t.name,"Native state name");if(!$j.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=qi(t.spec_changes,"Native spec_changes",Lj);Mn(r.map(s=>s.capability),"Native spec change capabilities");let n=qi(t.acceptance,"Native acceptance",Wj);Mn(n.map(s=>s.id),"Native acceptance IDs");let a=qi(t.history,"Native history",VN);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Fn,name:i,language:Qe(t.language,["en","zh-CN"],"Native state language"),phase:Qe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Qe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:xe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Mj(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:qj(t.workspace),loop:Vj(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Jj(t.builder_handoff),blockers:qi(t.blockers,"Native blockers",Gj),verification:t.verification===null?null:Kj(t.verification),history:a,history_overflow:Xj(t.history_overflow),verification_result:Qe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Qe(t.verification_report,["verification.md"],"Native verification_report"),archived:$a(t.archived,"Native archived"),created_at:Oa(t.created_at,"Native created_at")};return Qj(o),Zj(o),o}function WN(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return X({schema:Fn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",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:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:vu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ri(e,t){let i=X(e),r=VN(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 X({...i,history:n,history_overflow:a})}function e$(e,t){let i=(0,yu.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 wt(e){let t=await jj.readFile(e,"utf8");return X(e$(t,"Native portable state"))}async function Rs(e,t,i={}){let r=X(t);await Ne(e,(0,yu.stringify)(r),i)}var gu=new Map;async function t$(e,t){let i=gu.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);gu.set(e,a),await i;try{return await t()}finally{r(),gu.get(e)===a&&gu.delete(e)}}async function Bn(e){return t$(e.file,async()=>{let t=xe(e.expectedStateVersion,"Native expected state version",1),i=X(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await wt(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new wu(t,r.state_version);return await Rs(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await wt(e.file);if(n.state_version!==t)throw new wu(t,n.state_version)}}),i})}function i$(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function de(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(i$(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 $e="comet.native.v3",Oe="comet.native.v2",yt="comet.native.v1",qr="comet.native.transition.v3",dr="comet.native.transition.v2",Ln="comet.native.transition.v1";var bu="comet.native.portable-migration.v1",n$=new Set(["schema","id","change","fromSchema","status","createdAt"]),a$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,o$=/^[a-z0-9][a-z0-9-]{7,127}$/u,s$=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),c$=new Set([yt,Oe,$e]);function l$(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function u$(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 d$(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 f$(e){return e.schema===yt?qn(e):e.schema===Oe?Vi(e):jt(e)}function h$(e){return r$.posix.normalize(e.replaceAll("\\","/"))}function p$(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:h$(t.source)})}function m$(e){return e==="shape"?"shape":"build"}function v$(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function g$(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 zN(e){let t=f$(e.state);LN(e.acceptance);let i=m$(t.phase),r=i==="shape"?0:1,n=u$(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 X({schema:Fn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:p$(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:v$(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:de(g$(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:vu(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function bp(e){let t=l$(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!n$.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==bu)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!o$.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!a$.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!c$.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!s$.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:bu,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:d$(t.createdAt,"Native portable migration transaction createdAt")}}function JN(e){switch(bp(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 ku="comet.native.archive-transaction.v4",GN="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",y$=new RegExp(`^portable-archive-(${GN})\\.json$`,"u"),N$=new RegExp(`^portable-migration-(${GN})\\.json$`,"u"),b$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,k$=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,S$=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),E$=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),P$=new Set(["capability","operation","source","content"]),UN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;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(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function R$(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=KN(e,i);if(YN(r,P$,i),typeof r.capability!="string"||!UN.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 C$(e){let t=KN(e,"Native portable Archive transaction");if(YN(t,E$,"Native portable Archive transaction"),t.schema!==ku)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!b$.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!UN.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"||!k$.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"||!S$.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(R$);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:ku,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=y$.exec(e);if(t)return{kind:"archive",change:t[1]};let i=N$.exec(e);return i?{kind:"migration",change:i[1]}:null}function Vr(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 kp.join(e.transactionsDir,i)}async function Cs(e,t){let i=Vn(t);if(!i)return null;let r=await ee({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=kp.join(e.transactionsDir,t);if(i.kind==="archive"){let s=C$(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=bp(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 Ha(e,t){let i=Vr(e,t);try{return await Cs(e,kp.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function XN(e){let t;try{t=await w$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Vn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function QN(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as xs}from"fs";import ni from"path";import{TextDecoder as I$}from"util";import{createHash as x$}from"node:crypto";import{constants as Su,promises as U}from"node:fs";import ne from"node:path";import{TextDecoder as A$}from"node:util";function st(e,t){let i=ne.relative(e,t);return i===""||!ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ne.sep}`)}function ZN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Fa(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function eb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Da(e,t){return q({...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 Wr(e,t){let i=await U.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await U.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function zr(e,t,i){let r=ne.resolve(e),n=ne.resolve(t);if(!st(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Wr(r,i)],o=r;for(let s of ne.relative(r,n).split(ne.sep).filter(Boolean)){await Ie(a,i),o=ne.join(o,s);let c=await Wr(o,i);if(!st(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ie(a,i),a}async function Ie(e,t){for(let i of e){let r=await U.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Fa(i,r)||await U.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function _$(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 ge(e){let t=ZN(e.maxBytes),i=ne.resolve(e.file),r=await zr(e.root,ne.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Wr(ne.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ie(r,e.label);let a=await U.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=eb(a),s=await U.realpath(i);if(!st(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>st(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Su.O_RDONLY:Su.O_RDONLY|Su.O_NOFOLLOW|Su.O_NONBLOCK,l=await U.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([U.lstat(i),U.realpath(i)]);if(await Ie(r,e.label),await Ie(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Da(o,u)||!Da(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await _$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),U.lstat(i),U.realpath(i)]);if(await Ie(r,e.label),await Ie(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Da(o,m)||!Da(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:x$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Eu(e){let t=await ge(e),i;try{i=new A$("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function $t(e){let t=await zr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await U.readdir(e.directory,{withFileTypes:!0});else{let r=ZN(e.maxEntries);i=[];let n=await U.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Ie(t,e.label),{entries:i,verify:()=>Ie(t,e.label)}}async function Wt(e){let t=await zr(e.root,e.directory,e.label);return{verify:()=>Ie(t,e.label)}}async function T$(e){let t=ne.resolve(e.directory),i=ne.resolve(e.quarantine);if(ne.dirname(i)!==ne.dirname(t)||!st(ne.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await zr(e.root,ne.dirname(t),e.label),n=await Wr(t,e.label);if(!st(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await Ie(r,e.label);let a=await U.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Fa(n,a)||await U.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await U.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await U.rename(t,i),await Ie(r,e.label);let o=await U.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Fa(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await U.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function tb(e){await T$(e)}async function Pu(e){let t=ne.resolve(e.file),i=await zr(e.root,ne.dirname(t),e.label),r=await U.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=eb(r),a=await U.realpath(t);if(!st(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ge({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([U.lstat(t),U.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Da(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await Ie(i,e.label);let[l,u]=await Promise.all([U.lstat(t),U.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Da(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await U.rm(t),await Ie(i,e.label)}async function Sp(e){let t=ne.resolve(e.directory),i=await zr(e.root,ne.dirname(t),e.label),r=await Wr(t,e.label);if(!st(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await Ie(i,e.label);let n=await U.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Fa(r,n)||await U.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await U.rmdir(t),await Ie(i,e.label)}async function Wi(e){let t=ne.resolve(e.root),i=ne.resolve(e.directory);if(!st(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await Wr(t,e.label)],n=t;for(let a of ne.relative(t,i).split(ne.sep).filter(Boolean)){await Ie(r,e.label),n=ne.join(n,a);try{await U.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Wr(n,e.label);if(!st(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await Ie(r,e.label)}async function Ep(e){let t=ne.resolve(e.root),i=ne.resolve(e.source),r=ne.resolve(e.target);if(i===r||!st(t,i)||!st(t,r)||st(i,r)||st(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Wi({root:t,directory:ne.dirname(r),label:`${e.label} target parent`});let n=await zr(t,ne.dirname(i),e.label),a=await zr(t,ne.dirname(r),e.label),o=await Wr(i,e.label);if(!st(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await U.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Ie(n,e.label),Ie(a,e.label)]);let s=await U.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Fa(o,s)||await U.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await U.rename(i,r),await Promise.all([Ie(n,e.label),Ie(a,e.label)]);let c=await U.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Fa(o,c)||!st(n[0].realPath,await U.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await U.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Jr(e){let t=await ge({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await fg(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await U.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ge({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ge({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var j$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),$$=new Set(["id","type","source","target","staged","backup"]),O$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),H$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),D$=new Set(["sequence","timestamp","type","operationId"]),ab=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),ob=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),F$=256*1024,M$=1024*1024,sb=16*1024,Cu=1024,Cp=64*1024*1024,B$=2e4,cb=new I$("utf-8",{fatal:!0});function As(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _s(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 Ba(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Pp(e,t){if(typeof e!="string"||e.length===0||ni.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ru(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function ib(e,t){if(Pp(e,t),e.includes("\\")||e!==ni.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 L$(e,t){let i=As(e,`transaction operations[${t}]`);if(_s(i,$$,`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`);Pp(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Pp(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 Au(e){let t=As(e,"Native Archive transaction journal");if(_s(t,O$,"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"||!ab.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(!Ba(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ru(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=As(s,`Archive transaction operations[${c}]`);if(_s(l,H$,`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`);ib(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&ib(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ru(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(Ru(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`);Ru(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 xp(e){let t=As(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Au(t);if(_s(t,j$,"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"||!ab.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ni.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ni.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(!Ba(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(L$),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 lb(e,t){let i=As(e,`Native transaction event at line ${t}`);if(_s(i,D$,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Ba(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!ob.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function q$(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;rString(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Ba(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Ba(e)}function Ma(e,t){return e.lengthsb)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Ma(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!q$(n))return!1;if(r.length<24)return!0;if(!Ba(n))return!1;let a='","type":"',o=r.slice(24);if(Ma(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of ob){if(Ma(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(V$(l))return!0}else if(Ma(l,'"}'))return!0}return!1}function z$(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>sb)throw new Error(`Native transaction event at line ${t} is too large`);return lb(JSON.parse(e),t)}function J$(e){let t=e.split(` +`),i=t.at(-1)==="";if(i&&t.pop(),t.length>Cu)throw new Error(`Native transaction event log exceeds ${Cu} events`);let r=[];for(let n=0;nJSON.stringify(t)).join(` `)} -`}function J$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ni.join(e.transactionsDir,t)}function _u(e,t){let i=J$(e,t);return{directory:i,journal:ni.join(i,"transaction.json"),events:ni.join(i,"events.jsonl"),staged:ni.join(i,"staged"),backups:ni.join(i,"backups")}}async function zi(e,t){let i=_u(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function G$(e,t){if(t.length===0||ni.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=ni.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Gr(e,t){let i=G$(e,t);return T(j(e,i),i)}async function Wn(e){try{return await xs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ap(e,t,i={}){let r=await zi(e,t);try{await xs.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ge({root:e.runtimeDir,file:r.events,maxBytes:F$,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=sb.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=z$(a),s=lb(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function ib(e,t,i){let r=await Ap(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function ai(e,t,i,r){let n=await zi(e,t),a=await Ap(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await Ne(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>ib(e,t,a)}),o;if(a.events.length>=Cu)throw new Error(`Native transaction event log ${t} exceeds ${Cu} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return cb(s,s.sequence),await xs.mkdir(n.directory,{recursive:!0}),await Ne(n.events,lb([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>ib(e,t,a)}),s}async function _p(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=xp(t);let i=await zi(e,t.id);await xs.mkdir(i.staged,{recursive:!0}),await xs.mkdir(i.backups,{recursive:!0}),await ve(i.journal,t,{containedRoot:e.runtimeDir}),await ai(e,t.id,"prepared")}async function Ot(e,t,i={}){let r=await zi(e,t),n=await ge({root:e.runtimeDir,file:r.journal,maxBytes:D$,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(sb.decode(n.bytes)),o=xp(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Ur(e,t,i={}){return(await Ap(e,t,i)).events}async function xu(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=xp({...t,status:i});return await ve((await zi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function Rp(e,t,i){try{return await ge({root:j(e,t),file:t,maxBytes:Cp,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Tp(e,t,i,r){let n=await Rp(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await Rp(e,i,`${r} target`);await Wi({root:j(e,i),directory:ni.dirname(i),label:`${r} target parent`}),await Jr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Cp,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function ub(e,t,i){let r=await Rp(e,t,i);r&&await Pu({root:j(e,t),file:t,maxBytes:Cp,expectedHash:r.hash,expectedSize:r.size,label:i})}async function rb(e,t){if(!t.backup)return;let i=await Gr(e,t.target),r=await Gr(e,t.backup);!await Wn(i)||await Wn(r)||await Tp(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function U$(e,t){let i=await Gr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await rb(e,t),await Tp(e,await Gr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await rb(e,t),await ub(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await Gr(e,t.source),[n,a]=await Promise.all([Wn(r),Wn(i)]);if(!n&&a){await(await $t({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:M$})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Ep({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function db(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await xu(e,t,"applying"):t,n=await Ur(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await ai(e,r.id,"operation-started",s.id),await U$(e,s),await ai(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await Ot(e,r.id),r}async function K$(e,t){let i=await Gr(e,t.target),r=t.backup?await Gr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await Gr(e,t.source);if(await Wn(i)){if(await Wn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Ep({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Wn(r)?await Tp(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await ub(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Tu(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Ur(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await xu(e,t,"rolling-back");await ai(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await K$(e,a);return await ai(e,r.id,"rollback-completed"),r=await xu(e,r,"rolled-back"),r}async function La(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await ai(e,t.id,i),i==="commit"?xu(e,t,"committed"):t}async function Q$(e,t,i){let r;try{r=await Y$.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 Ot(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 Cs(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(XN(a))return!0}catch{return!0}return!1}async function Z$(e,t){let i=Date.now()+5e3,r=X$.join(e.locksDir,"root-move.lock");for(;;)try{return await cr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bs(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 F(e,t,i,r){let n=await Z$(e,t);try{if(await Ia(e.projectRoot),await Q$(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await lr(n)}}function fb(e){return Number.isSafeInteger(e)&&e>=1}async function hb(e){if(!fb(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!fb(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Hu}from"crypto";import{spawn as Sb}from"node:child_process";import{promises as be}from"fs";import J from"path";import{createHash as pb}from"crypto";import{createReadStream as eO}from"fs";async function oi(e){let t=pb("sha256");for await(let i of eO(e))t.update(i);return t.digest("hex")}function B(e){return pb("sha256").update(e).digest("hex")}var Iu={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Dp=1e3,tO=8*1024*1024,iO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rO=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),nO=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),aO=new Set(["schema","include","exclude","hash"]),oO=new Set(["provider","gitSelection","physicalSelection","projection"]),sO=new Set(["provider","selection"]),cO=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),lO=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),uO=new Set(["schema","status","before","after"]),dO=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),fO=new Set(["path","hash","size","type","gitObjectId"]),hO=new Set(["path","size","type","reason"]),pO=new Set(["ref","hash","count"]),mO=new Set(["change-created","legacy-migration","explicit"]),vO=new Set(["file","directory","other"]),gO=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Du=/^[a-f0-9]{64}$/u,Eb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,wO=new Set(["EACCES","EPERM"]),Ja=64*1024,Op=64*1024,yO=6e4,NO=1e3,bO=2,Fp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},kO={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Pb(e){let t=e.deadlineMs??yO;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Pi(e){return Math.max(0,e.deadlineAt-Date.now())}function V(e){return Pi(e)>=1}function Ip(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Wa(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function SO(e){let t={...kO,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function EO(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&J.win32.isAbsolute(r)?J.win32.resolve(r):"C:\\Windows",a=J.win32.join(n,"System32","taskkill.exe");if(!J.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=Sb(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),NO),u.unref()}catch{d(!1)}});for(let s=0;s{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=EO(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Ip(m.error):Ip()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Rb(e){let t={...Fp,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function ju(e,t,i,r=Op){let{child:n,completion:a}=Mp(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let m=Math.max(0,r-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=Ja)return;let m=Ja-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function jp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Is(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Mp(e,t,i,r.stdin!==void 0),c=[],l=Hu("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,g=!1,y=!1,E=S=>{let k=0;for(;k0&&(p.byteLength+N.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),v=!0,g=!0):p=Buffer.concat([p,N])),b<0)break;m+=1,p.byteLength===0&&!v&&(y=!0);let w=p.byteLength+1;!v&&m<=r.maxRecords&&h+w<=r.maxBytes?(c.push(p),h+=w):g=!0,p=Buffer.alloc(0),v=!1,k=b+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(g=!0);let k=r.outputChunkBytes;if(k===void 0){E(S);return}for(let b=0;b{if(d>=Ja)return;let k=Ja-d,b=Buffer.from(S).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(S!==null&&b.includes(S)&&k===null&&!y&&p.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function $u(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function PO(e,t,i){if(i.length===0)return new Set;let r=await Is(e,t,["check-ignore","--no-index","-z","--stdin"],{...Fp,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=$u(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function RO(e,t,i){let{child:r,completion:n}=Mp(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Ja)return;let d=Ja-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function za(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||J.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||J.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function CO(e,t){return e.map(i=>{let r=za(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function xO(e){let t=J.resolve(e);for(;;){try{return await be.lstat(J.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=J.dirname(t);if(i===t)return!1;t=i}}async function Cb(e,t,i,r={}){let n=J.resolve(t.projectRoot),a=J.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=J.relative(n,J.resolve(f)).replaceAll("\\","/"),m=za(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Is(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Is(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Is(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function xb(e){return{stageBefore:jp(e.stagedBefore),combined:jp(e.combined),stageAfter:jp(e.stagedAfter)}}async function Ab(e,t,i=Fp,r={}){let n=J.resolve(t.projectRoot);if(!await xO(n))return null;let a;try{a=await ju(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Wa(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Cb(e,t,i,r)}catch(y){throw Wa(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=y=>{for(let E of y){let S=$u(E),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?[0-7]{6}) (?[a-f0-9]{40}|[a-f0-9]{64}) (?[0-3])$/u.exec(S.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=za(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let m=c.records.map($u),p=CO(m,"combined"),v=new Set(p.filter(y=>!u.has(y))),g=new Set(p.filter((y,E)=>!u.has(y)&&m[E].endsWith("/")));for(let y of f)g.delete(y);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:xb(o)}}function Yr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function mb(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function AO(e,t){return!Yr(e.stageBefore,e.stageAfter)||!Yr(e.stageAfter,t.stageBefore)||!Yr(e.combined,t.combined)||!Yr(t.stageBefore,t.stageAfter)}async function _b(e,t,i,r,n){let a;try{a=await Cb(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Wa(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=xb(a),c=mb(o)||mb(s),l=AO(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:B(`comet.native.git-selection-overflow.v2 -${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var _O=(1n<<256n)-1n;function TO(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function vb(e){let t=J.resolve(e.paths.projectRoot),i=J.resolve(e.paths.nativeRoot),r=J.resolve(e.paths.runtimeDir),n=J.resolve(e.paths.configFile),a=J.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,m=!1,p=!1,v=()=>Pi(e.execution)>=1?!0:(h=!0,p=!0,!1),g=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),b=Hu("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;Re.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,p=!0;return}o.push(S)},y=async S=>{if(p||!v())return;let k;try{k=await be.opendir(S)}catch(P){if(!v())return;if(!Me(P)&&!Fe(P)||S===t&&Me(P))throw P;m||=Fe(P),h||=Me(P),p=!0;return}if(!v()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let b=!1,R;try{for(;!p&&v();){let P;try{P=await k.read()}catch(fe){if(!v())break;if(!Me(fe)&&!Fe(fe)||S===t&&Me(fe))throw fe;m||=Fe(fe),h||=Me(fe),p=!0;break}if(!v()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,p=!0;break}let L=J.join(S,P.name),H=jO(t,L);if(L===n||L===a||Ri(i,L)||Ri(r,L)||e.denylist.some(fe=>Ri(fe,L))||Hi(H)!==null)continue;if(!v())break;let nt;try{nt=await be.lstat(L)}catch(fe){if(!v())break;if(!Me(fe)&&!Fe(fe))throw fe;if(m=!0,g({path:H,type:"other"}),s.push({path:H,size:null,type:"file",reason:Me(fe)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;let Pe=TO(nt);if(Pe==="directory"){if(DO(e.policy,H))continue;if(!v())break;let fe;try{fe=await be.realpath(L)}catch(Oi){if(!v())break;if(!Me(Oi)&&!Fe(Oi))throw Oi;if(m=!0,g({path:H,type:Pe}),s.push({path:H,size:null,type:"directory",reason:Me(Oi)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;if(!$(e.physicalProjectRoot,fe)||Ri(e.physicalNativeRoot,fe))continue;if(g({path:H,type:Pe}),await e.hooks?.afterNode?.(H),!v()||(await y(L),p))break;continue}if(g({path:H,type:Pe}),await e.hooks?.afterNode?.(H),!v()||p)break}}catch(P){b=!0,R=P}let N;try{await k.close()}catch(P){N=P}let w=v();if(b)throw R;if(w&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await y(t),v(),h?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let E=h?B(`comet.native.physical-selection-incomplete.v1 +`}function G$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ni.join(e.transactionsDir,t)}function _u(e,t){let i=G$(e,t);return{directory:i,journal:ni.join(i,"transaction.json"),events:ni.join(i,"events.jsonl"),staged:ni.join(i,"staged"),backups:ni.join(i,"backups")}}async function zi(e,t){let i=_u(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function U$(e,t){if(t.length===0||ni.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=ni.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Gr(e,t){let i=U$(e,t);return T(j(e,i),i)}async function Wn(e){try{return await xs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ap(e,t,i={}){let r=await zi(e,t);try{await xs.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ge({root:e.runtimeDir,file:r.events,maxBytes:M$,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=cb.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=J$(a),s=ub(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function rb(e,t,i){let r=await Ap(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function ai(e,t,i,r){let n=await zi(e,t),a=await Ap(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await Ne(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>rb(e,t,a)}),o;if(a.events.length>=Cu)throw new Error(`Native transaction event log ${t} exceeds ${Cu} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return lb(s,s.sequence),await xs.mkdir(n.directory,{recursive:!0}),await Ne(n.events,ub([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>rb(e,t,a)}),s}async function _p(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=xp(t);let i=await zi(e,t.id);await xs.mkdir(i.staged,{recursive:!0}),await xs.mkdir(i.backups,{recursive:!0}),await ve(i.journal,t,{containedRoot:e.runtimeDir}),await ai(e,t.id,"prepared")}async function Ot(e,t,i={}){let r=await zi(e,t),n=await ge({root:e.runtimeDir,file:r.journal,maxBytes:F$,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(cb.decode(n.bytes)),o=xp(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Ur(e,t,i={}){return(await Ap(e,t,i)).events}async function xu(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=xp({...t,status:i});return await ve((await zi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function Rp(e,t,i){try{return await ge({root:j(e,t),file:t,maxBytes:Cp,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Tp(e,t,i,r){let n=await Rp(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await Rp(e,i,`${r} target`);await Wi({root:j(e,i),directory:ni.dirname(i),label:`${r} target parent`}),await Jr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Cp,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function db(e,t,i){let r=await Rp(e,t,i);r&&await Pu({root:j(e,t),file:t,maxBytes:Cp,expectedHash:r.hash,expectedSize:r.size,label:i})}async function nb(e,t){if(!t.backup)return;let i=await Gr(e,t.target),r=await Gr(e,t.backup);!await Wn(i)||await Wn(r)||await Tp(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function K$(e,t){let i=await Gr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await nb(e,t),await Tp(e,await Gr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await nb(e,t),await db(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await Gr(e,t.source),[n,a]=await Promise.all([Wn(r),Wn(i)]);if(!n&&a){await(await $t({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:B$})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Ep({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function fb(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await xu(e,t,"applying"):t,n=await Ur(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await ai(e,r.id,"operation-started",s.id),await K$(e,s),await ai(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await Ot(e,r.id),r}async function Y$(e,t){let i=await Gr(e,t.target),r=t.backup?await Gr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await Gr(e,t.source);if(await Wn(i)){if(await Wn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Ep({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Wn(r)?await Tp(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await db(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Tu(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Ur(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await xu(e,t,"rolling-back");await ai(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await Y$(e,a);return await ai(e,r.id,"rollback-completed"),r=await xu(e,r,"rolled-back"),r}async function La(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await ai(e,t.id,i),i==="commit"?xu(e,t,"committed"):t}async function Z$(e,t,i){let r;try{r=await X$.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 Ot(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 Cs(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(QN(a))return!0}catch{return!0}return!1}async function eO(e,t){let i=Date.now()+5e3,r=Q$.join(e.locksDir,"root-move.lock");for(;;)try{return await cr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bs(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 F(e,t,i,r){let n=await eO(e,t);try{if(await Ia(e.projectRoot),await Z$(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await lr(n)}}function hb(e){return Number.isSafeInteger(e)&&e>=1}async function pb(e){if(!hb(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!hb(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Hu}from"crypto";import{spawn as Eb}from"node:child_process";import{promises as be}from"fs";import J from"path";import{createHash as mb}from"crypto";import{createReadStream as tO}from"fs";async function oi(e){let t=mb("sha256");for await(let i of tO(e))t.update(i);return t.digest("hex")}function B(e){return mb("sha256").update(e).digest("hex")}var Iu={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Dp=1e3,iO=8*1024*1024,rO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nO=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),aO=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),oO=new Set(["schema","include","exclude","hash"]),sO=new Set(["provider","gitSelection","physicalSelection","projection"]),cO=new Set(["provider","selection"]),lO=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),uO=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),dO=new Set(["schema","status","before","after"]),fO=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),hO=new Set(["path","hash","size","type","gitObjectId"]),pO=new Set(["path","size","type","reason"]),mO=new Set(["ref","hash","count"]),vO=new Set(["change-created","legacy-migration","explicit"]),gO=new Set(["file","directory","other"]),wO=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Du=/^[a-f0-9]{64}$/u,Pb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,yO=new Set(["EACCES","EPERM"]),Ja=64*1024,Op=64*1024,NO=6e4,bO=1e3,kO=2,Fp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},SO={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Rb(e){let t=e.deadlineMs??NO;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Pi(e){return Math.max(0,e.deadlineAt-Date.now())}function V(e){return Pi(e)>=1}function Ip(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Wa(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function EO(e){let t={...SO,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function PO(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&J.win32.isAbsolute(r)?J.win32.resolve(r):"C:\\Windows",a=J.win32.join(n,"System32","taskkill.exe");if(!J.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=Eb(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),bO),u.unref()}catch{d(!1)}});for(let s=0;s{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=PO(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Ip(m.error):Ip()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Cb(e){let t={...Fp,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function ju(e,t,i,r=Op){let{child:n,completion:a}=Mp(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let m=Math.max(0,r-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=Ja)return;let m=Ja-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function jp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Is(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Mp(e,t,i,r.stdin!==void 0),c=[],l=Hu("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,g=!1,y=!1,E=S=>{let k=0;for(;k0&&(p.byteLength+N.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),v=!0,g=!0):p=Buffer.concat([p,N])),b<0)break;m+=1,p.byteLength===0&&!v&&(y=!0);let w=p.byteLength+1;!v&&m<=r.maxRecords&&h+w<=r.maxBytes?(c.push(p),h+=w):g=!0,p=Buffer.alloc(0),v=!1,k=b+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(g=!0);let k=r.outputChunkBytes;if(k===void 0){E(S);return}for(let b=0;b{if(d>=Ja)return;let k=Ja-d,b=Buffer.from(S).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(S!==null&&b.includes(S)&&k===null&&!y&&p.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function $u(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function RO(e,t,i){if(i.length===0)return new Set;let r=await Is(e,t,["check-ignore","--no-index","-z","--stdin"],{...Fp,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=$u(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function CO(e,t,i){let{child:r,completion:n}=Mp(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Ja)return;let d=Ja-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function za(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||J.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||J.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function xO(e,t){return e.map(i=>{let r=za(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function AO(e){let t=J.resolve(e);for(;;){try{return await be.lstat(J.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=J.dirname(t);if(i===t)return!1;t=i}}async function xb(e,t,i,r={}){let n=J.resolve(t.projectRoot),a=J.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=J.relative(n,J.resolve(f)).replaceAll("\\","/"),m=za(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Is(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Is(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Is(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Ab(e){return{stageBefore:jp(e.stagedBefore),combined:jp(e.combined),stageAfter:jp(e.stagedAfter)}}async function _b(e,t,i=Fp,r={}){let n=J.resolve(t.projectRoot);if(!await AO(n))return null;let a;try{a=await ju(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Wa(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await xb(e,t,i,r)}catch(y){throw Wa(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=y=>{for(let E of y){let S=$u(E),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?[0-7]{6}) (?[a-f0-9]{40}|[a-f0-9]{64}) (?[0-3])$/u.exec(S.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=za(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let m=c.records.map($u),p=xO(m,"combined"),v=new Set(p.filter(y=>!u.has(y))),g=new Set(p.filter((y,E)=>!u.has(y)&&m[E].endsWith("/")));for(let y of f)g.delete(y);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:Ab(o)}}function Yr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function vb(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function _O(e,t){return!Yr(e.stageBefore,e.stageAfter)||!Yr(e.stageAfter,t.stageBefore)||!Yr(e.combined,t.combined)||!Yr(t.stageBefore,t.stageAfter)}async function Tb(e,t,i,r,n){let a;try{a=await xb(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Wa(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=Ab(a),c=vb(o)||vb(s),l=_O(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:B(`comet.native.git-selection-overflow.v2 +${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var TO=(1n<<256n)-1n;function IO(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function gb(e){let t=J.resolve(e.paths.projectRoot),i=J.resolve(e.paths.nativeRoot),r=J.resolve(e.paths.runtimeDir),n=J.resolve(e.paths.configFile),a=J.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,m=!1,p=!1,v=()=>Pi(e.execution)>=1?!0:(h=!0,p=!0,!1),g=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),b=Hu("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;Re.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,p=!0;return}o.push(S)},y=async S=>{if(p||!v())return;let k;try{k=await be.opendir(S)}catch(P){if(!v())return;if(!Me(P)&&!Fe(P)||S===t&&Me(P))throw P;m||=Fe(P),h||=Me(P),p=!0;return}if(!v()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let b=!1,R;try{for(;!p&&v();){let P;try{P=await k.read()}catch(he){if(!v())break;if(!Me(he)&&!Fe(he)||S===t&&Me(he))throw he;m||=Fe(he),h||=Me(he),p=!0;break}if(!v()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,p=!0;break}let L=J.join(S,P.name),H=$O(t,L);if(L===n||L===a||Ri(i,L)||Ri(r,L)||e.denylist.some(he=>Ri(he,L))||Hi(H)!==null)continue;if(!v())break;let nt;try{nt=await be.lstat(L)}catch(he){if(!v())break;if(!Me(he)&&!Fe(he))throw he;if(m=!0,g({path:H,type:"other"}),s.push({path:H,size:null,type:"file",reason:Me(he)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;let Pe=IO(nt);if(Pe==="directory"){if(FO(e.policy,H))continue;if(!v())break;let he;try{he=await be.realpath(L)}catch(Oi){if(!v())break;if(!Me(Oi)&&!Fe(Oi))throw Oi;if(m=!0,g({path:H,type:Pe}),s.push({path:H,size:null,type:"directory",reason:Me(Oi)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;if(!$(e.physicalProjectRoot,he)||Ri(e.physicalNativeRoot,he))continue;if(g({path:H,type:Pe}),await e.hooks?.afterNode?.(H),!v()||(await y(L),p))break;continue}if(g({path:H,type:Pe}),await e.hooks?.afterNode?.(H),!v()||p)break}}catch(P){b=!0,R=P}let N;try{await k.close()}catch(P){N=P}let w=v();if(b)throw R;if(w&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await y(t),v(),h?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let E=h?B(`comet.native.physical-selection-incomplete.v1 ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):B(`comet.native.physical-selection.v1 -${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:m}}}function Tb(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function IO(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!Tb(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Ib(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function gb(e,t){let r=(await ju(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Eb.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return B(`gitlink:${r}`)}async function wb(e,t){let i=await gb(e,t),r=await RO(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await gb(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Ts(e,t){if(Hi(t)!==null)return!1;let i=J.resolve(e.projectRoot,...t.split("/"));return!Ri(J.resolve(e.nativeRoot),i)&&!Ri(J.resolve(e.runtimeDir),i)}function Bp(e,t={}){let i=fr(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.lengthJ.resolve(e,...i.split(/[\\/]/u)))}function Ri(e,t){let i=J.resolve(e),r=J.resolve(t);return r===i||$(i,r)}function Me(e){return wO.has(e.code??"")}function Fe(e){return e.code==="ENOENT"}function Lp(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` -`)}function OO(e,t){return B(`comet.native.snapshot-policy.v1 -${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function $p(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function HO(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function yb(e){let t=su(e,"Native snapshot pattern"),i=[];for(let r=0;r{let a=n?HO(n):void 0;if(a&&!a())return!1;let o=$p(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=$p(i,c,a),o===null||o.size===0)return!1}return $p(i,o,a)?.has(i.length)??!1}}function jb(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>su(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>su(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=OO(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(yb),excludeMatchers:i.map(yb),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function DO(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Nb(e,t,i){if(!e)return!0;let r=()=>V(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function js(e,t,i){let r=JSON.stringify(i);return B(`${e} +${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:m}}}function Ib(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function jO(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!Ib(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function jb(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function wb(e,t){let r=(await ju(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Pb.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return B(`gitlink:${r}`)}async function yb(e,t){let i=await wb(e,t),r=await CO(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await wb(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Ts(e,t){if(Hi(t)!==null)return!1;let i=J.resolve(e.projectRoot,...t.split("/"));return!Ri(J.resolve(e.nativeRoot),i)&&!Ri(J.resolve(e.runtimeDir),i)}function Bp(e,t={}){let i=fr(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.lengthJ.resolve(e,...i.split(/[\\/]/u)))}function Ri(e,t){let i=J.resolve(e),r=J.resolve(t);return r===i||$(i,r)}function Me(e){return yO.has(e.code??"")}function Fe(e){return e.code==="ENOENT"}function Lp(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` +`)}function HO(e,t){return B(`comet.native.snapshot-policy.v1 +${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function $p(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function DO(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Nb(e){let t=su(e,"Native snapshot pattern"),i=[];for(let r=0;r{let a=n?DO(n):void 0;if(a&&!a())return!1;let o=$p(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=$p(i,c,a),o===null||o.size===0)return!1}return $p(i,o,a)?.has(i.length)??!1}}function $b(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>su(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>su(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=HO(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(Nb),excludeMatchers:i.map(Nb),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function FO(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function bb(e,t,i){if(!e)return!0;let r=()=>V(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function js(e,t,i){let r=JSON.stringify(i);return B(`${e} ${Buffer.byteLength(t)}:${t} -${Buffer.byteLength(r)}:${r}`)}function Hp(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ou(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Hp(i))return e.splice(t,1),i}return null}function Kr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function FO(e,t,i,r){if(!V(r))return{status:"budget-exhausted"};let n;try{n=await be.open(e,"r")}catch(c){if(!V(r))return{status:"budget-exhausted"};throw c}if(!V(r))return await n.close(),{status:"budget-exhausted"};let a=Hu("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!V(r))return{status:"budget-exhausted"};let c=await n.stat();if(!V(r))return{status:"budget-exhausted"};if(!c.isFile()||!Kr(i,c))return{status:"changed"};for(;;){if(!V(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!V(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!V(r))return{status:"budget-exhausted"};let d=await n.stat();return V(r)?!d.isFile()||!Kr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function si(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ci(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Va(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ji(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function $b(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=J.posix.normalize(e);if(i!==e||J.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function MO(e,t){let i=si(e,`Native snapshot entry ${t}`);ci(i,fO,`Native snapshot entry ${t}`);let r=$b(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:Ji(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Eb.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function BO(e,t){let i=si(e,`Native snapshot omission ${t}`);if(ci(i,hO,`Native snapshot omission ${t}`),!vO.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!gO.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:$b(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:Ji(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function LO(e){let t=si(e,"Native snapshot omission overflow");if(ci(t,pO,"Native snapshot omission overflow"),typeof t.hash!="string"||!Du.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Va(t.count,"Native snapshot omission overflow count")}}function qa(e,t){let i=si(e,t);if(ci(i,lO,t),typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=Ji(i.recordCount,`${t} recordCount`),n=Ji(i.storedRecordCount,`${t} storedRecordCount`),a=Ji(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function bb(e){let t=si(e,"Native Git selection evidence");if(ci(t,cO,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=qa(t.stageBefore,"Native Git selection stageBefore"),r=qa(t.combined,"Native Git selection combined"),n=qa(t.stageAfter,"Native Git selection stageAfter"),a=qa(t.finalStageBefore,"Native Git selection finalStageBefore"),o=qa(t.finalCombined,"Native Git selection finalCombined"),s=qa(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Yr(i,n)||!Yr(n,a)||!Yr(r,o)||!Yr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function kb(e,t){let i=si(e,t);if(ci(i,dO,t),typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=Ji(i.visitedNodeCount,`${t} visitedNodeCount`),n=Ji(i.recordCount,`${t} recordCount`),a=Ji(i.storedRecordCount,`${t} storedRecordCount`),o=Ji(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function qO(e){let t=si(e,"Native physical selection evidence");if(ci(t,uO,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=kb(t.before,"Native physical selection before"),r=kb(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!Tb(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function fr(e){let t=si(e,"Native content snapshot manifest");if(ci(t,rO,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!mO.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=si(t.capture,"Native content snapshot capture");if(ci(b,oO,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:bb(b.gitSelection),N=b.physicalSelection===void 0?void 0:qO(b.physicalSelection),w=null;if(b.projection!==void 0){let P=si(b.projection,"Native content snapshot projection");if(ci(P,sO,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:bb(P.selection)}}}if(b.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=si(t.limits,"Native content snapshot limits");ci(r,nO,"Native content snapshot limits");let n={maxFiles:Va(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Va(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Va(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Va(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Va(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=si(t.policy,"Native snapshot policy");if(ci(b,aO,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=jb({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(MO),s=t.omitted.map(BO),c=Ji(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:LO(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,R)=>b+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Dp||c0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...v,...g])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,E=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(E!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Lp(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Fu(e,t,i={}){let r=fr(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=J.resolve(e.projectRoot),a=Pb(i),o=Rb(i.gitSelectionLimits),s=await Ab(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Ib(s).filter(N=>Ts(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>Ts(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),m=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),p=await PO(a,n,m),v=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&Ts(e,N.path)&&(c.has(N.path)||!p.has(N.path)));await _b(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let N of l)g.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omitted.filter(N=>f(N.path)||h(N.path)||!Ts(e,N.path)?!1:p.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of g)y.some(w=>w.path===N.path&&w.reason===N.reason)||y.push(N);y.sort((N,w)=>N.path.localeCompare(w.path,"en"));let E=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??B("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,S=js(S,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{E+=1,S=js(S,"omission",N)};for(;y.length>Dp;){let N=Ou(y);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+E===0,entries:v,omitted:y,omittedCount:y.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:E}}:{}}),R=b();for(;Lp(R)>r.limits.maxManifestBytes;){let N=Ou(y);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=b()}return fr(R)}function Ob(e,t){if(!iO.test(t))throw new Error(`Invalid Native change name: ${t}`);return J.join(M(e,t),"baseline-manifest.json")}async function Mu(e,t={}){let i={maxFiles:t.limits?.maxFiles??Iu.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Iu.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Iu.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Iu.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=jb(t.policy),n=Pb({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Rb(t.gitSelectionLimits),o=SO(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=J.resolve(e.projectRoot),c=await be.realpath(s),l=J.resolve(e.nativeRoot),u=await be.realpath(l),d=J.resolve(e.runtimeDir),f=J.resolve(e.configFile),h=J.join(s,".comet","current-change.json"),m=$O(s,t.denylist??[]),p=[],v=[],g=new Map,y=new Map,E=0,S=0,k=B("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,N=null,w=_=>{S+=1,k=js(k,"omission",_)},P=_=>{if(E+=1,v.length{E+=_.count,S+=_.count,k=js(k,"git-selection",{source:"git-selection",..._})},H=_=>{S+=1,k=js(k,"manifest-entry",{reason:"manifest-size",entry:_})},nt=async(_,A)=>{p.push(_),b+=_.size,g.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Pe=(_,A)=>{let I=p.findIndex(ye=>ye.path===_);if(I<0)return;let[G]=p.splice(I,1);b-=G.size,g.delete(_),P(A)},fe=async(_,A,I,G)=>{if(!I.isFile()||I.isSymbolicLink()||!V(n))return;let ye;try{ye=await be.realpath(_)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:I.size,type:"file",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(!V(n)||!$(c,ye)||Ri(u,ye))return;if(p.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let Z,z,_e;try{if(Z=await FO(ye,I.size,I,n),Z.status==="budget-exhausted"||!V(n))return;if(Z.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!V(n)||(_e=await be.realpath(_),!V(n)))return;z=await be.lstat(_)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:I.size,type:"file",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(V(n)){if(Z.bytes!==I.size||_e!==ye||!Kr(I,Z.finalStat)||!Kr(Z.finalStat,z)||!z.isFile()||z.isSymbolicLink()||z.size!==I.size||z.mtimeMs!==I.mtimeMs||z.ctimeMs!==I.ctimeMs){P({path:A,size:z.isFile()?z.size:null,type:z.isFile()?"file":"other",reason:"changed-during-read"});return}V(n)&&await nt({path:A,hash:Z.hash,size:z.size,type:"file",...G===void 0?{}:{gitObjectId:G}},{kind:"file",target:_,realTarget:ye,stat:z})}},Oi=async(_,A,I)=>{if(!V(n))return;let G,ye,Z;try{if(G=await be.readlink(_,{encoding:"buffer"}),!V(n)||(Z=await be.lstat(_),!V(n)))return;ye=await be.readlink(_,{encoding:"buffer"})}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:null,type:"other",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(!V(n))return;if(!Z.isSymbolicLink()||!Kr(I,Z)||Z.mtimeMs!==I.mtimeMs||Z.ctimeMs!==I.ctimeMs||!G.equals(ye)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let z=G.byteLength;if(p.length>=i.maxFiles){P({path:A,size:z,type:"other",reason:"file-count"});return}if(z>i.maxFileBytes){P({path:A,size:z,type:"other",reason:"file-size"});return}if(b+z>i.maxTotalBytes){P({path:A,size:z,type:"other",reason:"total-size"});return}let _e=Hu("sha256").update("symlink\0").update(G).digest("hex");V(n)&&await nt({path:A,hash:_e,size:z,type:"file"},{kind:"symlink",target:_,rawTarget:G,stat:Z})},vi=async()=>{for(let[_,A]of[...g]){if(!V(n))return;if(A.kind==="file"){let z,_e;try{if(z=await be.realpath(A.target),!V(n))return;_e=await be.lstat(A.target)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;Pe(_,{path:_,size:null,type:"file",reason:Me(x)?"unreadable":"changed-during-read"});continue}if(!V(n))return;(z!==A.realTarget||!_e.isFile()||_e.isSymbolicLink()||!Kr(A.stat,_e)||_e.size!==A.stat.size||_e.mtimeMs!==A.stat.mtimeMs||_e.ctimeMs!==A.stat.ctimeMs)&&Pe(_,{path:_,size:_e.isFile()?_e.size:null,type:_e.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let z,_e;try{if(z=await be.lstat(A.target),!V(n))return;_e=await be.readlink(A.target,{encoding:"buffer"})}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;Pe(_,{path:_,size:null,type:"other",reason:Me(x)?"unreadable":"changed-during-read"});continue}if(!V(n))return;(!z.isSymbolicLink()||!Kr(A.stat,z)||z.mtimeMs!==A.stat.mtimeMs||z.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(_e))&&Pe(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,G;try{if(I=await be.realpath(A.target),!V(n))return;G=await be.lstat(A.target)}catch{if(!V(n))return;Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!V(n))return;if(!(I===A.realTarget&&G.isDirectory()&&!G.isSymbolicLink()&&Kr(A.stat,G)&&$(c,I)&&!Ri(u,I))){Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let Z;try{if(!V(n))return;Z=await wb(n,I)}catch(z){if(Wa(z))throw z;Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!V(n))return;Z.dirty?Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):Z.hash!==A.hash&&Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!V(n))return;try{let I=await be.lstat(A);if(!V(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!V(n))return;if(Fe(I))continue;if(!Me(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},Lt=await Ab(n,e,a,t.gitSelectionHooks);if(Lt===null){let _=await vb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let G of _.records){if(G.type!=="file"&&G.type!=="symlink"||g.has(G.path))continue;if(Pi(n)<1)break;if(!Nb(r,G.path,n))continue;if(Pi(n)<1)break;let ye=J.resolve(s,...G.path.split("/")),Z;try{Z=await be.lstat(ye)}catch(z){if(!V(n))break;if(!Me(z)&&!Fe(z))throw z;P({path:G.path,size:null,type:"file",reason:Fe(z)?"changed-during-read":"unreadable"});continue}if(Pi(n)<1)break;if(G.type==="symlink"&&Z.isSymbolicLink()){if(await Oi(ye,G.path,Z),Pi(n)<1)break;continue}if(G.type!=="file"||!Z.isFile()||Z.isSymbolicLink()){P({path:G.path,size:Z.isFile()?Z.size:null,type:Z.isDirectory()?"directory":Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await fe(ye,G.path,Z),Pi(n)<1)break}Pi(n)>=1&&await vi();let A=await vb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o}),I=IO(_.evidence,A.evidence);N=I.evidence;for(let G of[..._.omissions,...A.omissions,...I.omissions])v.some(ye=>ye.path===G.path&&ye.reason===G.reason)||P(G)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=fr(_);for(let Re of x.entries)Re.gitObjectId!==void 0&&A.set(Re.path,Re);I=A.size>0}let G=new Set,ye=!0;try{let x=await Is(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,ye=!1,A.clear();else for(let Re of x.records){let Te=$u(Re),vt=Te.indexOf(" "),at=vt<0?null:za(Te.slice(vt+1));if(vt!==1||at===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");Te[0]!=="H"&&G.add(at)}}catch(x){if(Wa(x))throw x;I=!1,ye=!1,A.clear()}let Z=new Set;try{let x=await ju(n,s,["ls-files","--modified","-z"],Op);for(let Re of x.toString("utf8").split("\0")){let Te=za(Re);Te!==null&&Z.add(Te)}}catch{I=!1,ye=!1,A.clear()}let z=new Set,_e=new Set;for(let x of Ib(Lt)){if(g.has(x)||!Ts(e,x))continue;if(Pi(n)<1)break;if(!Nb(r,x,n))continue;if(Pi(n)<1)break;let Re=J.resolve(s,...x.split("/"));if(Re===f||Re===h||Ri(d,Re)||m.some(qt=>Ri(qt,Re)))continue;if(Lt.gitlinks.has(x)){if(p.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let qt,Wc;try{[qt,Wc]=await Promise.all([be.realpath(Re),be.lstat(Re)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Wc.isSymbolicLink()||!Wc.isDirectory()||!$(c,qt)||Ri(u,qt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let pa=await wb(n,qt);if(pa.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await nt({path:x,hash:pa.hash,size:0,type:"file"},{kind:"gitlink",target:Re,realTarget:qt,stat:Wc,hash:pa.hash})}catch(pa){if(Wa(pa))throw pa;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let Te;try{Te=await be.lstat(Re)}catch(qt){if(Fe(qt)&&Lt.tracked.has(x)){y.set(x,Re);continue}if(!Me(qt)&&!Fe(qt))throw qt;P({path:x,size:null,type:"file",reason:Fe(qt)?"changed-during-read":"unreadable"});continue}if(Te.isSymbolicLink()){await Oi(Re,x,Te);continue}if(!Te.isFile()){Lt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let vt=Lt.trackedObjectIds.get(x),at=vt?A.get(x):void 0;if(I&&at?.gitObjectId!==void 0&&at.gitObjectId===vt&&!G.has(x)&&!Z.has(x)){if(p.length>=i.maxFiles){P({path:x,size:at.size,type:"file",reason:"file-count"});continue}if(at.size>i.maxFileBytes){P({path:x,size:at.size,type:"file",reason:"file-size"});continue}if(b+at.size>i.maxTotalBytes){P({path:x,size:at.size,type:"file",reason:"total-size"});continue}p.push({...at}),b+=at.size,z.add(x);continue}let sg=ye&&!G.has(x)&&!Z.has(x)?vt:void 0;await fe(Re,x,Te,sg),sg!==void 0&&_e.add(x)}if(await vi(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await _b(n,e,a,Lt,t.gitSelectionHooks?.outputChunkBytes),z.size>0||I&&_e.size>0){let x=await ju(n,s,["ls-files","--modified","-z"],Op),Re=new Set;for(let Te of x.toString("utf8").split("\0")){let vt=za(Te);vt!==null&&Re.add(vt)}for(let Te of z){if(!Re.has(Te))continue;let vt=p.find(at=>at.path===Te);Pe(Te,{path:Te,size:vt?.size??null,type:"file",reason:"changed-during-read"})}for(let Te of _e){if(!Re.has(Te))continue;let vt=p.find(at=>at.path===Te);vt&&delete vt.gitObjectId}}for(let x of Lt.omissions)P(x);Lt.overflow&&L(Lt.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let IC=Lt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...Lt.evidence?{gitSelection:Lt.evidence}:{}},og=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:IC,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:v,omittedCount:E,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),lf=og();for(;Lp(lf)>i.maxManifestBytes;){if(v.filter(A=>!Hp(A)).length>0){let A=Math.max(1,Math.ceil(v.length/4));for(let I=0;I0){let A=Math.max(1,Math.ceil(p.length/4));for(let I of p.splice(-A))E+=1,H(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");lf=og()}return lf}async function qp(e,t,i={}){let n=(await Y(e.projectRoot))?.native.snapshot??cp;return Mu(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Vp(e,t,i){let r=Ob(e,t);await T(j(e,r),r),await ve(r,fr(i))}async function Ga(e,t){let i=Ob(e,t),r=j(e,i);await T(r,i);try{let n=await Eu({root:r,file:i,maxBytes:tO,label:"Native baseline snapshot manifest"});return fr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as v0}from"crypto";import g0 from"path";var zt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as u0}from"node:crypto";import{constants as Vu,promises as bt}from"node:fs";import Jt from"node:path";import{TextDecoder as d0}from"node:util";import o0 from"path";var UO=ma(_n(),1);import{promises as KO}from"node:fs";import YO from"node:path";var $s=".gitignore",Hb=4*1024*1024,Db="# >>> Comet managed project state >>>",Fb="# <<< Comet managed project state <<<";function XO(e){return e.includes(`\r +${Buffer.byteLength(r)}:${r}`)}function Hp(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ou(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Hp(i))return e.splice(t,1),i}return null}function Kr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function MO(e,t,i,r){if(!V(r))return{status:"budget-exhausted"};let n;try{n=await be.open(e,"r")}catch(c){if(!V(r))return{status:"budget-exhausted"};throw c}if(!V(r))return await n.close(),{status:"budget-exhausted"};let a=Hu("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!V(r))return{status:"budget-exhausted"};let c=await n.stat();if(!V(r))return{status:"budget-exhausted"};if(!c.isFile()||!Kr(i,c))return{status:"changed"};for(;;){if(!V(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!V(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!V(r))return{status:"budget-exhausted"};let d=await n.stat();return V(r)?!d.isFile()||!Kr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function si(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ci(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Va(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ji(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Ob(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=J.posix.normalize(e);if(i!==e||J.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function BO(e,t){let i=si(e,`Native snapshot entry ${t}`);ci(i,hO,`Native snapshot entry ${t}`);let r=Ob(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:Ji(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Pb.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function LO(e,t){let i=si(e,`Native snapshot omission ${t}`);if(ci(i,pO,`Native snapshot omission ${t}`),!gO.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!wO.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Ob(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:Ji(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function qO(e){let t=si(e,"Native snapshot omission overflow");if(ci(t,mO,"Native snapshot omission overflow"),typeof t.hash!="string"||!Du.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Va(t.count,"Native snapshot omission overflow count")}}function qa(e,t){let i=si(e,t);if(ci(i,uO,t),typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=Ji(i.recordCount,`${t} recordCount`),n=Ji(i.storedRecordCount,`${t} storedRecordCount`),a=Ji(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function kb(e){let t=si(e,"Native Git selection evidence");if(ci(t,lO,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=qa(t.stageBefore,"Native Git selection stageBefore"),r=qa(t.combined,"Native Git selection combined"),n=qa(t.stageAfter,"Native Git selection stageAfter"),a=qa(t.finalStageBefore,"Native Git selection finalStageBefore"),o=qa(t.finalCombined,"Native Git selection finalCombined"),s=qa(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Yr(i,n)||!Yr(n,a)||!Yr(r,o)||!Yr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Sb(e,t){let i=si(e,t);if(ci(i,fO,t),typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=Ji(i.visitedNodeCount,`${t} visitedNodeCount`),n=Ji(i.recordCount,`${t} recordCount`),a=Ji(i.storedRecordCount,`${t} storedRecordCount`),o=Ji(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function VO(e){let t=si(e,"Native physical selection evidence");if(ci(t,dO,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Sb(t.before,"Native physical selection before"),r=Sb(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!Ib(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function fr(e){let t=si(e,"Native content snapshot manifest");if(ci(t,nO,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!vO.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=si(t.capture,"Native content snapshot capture");if(ci(b,sO,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:kb(b.gitSelection),N=b.physicalSelection===void 0?void 0:VO(b.physicalSelection),w=null;if(b.projection!==void 0){let P=si(b.projection,"Native content snapshot projection");if(ci(P,cO,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:kb(P.selection)}}}if(b.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=si(t.limits,"Native content snapshot limits");ci(r,aO,"Native content snapshot limits");let n={maxFiles:Va(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Va(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Va(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Va(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Va(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=si(t.policy,"Native snapshot policy");if(ci(b,oO,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=$b({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(BO),s=t.omitted.map(LO),c=Ji(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:qO(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,R)=>b+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Dp||c0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...v,...g])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,E=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(E!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Lp(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Fu(e,t,i={}){let r=fr(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=J.resolve(e.projectRoot),a=Rb(i),o=Cb(i.gitSelectionLimits),s=await _b(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(jb(s).filter(N=>Ts(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>Ts(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),m=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),p=await RO(a,n,m),v=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&Ts(e,N.path)&&(c.has(N.path)||!p.has(N.path)));await Tb(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let N of l)g.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omitted.filter(N=>f(N.path)||h(N.path)||!Ts(e,N.path)?!1:p.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of g)y.some(w=>w.path===N.path&&w.reason===N.reason)||y.push(N);y.sort((N,w)=>N.path.localeCompare(w.path,"en"));let E=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??B("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,S=js(S,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{E+=1,S=js(S,"omission",N)};for(;y.length>Dp;){let N=Ou(y);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+E===0,entries:v,omitted:y,omittedCount:y.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:E}}:{}}),R=b();for(;Lp(R)>r.limits.maxManifestBytes;){let N=Ou(y);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=b()}return fr(R)}function Hb(e,t){if(!rO.test(t))throw new Error(`Invalid Native change name: ${t}`);return J.join(M(e,t),"baseline-manifest.json")}async function Mu(e,t={}){let i={maxFiles:t.limits?.maxFiles??Iu.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Iu.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Iu.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Iu.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=$b(t.policy),n=Rb({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Cb(t.gitSelectionLimits),o=EO(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=J.resolve(e.projectRoot),c=await be.realpath(s),l=J.resolve(e.nativeRoot),u=await be.realpath(l),d=J.resolve(e.runtimeDir),f=J.resolve(e.configFile),h=J.join(s,".comet","current-change.json"),m=OO(s,t.denylist??[]),p=[],v=[],g=new Map,y=new Map,E=0,S=0,k=B("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,N=null,w=_=>{S+=1,k=js(k,"omission",_)},P=_=>{if(E+=1,v.length{E+=_.count,S+=_.count,k=js(k,"git-selection",{source:"git-selection",..._})},H=_=>{S+=1,k=js(k,"manifest-entry",{reason:"manifest-size",entry:_})},nt=async(_,A)=>{p.push(_),b+=_.size,g.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Pe=(_,A)=>{let I=p.findIndex(ye=>ye.path===_);if(I<0)return;let[G]=p.splice(I,1);b-=G.size,g.delete(_),P(A)},he=async(_,A,I,G)=>{if(!I.isFile()||I.isSymbolicLink()||!V(n))return;let ye;try{ye=await be.realpath(_)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:I.size,type:"file",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(!V(n)||!$(c,ye)||Ri(u,ye))return;if(p.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let Z,z,_e;try{if(Z=await MO(ye,I.size,I,n),Z.status==="budget-exhausted"||!V(n))return;if(Z.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!V(n)||(_e=await be.realpath(_),!V(n)))return;z=await be.lstat(_)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:I.size,type:"file",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(V(n)){if(Z.bytes!==I.size||_e!==ye||!Kr(I,Z.finalStat)||!Kr(Z.finalStat,z)||!z.isFile()||z.isSymbolicLink()||z.size!==I.size||z.mtimeMs!==I.mtimeMs||z.ctimeMs!==I.ctimeMs){P({path:A,size:z.isFile()?z.size:null,type:z.isFile()?"file":"other",reason:"changed-during-read"});return}V(n)&&await nt({path:A,hash:Z.hash,size:z.size,type:"file",...G===void 0?{}:{gitObjectId:G}},{kind:"file",target:_,realTarget:ye,stat:z})}},Oi=async(_,A,I)=>{if(!V(n))return;let G,ye,Z;try{if(G=await be.readlink(_,{encoding:"buffer"}),!V(n)||(Z=await be.lstat(_),!V(n)))return;ye=await be.readlink(_,{encoding:"buffer"})}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:null,type:"other",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(!V(n))return;if(!Z.isSymbolicLink()||!Kr(I,Z)||Z.mtimeMs!==I.mtimeMs||Z.ctimeMs!==I.ctimeMs||!G.equals(ye)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let z=G.byteLength;if(p.length>=i.maxFiles){P({path:A,size:z,type:"other",reason:"file-count"});return}if(z>i.maxFileBytes){P({path:A,size:z,type:"other",reason:"file-size"});return}if(b+z>i.maxTotalBytes){P({path:A,size:z,type:"other",reason:"total-size"});return}let _e=Hu("sha256").update("symlink\0").update(G).digest("hex");V(n)&&await nt({path:A,hash:_e,size:z,type:"file"},{kind:"symlink",target:_,rawTarget:G,stat:Z})},vi=async()=>{for(let[_,A]of[...g]){if(!V(n))return;if(A.kind==="file"){let z,_e;try{if(z=await be.realpath(A.target),!V(n))return;_e=await be.lstat(A.target)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;Pe(_,{path:_,size:null,type:"file",reason:Me(x)?"unreadable":"changed-during-read"});continue}if(!V(n))return;(z!==A.realTarget||!_e.isFile()||_e.isSymbolicLink()||!Kr(A.stat,_e)||_e.size!==A.stat.size||_e.mtimeMs!==A.stat.mtimeMs||_e.ctimeMs!==A.stat.ctimeMs)&&Pe(_,{path:_,size:_e.isFile()?_e.size:null,type:_e.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let z,_e;try{if(z=await be.lstat(A.target),!V(n))return;_e=await be.readlink(A.target,{encoding:"buffer"})}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;Pe(_,{path:_,size:null,type:"other",reason:Me(x)?"unreadable":"changed-during-read"});continue}if(!V(n))return;(!z.isSymbolicLink()||!Kr(A.stat,z)||z.mtimeMs!==A.stat.mtimeMs||z.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(_e))&&Pe(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,G;try{if(I=await be.realpath(A.target),!V(n))return;G=await be.lstat(A.target)}catch{if(!V(n))return;Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!V(n))return;if(!(I===A.realTarget&&G.isDirectory()&&!G.isSymbolicLink()&&Kr(A.stat,G)&&$(c,I)&&!Ri(u,I))){Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let Z;try{if(!V(n))return;Z=await yb(n,I)}catch(z){if(Wa(z))throw z;Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!V(n))return;Z.dirty?Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):Z.hash!==A.hash&&Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!V(n))return;try{let I=await be.lstat(A);if(!V(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!V(n))return;if(Fe(I))continue;if(!Me(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},Lt=await _b(n,e,a,t.gitSelectionHooks);if(Lt===null){let _=await gb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let G of _.records){if(G.type!=="file"&&G.type!=="symlink"||g.has(G.path))continue;if(Pi(n)<1)break;if(!bb(r,G.path,n))continue;if(Pi(n)<1)break;let ye=J.resolve(s,...G.path.split("/")),Z;try{Z=await be.lstat(ye)}catch(z){if(!V(n))break;if(!Me(z)&&!Fe(z))throw z;P({path:G.path,size:null,type:"file",reason:Fe(z)?"changed-during-read":"unreadable"});continue}if(Pi(n)<1)break;if(G.type==="symlink"&&Z.isSymbolicLink()){if(await Oi(ye,G.path,Z),Pi(n)<1)break;continue}if(G.type!=="file"||!Z.isFile()||Z.isSymbolicLink()){P({path:G.path,size:Z.isFile()?Z.size:null,type:Z.isDirectory()?"directory":Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await he(ye,G.path,Z),Pi(n)<1)break}Pi(n)>=1&&await vi();let A=await gb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o}),I=jO(_.evidence,A.evidence);N=I.evidence;for(let G of[..._.omissions,...A.omissions,...I.omissions])v.some(ye=>ye.path===G.path&&ye.reason===G.reason)||P(G)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=fr(_);for(let Re of x.entries)Re.gitObjectId!==void 0&&A.set(Re.path,Re);I=A.size>0}let G=new Set,ye=!0;try{let x=await Is(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,ye=!1,A.clear();else for(let Re of x.records){let Te=$u(Re),vt=Te.indexOf(" "),at=vt<0?null:za(Te.slice(vt+1));if(vt!==1||at===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");Te[0]!=="H"&&G.add(at)}}catch(x){if(Wa(x))throw x;I=!1,ye=!1,A.clear()}let Z=new Set;try{let x=await ju(n,s,["ls-files","--modified","-z"],Op);for(let Re of x.toString("utf8").split("\0")){let Te=za(Re);Te!==null&&Z.add(Te)}}catch{I=!1,ye=!1,A.clear()}let z=new Set,_e=new Set;for(let x of jb(Lt)){if(g.has(x)||!Ts(e,x))continue;if(Pi(n)<1)break;if(!bb(r,x,n))continue;if(Pi(n)<1)break;let Re=J.resolve(s,...x.split("/"));if(Re===f||Re===h||Ri(d,Re)||m.some(qt=>Ri(qt,Re)))continue;if(Lt.gitlinks.has(x)){if(p.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let qt,Wc;try{[qt,Wc]=await Promise.all([be.realpath(Re),be.lstat(Re)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Wc.isSymbolicLink()||!Wc.isDirectory()||!$(c,qt)||Ri(u,qt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let pa=await yb(n,qt);if(pa.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await nt({path:x,hash:pa.hash,size:0,type:"file"},{kind:"gitlink",target:Re,realTarget:qt,stat:Wc,hash:pa.hash})}catch(pa){if(Wa(pa))throw pa;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let Te;try{Te=await be.lstat(Re)}catch(qt){if(Fe(qt)&&Lt.tracked.has(x)){y.set(x,Re);continue}if(!Me(qt)&&!Fe(qt))throw qt;P({path:x,size:null,type:"file",reason:Fe(qt)?"changed-during-read":"unreadable"});continue}if(Te.isSymbolicLink()){await Oi(Re,x,Te);continue}if(!Te.isFile()){Lt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let vt=Lt.trackedObjectIds.get(x),at=vt?A.get(x):void 0;if(I&&at?.gitObjectId!==void 0&&at.gitObjectId===vt&&!G.has(x)&&!Z.has(x)){if(p.length>=i.maxFiles){P({path:x,size:at.size,type:"file",reason:"file-count"});continue}if(at.size>i.maxFileBytes){P({path:x,size:at.size,type:"file",reason:"file-size"});continue}if(b+at.size>i.maxTotalBytes){P({path:x,size:at.size,type:"file",reason:"total-size"});continue}p.push({...at}),b+=at.size,z.add(x);continue}let cg=ye&&!G.has(x)&&!Z.has(x)?vt:void 0;await he(Re,x,Te,cg),cg!==void 0&&_e.add(x)}if(await vi(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Tb(n,e,a,Lt,t.gitSelectionHooks?.outputChunkBytes),z.size>0||I&&_e.size>0){let x=await ju(n,s,["ls-files","--modified","-z"],Op),Re=new Set;for(let Te of x.toString("utf8").split("\0")){let vt=za(Te);vt!==null&&Re.add(vt)}for(let Te of z){if(!Re.has(Te))continue;let vt=p.find(at=>at.path===Te);Pe(Te,{path:Te,size:vt?.size??null,type:"file",reason:"changed-during-read"})}for(let Te of _e){if(!Re.has(Te))continue;let vt=p.find(at=>at.path===Te);vt&&delete vt.gitObjectId}}for(let x of Lt.omissions)P(x);Lt.overflow&&L(Lt.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let jC=Lt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...Lt.evidence?{gitSelection:Lt.evidence}:{}},sg=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:jC,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:v,omittedCount:E,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),lf=sg();for(;Lp(lf)>i.maxManifestBytes;){if(v.filter(A=>!Hp(A)).length>0){let A=Math.max(1,Math.ceil(v.length/4));for(let I=0;I0){let A=Math.max(1,Math.ceil(p.length/4));for(let I of p.splice(-A))E+=1,H(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");lf=sg()}return lf}async function qp(e,t,i={}){let n=(await Y(e.projectRoot))?.native.snapshot??cp;return Mu(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Vp(e,t,i){let r=Hb(e,t);await T(j(e,r),r),await ve(r,fr(i))}async function Ga(e,t){let i=Hb(e,t),r=j(e,i);await T(r,i);try{let n=await Eu({root:r,file:i,maxBytes:iO,label:"Native baseline snapshot manifest"});return fr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as g0}from"crypto";import w0 from"path";var zt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as d0}from"node:crypto";import{constants as Vu,promises as bt}from"node:fs";import Jt from"node:path";import{TextDecoder as f0}from"node:util";import s0 from"path";var KO=ma(_n(),1);import{promises as YO}from"node:fs";import XO from"node:path";var $s=".gitignore",Db=4*1024*1024,Fb="# >>> Comet managed project state >>>",Mb="# <<< Comet managed project state <<<";function QO(e){return e.includes(`\r `)?`\r `:` -`}function QO(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function ZO(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function e0(e){let t=[],i=!1;for(let r of QO(e)){let n=ZO(r);if(n===Db){if(i)throw new Error("Comet .gitignore managed block is malformed");i=!0;continue}if(n===Fb){if(!i)throw new Error("Comet .gitignore managed block is malformed");i=!1;continue}i||t.push(r)}if(i)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function Mb(e){let t=XO(e),i=e0(e);return i.length>0&&!/(?:\r\n|\n|\r)$/u.test(i)&&(i+=t),i+[Db,"!/.comet/","/.comet/*","!/.comet/config.yaml",Fb,""].join(t)}async function Wp(e){let t=YO.resolve(e),i=await sr(t,$s,{label:"project .gitignore",expected:"file"}),r="",n=new Uint8Array;i.exists&&(n=(await Mi(t,$s,Hb,{label:"project .gitignore"})).bytes,r=Buffer.from(n).toString("utf8"));let a=Mb(r);a!==r&&(await $n(i.target,a,{containedRoot:t,exclusive:!i.exists,beforeCommit:i.exists?async()=>{if(!(await Mi(t,$s,Hb,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await sr(t,$s,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}}),await sr(t,$s,{label:"project .gitignore",expected:"file"}),await KO.access(i.target))}import Nt from"path";var t0=null;function i0(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Bu(e,t){return(...i)=>{let r=t0;if(r===null)return t(...i);let n=i0(`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 r0=Bu("hookWritePolicy",async e=>(await tp(e))?.hook??{allow_paths:[]});function Bb(e,t){let i=Nt.relative(e,t);return i===""||!Nt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Nt.sep}`)}function n0(e,t){let i=Nt.isAbsolute(t)?Nt.resolve(t):Nt.resolve(e,t),r=Nt.relative(Nt.resolve(e),i);return r===""||Nt.isAbsolute(r)||r===".."||r.startsWith(`..${Nt.sep}`)?null:r.replaceAll("\\","/")}function Lb(e){return process.platform==="win32"?e.toLowerCase():e}async function Lu(e,t,i=[]){let r=Nt.isAbsolute(t)?Nt.resolve(t):Nt.resolve(e,t),n=Nt.resolve(e);if(!Bb(n,r)||i.some(c=>Bb(Nt.resolve(c),r)))return null;let a=n0(e,t);if(!a)return null;let s=(await r0(e)).allow_paths.find(c=>{let l=Lb(a),u=Lb(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var qb=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Hs(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Os(e,t){let i=Hs(e,t);if(o0.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function s0(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Vb(e){if(!e.run_id)return null;let t=Hs(e,"run_id"),i=Hs(e,"skill"),r=Hs(e,"skill_version"),n=Hs(e,"skill_hash"),a=Os(e,"pending_ref"),o=Os(e,"trajectory_ref"),s=Os(e,"context_ref"),c=Os(e,"artifacts_ref"),l=Os(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:qb(e,"current_step"),iteration:u,pending:qb(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:s0(e)}}var xJ=256*1024;var c0=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function l0(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Vb(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function qu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!c0.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return l0(t)}var ct={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Fs(e,t){let i=Jt.relative(e,t);return i===""||!Jt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Jt.sep}`)}function zb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ds(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function f0(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xr(e,t,i){let r=zt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Jt.resolve(e),a=Jt.resolve(n,...r.slice(8).split("/"));if(!Fs(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Wb(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zp(e,t){let i=Jt.resolve(e),r=Jt.resolve(t);if(!Fs(i,r))throw new Error("Native Run path is outside its change");let n=[await Wb(i)],a=i;for(let o of Jt.relative(i,r).split(Jt.sep).filter(Boolean)){a=Jt.join(a,o);let s;try{s=await Wb(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Fs(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Wu(e){for(let t of e){let i=await bt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!f0(t,i)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function h0(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 zn(e,t,i,r,n){let a=await zp(e,Jt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await bt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=zb(o),c=await bt.realpath(t);if(!Fs(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Vu.O_RDONLY:Vu.O_RDONLY|Vu.O_NOFOLLOW|Vu.O_NONBLOCK,u;try{u=await bt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await Wu(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Ds(s,d)||!Ds(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let m=await h0(u,i,r);await n?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await Wu(a),!v.isFile()||v.isSymbolicLink()||g!==c||!Ds(s,p)||!Ds(s,v))throw new Error(`${r} changed while reading`);let y;try{y=new d0("utf-8",{fatal:!0}).decode(m)}catch(E){throw new Error(`${r} is not valid UTF-8`,{cause:E})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function p0(e,t,i){let r=await zp(e,Jt.dirname(t));if(!r)return{exists:!1};let n;try{n=await bt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await bt.realpath(t);if(!Fs(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Wu(r),{exists:!0,identity:zb(n),realPath:a}}async function m0(e,t,i,r){let n=await zp(e,Jt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await bt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Ds(i.identity,a)||await bt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Wu(n)}async function zu(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await p0(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Ne(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await m0(e.changeDir,e.file,i,e.label)}});let r=await zn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Jb(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Gb(e){return`${JSON.stringify(e,null,2)} -`}function Qr(e){return qu(e)}async function Je(e,t){let i=Xr(e,"stateRef"),r=await zn(e,i,ct.runStateBytes,"Native Run state",t);return r?qu(Jb(r.text,"Native Run state")):null}async function Jn(e,t,i){let r=qu(t);await zu({changeDir:e,file:Xr(e,"stateRef"),content:Gb(r),maxBytes:ct.runStateBytes,label:"Native Run state",hooks:i})}async function kt(e,t,i){let r=Xr(e,"trajectoryRef",t),n=await zn(e,r,ct.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>ct.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ct.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Ub(e,t,i){return(await zn(e,Xr(e,"trajectoryRef",t),ct.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Kb(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=Xr(e,"trajectoryRef",t),o=await zn(e,a,ct.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(u0("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await zu({changeDir:e,file:a,content:i,maxBytes:ct.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function Yb(e,t,i,r){let n=Xr(e,"trajectoryRef",t),a=`${JSON.stringify(i)} -`;if(Buffer.byteLength(a,"utf8")>ct.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${ct.trajectoryEventBytes} bytes`);let o=await zn(e,n,ct.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=ct.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ct.trajectoryEvents} events`);await zu({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:ct.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Ua(e,t,i){let r=await zn(e,Xr(e,"checkpointRef",t),ct.checkpointBytes,"Native Run checkpoint",i);return r?Jb(r.text,"Native Run checkpoint"):null}async function Xb(e,t,i,r){await zu({changeDir:e,file:Xr(e,"checkpointRef",t),content:Gb(i),maxBytes:ct.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var w0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ju=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Jp(e){return v0("sha256").update(e).digest("hex")}function y0(e,t){if(!w0.test(t))throw new Error(`Invalid Native change name: ${t}`);return g0.join(M(e,t),"trajectory.jsonl")}function N0(e){let t=e.split(/\n/u),i=0;for(let r=0;r=Math.max(0,t.length-1)}function k0(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=N0(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(` -`)])}catch(d){if(!b0(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Jp(t),targetHash:Jp(l),tailHash:Jp(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Qb(e,t){let i=y0(e,t);await T(j(e,i),i);let r=M(e,t),n=await Ub(r,zt.trajectoryRef);return n===null?{status:"clean",file:i}:k0(i,Buffer.from(n))}async function Ka(e,t){let i=await Qb(e,t);return"inspection"in i?i.inspection:i}async function Gu(e,t){let i=await Ka(e,t);if(i.status!=="clean")throw new Ju(i)}async function Zb(e,t,i){return F(e,`repair trajectory tail for ${t}`,async()=>{let r=await Qb(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new Ju(r)}try{await Kb(M(e,t),zt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await Ka(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as S0}from"node:crypto";import{promises as Uu}from"node:fs";import hr from"node:path";var Ms=/^[a-f0-9]{64}$/u,ek=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,E0=16*1024,Up=process.platform,P0=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Ya(e){return P0.has(e)}function rk(e,t){let i=hr.relative(e,t);return hr.isAbsolute(i)||i===".."||i.startsWith(`..${hr.sep}`)?null:i.replaceAll("\\","/")||"."}function nk(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function ak(e,t){if(e.length===0||nk(e)||e.includes("\\")||hr.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=hr.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Kp(e,t){return S0("sha256").update(`${e} -${t}`).digest("hex")}async function tk(e,t){let i=await Uu.realpath(t),r=await Uu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Up==="win32"?hr.normalize(i).toLowerCase():i;return Kp(e,`${n} +`}function ZO(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function e0(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function t0(e){let t=[],i=!1;for(let r of ZO(e)){let n=e0(r);if(n===Fb){if(i)throw new Error("Comet .gitignore managed block is malformed");i=!0;continue}if(n===Mb){if(!i)throw new Error("Comet .gitignore managed block is malformed");i=!1;continue}i||t.push(r)}if(i)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function Bb(e){let t=QO(e),i=t0(e);return i.length>0&&!/(?:\r\n|\n|\r)$/u.test(i)&&(i+=t),i+[Fb,"!/.comet/","/.comet/*","!/.comet/config.yaml",Mb,""].join(t)}async function Wp(e){let t=XO.resolve(e),i=await sr(t,$s,{label:"project .gitignore",expected:"file"}),r="",n=new Uint8Array;i.exists&&(n=(await Mi(t,$s,Db,{label:"project .gitignore"})).bytes,r=Buffer.from(n).toString("utf8"));let a=Bb(r);a!==r&&(await $n(i.target,a,{containedRoot:t,exclusive:!i.exists,beforeCommit:i.exists?async()=>{if(!(await Mi(t,$s,Db,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await sr(t,$s,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}}),await sr(t,$s,{label:"project .gitignore",expected:"file"}),await YO.access(i.target))}import Nt from"path";var i0=null;function r0(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Bu(e,t){return(...i)=>{let r=i0;if(r===null)return t(...i);let n=r0(`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 n0=Bu("hookWritePolicy",async e=>(await tp(e))?.hook??{allow_paths:[]});function Lb(e,t){let i=Nt.relative(e,t);return i===""||!Nt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Nt.sep}`)}function a0(e,t){let i=Nt.isAbsolute(t)?Nt.resolve(t):Nt.resolve(e,t),r=Nt.relative(Nt.resolve(e),i);return r===""||Nt.isAbsolute(r)||r===".."||r.startsWith(`..${Nt.sep}`)?null:r.replaceAll("\\","/")}function qb(e){return process.platform==="win32"?e.toLowerCase():e}async function Lu(e,t,i=[]){let r=Nt.isAbsolute(t)?Nt.resolve(t):Nt.resolve(e,t),n=Nt.resolve(e);if(!Lb(n,r)||i.some(c=>Lb(Nt.resolve(c),r)))return null;let a=a0(e,t);if(!a)return null;let s=(await n0(e)).allow_paths.find(c=>{let l=qb(a),u=qb(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var Vb=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Hs(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Os(e,t){let i=Hs(e,t);if(s0.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function c0(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Wb(e){if(!e.run_id)return null;let t=Hs(e,"run_id"),i=Hs(e,"skill"),r=Hs(e,"skill_version"),n=Hs(e,"skill_hash"),a=Os(e,"pending_ref"),o=Os(e,"trajectory_ref"),s=Os(e,"context_ref"),c=Os(e,"artifacts_ref"),l=Os(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Vb(e,"current_step"),iteration:u,pending:Vb(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:c0(e)}}var IJ=256*1024;var l0=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function u0(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Wb(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function qu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!l0.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return u0(t)}var ct={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Fs(e,t){let i=Jt.relative(e,t);return i===""||!Jt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Jt.sep}`)}function Jb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ds(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function h0(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xr(e,t,i){let r=zt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Jt.resolve(e),a=Jt.resolve(n,...r.slice(8).split("/"));if(!Fs(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function zb(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zp(e,t){let i=Jt.resolve(e),r=Jt.resolve(t);if(!Fs(i,r))throw new Error("Native Run path is outside its change");let n=[await zb(i)],a=i;for(let o of Jt.relative(i,r).split(Jt.sep).filter(Boolean)){a=Jt.join(a,o);let s;try{s=await zb(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Fs(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Wu(e){for(let t of e){let i=await bt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!h0(t,i)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function p0(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 zn(e,t,i,r,n){let a=await zp(e,Jt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await bt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Jb(o),c=await bt.realpath(t);if(!Fs(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Vu.O_RDONLY:Vu.O_RDONLY|Vu.O_NOFOLLOW|Vu.O_NONBLOCK,u;try{u=await bt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await Wu(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Ds(s,d)||!Ds(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let m=await p0(u,i,r);await n?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await Wu(a),!v.isFile()||v.isSymbolicLink()||g!==c||!Ds(s,p)||!Ds(s,v))throw new Error(`${r} changed while reading`);let y;try{y=new f0("utf-8",{fatal:!0}).decode(m)}catch(E){throw new Error(`${r} is not valid UTF-8`,{cause:E})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function m0(e,t,i){let r=await zp(e,Jt.dirname(t));if(!r)return{exists:!1};let n;try{n=await bt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await bt.realpath(t);if(!Fs(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Wu(r),{exists:!0,identity:Jb(n),realPath:a}}async function v0(e,t,i,r){let n=await zp(e,Jt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await bt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Ds(i.identity,a)||await bt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Wu(n)}async function zu(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await m0(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Ne(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await v0(e.changeDir,e.file,i,e.label)}});let r=await zn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Gb(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Ub(e){return`${JSON.stringify(e,null,2)} +`}function Qr(e){return qu(e)}async function Je(e,t){let i=Xr(e,"stateRef"),r=await zn(e,i,ct.runStateBytes,"Native Run state",t);return r?qu(Gb(r.text,"Native Run state")):null}async function Jn(e,t,i){let r=qu(t);await zu({changeDir:e,file:Xr(e,"stateRef"),content:Ub(r),maxBytes:ct.runStateBytes,label:"Native Run state",hooks:i})}async function kt(e,t,i){let r=Xr(e,"trajectoryRef",t),n=await zn(e,r,ct.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>ct.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ct.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Kb(e,t,i){return(await zn(e,Xr(e,"trajectoryRef",t),ct.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Yb(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=Xr(e,"trajectoryRef",t),o=await zn(e,a,ct.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(d0("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await zu({changeDir:e,file:a,content:i,maxBytes:ct.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function Xb(e,t,i,r){let n=Xr(e,"trajectoryRef",t),a=`${JSON.stringify(i)} +`;if(Buffer.byteLength(a,"utf8")>ct.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${ct.trajectoryEventBytes} bytes`);let o=await zn(e,n,ct.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=ct.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ct.trajectoryEvents} events`);await zu({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:ct.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Ua(e,t,i){let r=await zn(e,Xr(e,"checkpointRef",t),ct.checkpointBytes,"Native Run checkpoint",i);return r?Gb(r.text,"Native Run checkpoint"):null}async function Qb(e,t,i,r){await zu({changeDir:e,file:Xr(e,"checkpointRef",t),content:Ub(i),maxBytes:ct.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var y0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ju=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Jp(e){return g0("sha256").update(e).digest("hex")}function N0(e,t){if(!y0.test(t))throw new Error(`Invalid Native change name: ${t}`);return w0.join(M(e,t),"trajectory.jsonl")}function b0(e){let t=e.split(/\n/u),i=0;for(let r=0;r=Math.max(0,t.length-1)}function S0(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=b0(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(` +`)])}catch(d){if(!k0(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Jp(t),targetHash:Jp(l),tailHash:Jp(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Zb(e,t){let i=N0(e,t);await T(j(e,i),i);let r=M(e,t),n=await Kb(r,zt.trajectoryRef);return n===null?{status:"clean",file:i}:S0(i,Buffer.from(n))}async function Ka(e,t){let i=await Zb(e,t);return"inspection"in i?i.inspection:i}async function Gu(e,t){let i=await Ka(e,t);if(i.status!=="clean")throw new Ju(i)}async function ek(e,t,i){return F(e,`repair trajectory tail for ${t}`,async()=>{let r=await Zb(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new Ju(r)}try{await Yb(M(e,t),zt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await Ka(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as E0}from"node:crypto";import{promises as Uu}from"node:fs";import hr from"node:path";var Ms=/^[a-f0-9]{64}$/u,tk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,P0=16*1024,Up=process.platform,R0=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Ya(e){return R0.has(e)}function nk(e,t){let i=hr.relative(e,t);return hr.isAbsolute(i)||i===".."||i.startsWith(`..${hr.sep}`)?null:i.replaceAll("\\","/")||"."}function ak(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function ok(e,t){if(e.length===0||ak(e)||e.includes("\\")||hr.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=hr.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Kp(e,t){return E0("sha256").update(`${e} +${t}`).digest("hex")}async function ik(e,t){let i=await Uu.realpath(t),r=await Uu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Up==="win32"?hr.normalize(i).toLowerCase():i;return Kp(e,`${n} ${r.dev} ${r.ino} -${r.birthtimeMs}`)}async function ik(e,t){let i=await Uu.realpath(t),r=await Uu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Up==="win32"?hr.normalize(i).toLowerCase():i;return Kp(e,n)}function R0(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 Gp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||nk(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function ok(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Gp(e.changeBranch,"Native workspace change branch"),Gp(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 C0(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"||!ek.test(t.baseCommit)||typeof t.targetCommit!="string"||!ek.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Gp(t.targetBranch,"Native workspace Git target branch")}function Bs(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"||!Ms.test(String(t.projectRootId))||!Ms.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");R0(t.capturedAt),ak(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&&!Ms.test(String(t.projectRootPathId))||a&&!Ms.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ms.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&C0(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(ok(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 Xa(e,t){return hr.join(M(e,t),"workspace.json")}function x0(e,t){let i=Xa(e,t),r=j(e,i),n=rk(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:ak(n,"Native workspace file ref")}}async function sk(e,t){try{let i=x0(e,t),r=await ee({root:i.root,ref:i.ref,maxBytes:E0});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ku(e,t){let i=me(e.projectRoot),r={projectRoot:hr.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await lt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await Gi({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Yp(e,t){let i=await sk(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Bs(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function ck(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=rk(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=me(e.paths.projectRoot),r=i.isGitWorktree?uf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:uf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([tk("comet.native.workspace-project-root.v2",e.paths.projectRoot),tk("comet.native.workspace-native-root.v2",e.paths.nativeRoot),ik("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),ik("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&ok(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Kp("comet.native.workspace-session.v2",`${s} +${r.birthtimeMs}`)}async function rk(e,t){let i=await Uu.realpath(t),r=await Uu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Up==="win32"?hr.normalize(i).toLowerCase():i;return Kp(e,n)}function C0(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 Gp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ak(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function sk(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Gp(e.changeBranch,"Native workspace change branch"),Gp(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 x0(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"||!tk.test(t.baseCommit)||typeof t.targetCommit!="string"||!tk.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Gp(t.targetBranch,"Native workspace Git target branch")}function Bs(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"||!Ms.test(String(t.projectRootId))||!Ms.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");C0(t.capturedAt),ok(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&&!Ms.test(String(t.projectRootPathId))||a&&!Ms.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ms.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&x0(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(sk(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 Xa(e,t){return hr.join(M(e,t),"workspace.json")}function A0(e,t){let i=Xa(e,t),r=j(e,i),n=nk(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:ok(n,"Native workspace file ref")}}async function ck(e,t){try{let i=A0(e,t),r=await ee({root:i.root,ref:i.ref,maxBytes:P0});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ku(e,t){let i=me(e.projectRoot),r={projectRoot:hr.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await lt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await Gi({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Yp(e,t){let i=await ck(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Bs(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function lk(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=nk(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=me(e.paths.projectRoot),r=i.isGitWorktree?uf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:uf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([ik("comet.native.workspace-project-root.v2",e.paths.projectRoot),ik("comet.native.workspace-native-root.v2",e.paths.nativeRoot),rk("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),rk("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&sk(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Kp("comet.native.workspace-session.v2",`${s} ${c} -${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Bs(h),h}async function Yu(e){let t=await ck(e),i=Xa(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ve(i,t,{containedRoot:r}),t}async function lt(e,t){let i=await sk(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Bs(i),i)}async function lk(e){return await Yp(e.paths,e.name)?Yu(e):null}async function Zr(e){Bs(e.identity);let t=await ck({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Up==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function Gi(e){if(Bs(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Zr(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=me(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function uk(e,t){let i=await lt(e,t);if(i===null)return null;let r=await Gi({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var hk=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],A0=new Set(hk),pk=new Set([...hk,"minimum_runtime_version","revision"]),_0=new Set([...pk,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),T0=new Set(["capability","operation","source","base_hash"]),I0=new Set(["shape","build","verify","archive"]),j0=new Set(["implicit","confirmed"]),$0=new Set(["pending","pass","fail"]),Ve="comet-state.yaml",Qp=/^[a-f0-9]{64}$/u,mk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,O0=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,qs=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"},pr=class extends Error{constructor(i,r){super(i!==$e||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"},Vs=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"},Qa=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"},Za=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"},bG=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function zs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function vk(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 Un(e){if(!mk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function H0(e){if(!mk.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function gk(e,t){if(e.length===0||ut.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function D0(e,t){let i=zs(e,`spec_changes[${t}]`);if(vk(i,T0,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(H0(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"&&gk(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"||!Qp.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"||!Qp.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 F0(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 Zp(e,t){if(vk(e,t,Ve),typeof e.name!="string")throw new Error("Native change name is required");if(Un(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"||!I0.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&&!j0.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(D0),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"||!$0.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"&&gk(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!F0(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 qn(e){let t=zs(e,Ve);if(t.schema!==yt)throw new Error(`Expected ${yt}`);return{schema:yt,...Zp(t,A0)}}function Ws(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xp(e,t,i){if(e===null)return null;let r=typeof e=="string"?O0.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function M0(e){if(e==null)return null;if(typeof e!="string"||!Qp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function B0(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 Vi(e){let t=zs(e,Ve);if(t.schema!==Oe)throw new Error(`Expected ${Oe}`);if(Ws(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Oe} minimum_runtime_version must be 2`);return{schema:Oe,minimum_runtime_version:2,revision:Ws(t.revision,"Native v2 revision"),...Zp(t,pk)}}function jt(e){let t=zs(e,Ve);if(t.schema!==$e){if(t.schema===yt||t.schema===Oe){let o=t.schema===yt?qn(t):Vi(t);throw new qs(o.name,o.schema)}throw new pr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Ws(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new pr(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Ws(t.revision,"Native revision"),n=Zp(t,_0),a=M0(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:$e,minimum_runtime_version:3,revision:r,verification_protocol:B0(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xp(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xp(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xp(t.partial_allowance,"Native partial_allowance","allowances")}}function wk(e){let t=zs(e,Ve);if(t.schema===yt){let n=qn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema===Oe){let n=Vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema!==$e){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 pr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Ws(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new pr(t.schema,i).message};let r=jt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Gn(e){let t=jt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Qu(e){let t=Vi(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function te(e,t){Un(t);let i=ut.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function eo(e,t){let i=M(e,t),r=ut.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ls.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function to(e,t){let i=M(e,t),r=ut.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ls.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var L0=256*1024;async function Zu(e,t=ut.dirname(e)){let i=ut.relative(t,e).split(ut.sep).join("/"),r=await ee({root:t,ref:i,maxBytes:L0}),n=(0,Xu.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 li(e,t){let i=ut.join(te(e,t),Ve);await T(e.nativeRoot,i);let r=wk(await Zu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await eo(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await q0(e,r.state),r)}async function Kn(e,t){let i=ut.join(te(e,t),Ve);await T(e.nativeRoot,i);let r=wk(await Zu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function q0(e,t){if(await Ga(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function je(e,t){let i=await li(e,t);if(i.status==="migration-required")throw new qs(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new pr(i.schema,i.minimumRuntimeVersion);return await uk(e,t),i.state}async function yk(e,t,i){let r={...t,schema:$e,minimum_runtime_version:3,revision:i+1},n=await hb({expectedRevision:i,next:r,read:async()=>{let a=jt(await Zu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Ne(e,(0,Xu.stringify)(Gn(a))),equals:(a,o)=>JSON.stringify(Gn(a))===JSON.stringify(Gn(o)),conflict:a=>new Vs(t.name,i,a)});return Object.assign(t,n),n}async function Js(e,t,i,r){if(await Ia(e.projectRoot),await eo(e,t.name))throw new qs(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await to(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await je(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Gu(e,t.name);let a=ut.join(te(e,t.name),Ve);return await T(e.nativeRoot,a),yk(a,t,i)}async function Nk(e,t){return yk(e,t,t.revision)}async function bk(e){return jt(await Zu(e))}async function V0(e){let t;try{let r=await $t({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await r.verify(),t=r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort()}async function kk(e){let t=[];for(let i of await V0(e)){let r=await Kn(e,i);if(!r.state){if(await fk(e,i))continue;t.push(i);continue}if(r.state.archived)continue;let n=await lt(e,i);if(!(!n&&await fk(e,i))){if(n?.schema==="comet.native.workspace.v3"){if((await Gi({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Zr({paths:e,identity:n})).state==="drifted")continue;t.push(i)}}return t}function dk(e,t){let i=ut.resolve(e),r=ut.resolve(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function fk(e,t){for(let i of Zt(e.projectRoot))if(!dk(i,e.projectRoot))try{let r=await Y(i);if(!r)continue;let n=await re(i,r.native.artifact_root),a=ut.join(n.changesDir,t),o=ut.join(a,"comet-state.yaml");try{let l=await Ls.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ls.readFile(ut.join(ze(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&dk(d.workspace.projectRoot,i))return!0;continue}}catch(l){l.code}await Ls.access(ut.join(a,Ve));let s=await lt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Gi({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Zr({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}import{randomUUID as hd}from"node:crypto";import{promises as di}from"node:fs";import He from"node:path";var am=ma(_n(),1);import{promises as _k}from"node:fs";import ui from"node:path";import{execFileSync as W0}from"node:child_process";var z0=3e4,J0=8*1024*1024,em=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 Sk(e,t){try{return W0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:z0,maxBuffer:J0,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new em(e,t,r)}}function he(e,t){return Sk(e,t).trim()}function Gs(e){return he(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function tm(e,t){he(e,["check-ref-format","--branch",t])}function im(e){let t=Sk(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;nr.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 Pk="children.yaml",rm="comet.native.children.v1",G0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,U0=new Set(["schema","children"]),K0=new Set(["name","depends_on","covers"]);function Rk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ck(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 xk(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 nm(e,t){let i=ui.normalize(ui.resolve(e)),r=ui.normalize(ui.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Y0(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 X0(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function Q0(e,t){let i=(0,am.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Rk(i.toJS({mapAsMap:!1}),"Native children contract");if(Ck(r,U0,"Native children contract"),r.schema!==rm)throw new Error(`Native children schema must be ${rm}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Rk(s,`Native child ${c}`);if(Ck(l,K0,`Native child ${c}`),typeof l.name!="string"||!G0.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:xk(l.depends_on,`Native child ${l.name} depends_on`),covers:xk(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return Y0(n),t&&X0(n,t),{schema:rm,children:n}}async function Us(e){let t=ui.join(e.changeDir,Pk);try{await _k.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await ee({root:e.changeDir,ref:Pk});return{contract:Q0(i.text,e.acceptanceIds),size:i.size}}function ed(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function Z0(e){let t=Zt(e.projectRoot);t.some(r=>nm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>ui.resolve(n)))]){let n=await Y(r);n&&i.push({projectRoot:r,paths:await re(r,n.native.artifact_root),parent:nm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function eH(e,t){let i=ui.join(e.paths.changesDir,t,"comet-state.yaml");try{return await wt(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function tH(e,t){let i;try{i=await _k.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=ui.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await wt(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function iH(e,t,i){let r=ui.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${ui.sep}`))return null;let n=r.split(ui.sep).join("/");try{let a=(0,am.parseDocument)(he(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:X(a.toJS({mapAsMap:!1}))}catch{return null}}function rH(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Ak(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Gt(e){let t=ui.join(e.paths.changesDir,e.state.name),i=await Us({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=ed({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await Z0(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:p})=>p)),c=new Map,l=new Map;for(let p of a){let v=p.parent&&o?`refs/heads/${o}`:"HEAD";for(let g of await tH(p,s)){let y={...g,source:p,committedState:iH(p,g.file,v)};c.set(g.state.name,[...c.get(g.state.name)??[],y])}for(let g of s){let y=await eH(p,g);y&&l.set(g,[...l.get(g)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let v=(c.get(p.name)??[]).find(({source:E,committedState:S})=>E.parent&&S?.name===p.name&&Ak(S,o));if(v){u.set(p.name,{kind:"done",phase:v.state.phase,projectRoot:v.source.projectRoot,message:null});continue}let g=c.get(p.name)?.[0];if(g){u.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=l.get(p.name)??[];y.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&u.set(p.name,rH(y[0].state,y[0].source,o))}let d=new Map(i.contract.children.map(p=>[p.name,p])),f=new Map,h=p=>{let v=f.get(p);if(v)return v;let g=d.get(p),E=g.depends_on.map(h).every(({status:w})=>w==="done"),S=u.get(p),k=S?.kind==="active"&&E?g.depends_on.filter(w=>!(c.get(w)??[]).some(({source:P,committedState:L})=>nm(P.projectRoot,S.projectRoot)&&L?.name===w&&Ak(L,o))):[],b,R=S?.message??null;S?.kind==="done"?(b=E?"done":"blocked",E||(R=`Native child ${p} was merged before its dependencies`)):S?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(R=`Native child ${p} does not include merged dependencies: ${k.join(", ")}`):R=`Native child ${p} started before its dependencies merged`):S?.kind==="blocked"?b="blocked":(b=n&&E?"ready":"pending",n||(R="Parent Shape confirmation is required"));let N={name:p,dependsOn:[...g.depends_on],covers:[...g.covers],status:b,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:R};return f.set(p,N),N},m=i.contract.children.map(({name:p})=>h(p));return{contractHash:r,confirmed:n,parentBranch:o,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}import{createWriteStream as EH,promises as PH}from"node:fs";import Ut from"node:path";import{spawn as om}from"node:child_process";import{existsSync as Tk}from"node:fs";import Yn from"node:path";var nH=new Set([".bat",".cmd",".ps1"]),aH=new Set([".bat",".cmd"]),oH=/[&|<>()^%"!\r\n]/u,sH=["$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("; ");function sm(e,t){let i=t.toLowerCase();return Object.entries(e).find(([r,n])=>r.toLowerCase()===i&&n!==void 0)?.[1]}function cH(e){let t=(sm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function lH(e,t,i){let n=Yn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(sm(t,"PATH")??"").split(Yn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Yn.win32.extname(e)?[e]:cH(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Yn.join(s,c):Yn.resolve(i,c)))}function uH(e,t,i){return lH(e,t,i).find(r=>Tk(r))??e}function dH(e){let t=sm(e,"SystemRoot");if(t){let i=Yn.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Tk(i))return i}return"powershell.exe"}function fH(e){if(e.some(t=>oH.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function hH(e,t,i){let r=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(sH,"utf16le").toString("base64");return om(dH(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:i.cwd,env:{...i.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function cm(e,t,i){let r=i.env??process.env;if(process.platform!=="win32")return om(e,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=uH(e,r,i.cwd),a=Yn.win32.extname(n).toLowerCase();return aH.has(a)&&fH(t),nH.has(a)?hH(n,t,{cwd:i.cwd,env:r}):om(n,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as pH}from"node:child_process";import lm from"node:path";var mH=1e3,vH=2;async function td(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,r=i&&lm.win32.isAbsolute(i)?lm.win32.resolve(i):"C:\\Windows",n=lm.win32.join(r,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=pH(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),mH)}catch{u(!1)}});for(let o=0;o{if(t)return t=!1,"[REDACTED]";let r=St(i);return RH.test(i)&&(t=!0),r})}function rd(e,t){if(jk(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return id(e,t.cwdRef)}async function dm(e){let{plan:t}=e;jk(e.operationId,"Native check operation ID");let i=rd(e.projectRoot,t),r=Ut.join(e.runtimeDir,"logs","checks"),n=Ut.join(r,`${e.operationId}-${t.id}.log`);if(!Ik(Ut.resolve(e.runtimeDir),Ut.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await PH.mkdir(r,{recursive:!0});let a=(e.now??(()=>new Date))(),o=EH(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=cm(t.executable,t.argv,{cwd:i,env:process.env})}catch(h){o.destroy(),c(h);return}let u=!1,d=null,f=setTimeout(()=>{u=!0,td(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);f.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",h=>{d=h,o.write(` +${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Bs(h),h}async function Yu(e){let t=await lk(e),i=Xa(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ve(i,t,{containedRoot:r}),t}async function lt(e,t){let i=await ck(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Bs(i),i)}async function uk(e){return await Yp(e.paths,e.name)?Yu(e):null}async function Zr(e){Bs(e.identity);let t=await lk({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Up==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function Gi(e){if(Bs(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Zr(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=me(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function dk(e,t){let i=await lt(e,t);if(i===null)return null;let r=await Gi({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var pk=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],_0=new Set(pk),mk=new Set([...pk,"minimum_runtime_version","revision"]),T0=new Set([...mk,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),I0=new Set(["capability","operation","source","base_hash"]),j0=new Set(["shape","build","verify","archive"]),$0=new Set(["implicit","confirmed"]),O0=new Set(["pending","pass","fail"]),Ve="comet-state.yaml",Qp=/^[a-f0-9]{64}$/u,vk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,H0=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,qs=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"},pr=class extends Error{constructor(i,r){super(i!==$e||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"},Vs=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"},Qa=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"},Za=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"},PG=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function zs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function gk(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 Un(e){if(!vk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function D0(e){if(!vk.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function wk(e,t){if(e.length===0||ut.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function F0(e,t){let i=zs(e,`spec_changes[${t}]`);if(gk(i,I0,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(D0(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"&&wk(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"||!Qp.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"||!Qp.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 M0(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 Zp(e,t){if(gk(e,t,Ve),typeof e.name!="string")throw new Error("Native change name is required");if(Un(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"||!j0.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&&!$0.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(F0),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"||!O0.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"&&wk(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!M0(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 qn(e){let t=zs(e,Ve);if(t.schema!==yt)throw new Error(`Expected ${yt}`);return{schema:yt,...Zp(t,_0)}}function Ws(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xp(e,t,i){if(e===null)return null;let r=typeof e=="string"?H0.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/.json relative to the Native change`);return e}function B0(e){if(e==null)return null;if(typeof e!="string"||!Qp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function L0(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 Vi(e){let t=zs(e,Ve);if(t.schema!==Oe)throw new Error(`Expected ${Oe}`);if(Ws(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Oe} minimum_runtime_version must be 2`);return{schema:Oe,minimum_runtime_version:2,revision:Ws(t.revision,"Native v2 revision"),...Zp(t,mk)}}function jt(e){let t=zs(e,Ve);if(t.schema!==$e){if(t.schema===yt||t.schema===Oe){let o=t.schema===yt?qn(t):Vi(t);throw new qs(o.name,o.schema)}throw new pr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Ws(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new pr(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Ws(t.revision,"Native revision"),n=Zp(t,T0),a=B0(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:$e,minimum_runtime_version:3,revision:r,verification_protocol:L0(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xp(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xp(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xp(t.partial_allowance,"Native partial_allowance","allowances")}}function yk(e){let t=zs(e,Ve);if(t.schema===yt){let n=qn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema===Oe){let n=Vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema!==$e){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 pr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Ws(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new pr(t.schema,i).message};let r=jt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Gn(e){let t=jt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Qu(e){let t=Vi(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function te(e,t){Un(t);let i=ut.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function eo(e,t){let i=M(e,t),r=ut.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ls.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function to(e,t){let i=M(e,t),r=ut.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ls.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var q0=256*1024;async function Zu(e,t=ut.dirname(e)){let i=ut.relative(t,e).split(ut.sep).join("/"),r=await ee({root:t,ref:i,maxBytes:q0}),n=(0,Xu.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 li(e,t){let i=ut.join(te(e,t),Ve);await T(e.nativeRoot,i);let r=yk(await Zu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await eo(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await V0(e,r.state),r)}async function Kn(e,t){let i=ut.join(te(e,t),Ve);await T(e.nativeRoot,i);let r=yk(await Zu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function V0(e,t){if(await Ga(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function je(e,t){let i=await li(e,t);if(i.status==="migration-required")throw new qs(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new pr(i.schema,i.minimumRuntimeVersion);return await dk(e,t),i.state}async function Nk(e,t,i){let r={...t,schema:$e,minimum_runtime_version:3,revision:i+1},n=await pb({expectedRevision:i,next:r,read:async()=>{let a=jt(await Zu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Ne(e,(0,Xu.stringify)(Gn(a))),equals:(a,o)=>JSON.stringify(Gn(a))===JSON.stringify(Gn(o)),conflict:a=>new Vs(t.name,i,a)});return Object.assign(t,n),n}async function Js(e,t,i,r){if(await Ia(e.projectRoot),await eo(e,t.name))throw new qs(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await to(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await je(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Gu(e,t.name);let a=ut.join(te(e,t.name),Ve);return await T(e.nativeRoot,a),Nk(a,t,i)}async function bk(e,t){return Nk(e,t,t.revision)}async function kk(e){return jt(await Zu(e))}async function W0(e){let t;try{let r=await $t({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await r.verify(),t=r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort()}async function Sk(e){let t=[];for(let i of await W0(e)){let r=await Kn(e,i);if(!r.state){if(await hk(e,i))continue;t.push(i);continue}if(r.state.archived)continue;let n=await lt(e,i);if(!(!n&&await hk(e,i))){if(n?.schema==="comet.native.workspace.v3"){if((await Gi({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Zr({paths:e,identity:n})).state==="drifted")continue;t.push(i)}}return t}function fk(e,t){let i=ut.resolve(e),r=ut.resolve(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function hk(e,t){for(let i of Zt(e.projectRoot))if(!fk(i,e.projectRoot))try{let r=await Y(i);if(!r)continue;let n=await re(i,r.native.artifact_root),a=ut.join(n.changesDir,t),o=ut.join(a,"comet-state.yaml");try{let l=await Ls.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ls.readFile(ut.join(ze(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&fk(d.workspace.projectRoot,i))return!0;continue}}catch(l){l.code}await Ls.access(ut.join(a,Ve));let s=await lt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Gi({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Zr({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}import{randomUUID as hd}from"node:crypto";import{promises as di}from"node:fs";import He from"node:path";var am=ma(_n(),1);import{promises as Tk}from"node:fs";import ui from"node:path";import{execFileSync as z0}from"node:child_process";var J0=3e4,G0=8*1024*1024,em=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 Ek(e,t){try{return z0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:J0,maxBuffer:G0,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new em(e,t,r)}}function le(e,t){return Ek(e,t).trim()}function Gs(e){return le(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function tm(e,t){le(e,["check-ref-format","--branch",t])}function im(e){let t=Ek(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;nr.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 Rk="children.yaml",rm="comet.native.children.v1",U0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,K0=new Set(["schema","children"]),Y0=new Set(["name","depends_on","covers"]);function Ck(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xk(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 Ak(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 nm(e,t){let i=ui.normalize(ui.resolve(e)),r=ui.normalize(ui.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function X0(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 Q0(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function Z0(e,t){let i=(0,am.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Ck(i.toJS({mapAsMap:!1}),"Native children contract");if(xk(r,K0,"Native children contract"),r.schema!==rm)throw new Error(`Native children schema must be ${rm}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Ck(s,`Native child ${c}`);if(xk(l,Y0,`Native child ${c}`),typeof l.name!="string"||!U0.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:Ak(l.depends_on,`Native child ${l.name} depends_on`),covers:Ak(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return X0(n),t&&Q0(n,t),{schema:rm,children:n}}async function Us(e){let t=ui.join(e.changeDir,Rk);try{await Tk.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await ee({root:e.changeDir,ref:Rk});return{contract:Z0(i.text,e.acceptanceIds),size:i.size}}function ed(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function eH(e){let t=Zt(e.projectRoot);t.some(r=>nm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>ui.resolve(n)))]){let n=await Y(r);n&&i.push({projectRoot:r,paths:await re(r,n.native.artifact_root),parent:nm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function tH(e,t){let i=ui.join(e.paths.changesDir,t,"comet-state.yaml");try{return await wt(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function iH(e,t){let i;try{i=await Tk.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=ui.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await wt(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function rH(e,t,i){let r=ui.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${ui.sep}`))return null;let n=r.split(ui.sep).join("/");try{let a=(0,am.parseDocument)(le(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:X(a.toJS({mapAsMap:!1}))}catch{return null}}function nH(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function _k(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Gt(e){let t=ui.join(e.paths.changesDir,e.state.name),i=await Us({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=ed({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await eH(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:p})=>p)),c=new Map,l=new Map;for(let p of a){let v=p.parent&&o?`refs/heads/${o}`:"HEAD";for(let g of await iH(p,s)){let y={...g,source:p,committedState:rH(p,g.file,v)};c.set(g.state.name,[...c.get(g.state.name)??[],y])}for(let g of s){let y=await tH(p,g);y&&l.set(g,[...l.get(g)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let v=(c.get(p.name)??[]).find(({source:E,committedState:S})=>E.parent&&S?.name===p.name&&_k(S,o));if(v){u.set(p.name,{kind:"done",phase:v.state.phase,projectRoot:v.source.projectRoot,message:null});continue}let g=c.get(p.name)?.[0];if(g){u.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=l.get(p.name)??[];y.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&u.set(p.name,nH(y[0].state,y[0].source,o))}let d=new Map(i.contract.children.map(p=>[p.name,p])),f=new Map,h=p=>{let v=f.get(p);if(v)return v;let g=d.get(p),E=g.depends_on.map(h).every(({status:w})=>w==="done"),S=u.get(p),k=S?.kind==="active"&&E?g.depends_on.filter(w=>!(c.get(w)??[]).some(({source:P,committedState:L})=>nm(P.projectRoot,S.projectRoot)&&L?.name===w&&_k(L,o))):[],b,R=S?.message??null;S?.kind==="done"?(b=E?"done":"blocked",E||(R=`Native child ${p} was merged before its dependencies`)):S?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(R=`Native child ${p} does not include merged dependencies: ${k.join(", ")}`):R=`Native child ${p} started before its dependencies merged`):S?.kind==="blocked"?b="blocked":(b=n&&E?"ready":"pending",n||(R="Parent Shape confirmation is required"));let N={name:p,dependsOn:[...g.depends_on],covers:[...g.covers],status:b,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:R};return f.set(p,N),N},m=i.contract.children.map(({name:p})=>h(p));return{contractHash:r,confirmed:n,parentBranch:o,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}import{createWriteStream as PH,promises as RH}from"node:fs";import Ut from"node:path";import{spawn as om}from"node:child_process";import{existsSync as Ik}from"node:fs";import Yn from"node:path";var aH=new Set([".bat",".cmd",".ps1"]),oH=new Set([".bat",".cmd"]),sH=/[&|<>()^%"!\r\n]/u,cH=["$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("; ");function sm(e,t){let i=t.toLowerCase();return Object.entries(e).find(([r,n])=>r.toLowerCase()===i&&n!==void 0)?.[1]}function lH(e){let t=(sm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function uH(e,t,i){let n=Yn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(sm(t,"PATH")??"").split(Yn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Yn.win32.extname(e)?[e]:lH(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Yn.join(s,c):Yn.resolve(i,c)))}function dH(e,t,i){return uH(e,t,i).find(r=>Ik(r))??e}function fH(e){let t=sm(e,"SystemRoot");if(t){let i=Yn.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Ik(i))return i}return"powershell.exe"}function hH(e){if(e.some(t=>sH.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function pH(e,t,i){let r=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(cH,"utf16le").toString("base64");return om(fH(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:i.cwd,env:{...i.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function cm(e,t,i){let r=i.env??process.env;if(process.platform!=="win32")return om(e,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=dH(e,r,i.cwd),a=Yn.win32.extname(n).toLowerCase();return oH.has(a)&&hH(t),aH.has(a)?pH(n,t,{cwd:i.cwd,env:r}):om(n,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as mH}from"node:child_process";import lm from"node:path";var vH=1e3,gH=2;async function td(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,r=i&&lm.win32.isAbsolute(i)?lm.win32.resolve(i):"C:\\Windows",n=lm.win32.join(r,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=mH(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),vH)}catch{u(!1)}});for(let o=0;o{if(t)return t=!1,"[REDACTED]";let r=St(i);return CH.test(i)&&(t=!0),r})}function rd(e,t){if($k(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return id(e,t.cwdRef)}async function dm(e){let{plan:t}=e;$k(e.operationId,"Native check operation ID");let i=rd(e.projectRoot,t),r=Ut.join(e.runtimeDir,"logs","checks"),n=Ut.join(r,`${e.operationId}-${t.id}.log`);if(!jk(Ut.resolve(e.runtimeDir),Ut.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await RH.mkdir(r,{recursive:!0});let a=(e.now??(()=>new Date))(),o=PH(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=cm(t.executable,t.argv,{cwd:i,env:process.env})}catch(h){o.destroy(),c(h);return}let u=!1,d=null,f=setTimeout(()=>{u=!0,td(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);f.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",h=>{d=h,o.write(` [comet] failed to start check: ${St(h.message)} -`)}),l.once("close",(h,m)=>{clearTimeout(f);let p=(e.now??(()=>new Date))();o.end(()=>{let v=u||d!==null||m!==null;s({id:t.id,name:t.name,argvDisplay:um(t.argv),cwdRef:t.cwdRef,status:v?"interrupted":h===0?"passed":"failed",exitCode:h,signal:m,timedOut:u,durationMs:Math.max(0,p.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:p.toISOString(),repeatable:t.repeatable,logRef:Ut.relative(e.runtimeDir,n).split(Ut.sep).join("/")})})}),o.once("error",h=>{clearTimeout(f),td(l).catch(()=>l.kill("SIGKILL")),c(h)})})}import{randomUUID as _H}from"node:crypto";var $k=Symbol("comet.native.trusted-execution-identity"),Ok=Symbol("comet.native.trusted-verifier-envelope"),Ge="skill-coordinated";function fm(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Ys(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){fm(t.identityProvider,"Native identity provider");let i=Object.freeze({identityProvider:Ge,executionRef:fm(t.executionRef,"Native execution ref"),[$k]:!0});return e.add(i),i},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:fm(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Ok]:!0})}})}function nd(e){return typeof e=="object"&&e!==null&&e[Ok]===!0}function Hk(e){return typeof e=="object"&&e!==null&&e[$k]===!0}function ad(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xs(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Qs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Xn(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function CH(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,i)=>{let r=ad(t,`Native Verifier acceptance ${i}`);Xs(r,["id","result","reason"],`Native Verifier acceptance ${i}`);let n=Xn(r.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(r.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:r.result,reason:Xn(r.reason,`Native Verifier acceptance ${n} reason`)}})}function xH(e){let t=ad(e,"Native Verifier final result");if(Xs(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Qs(t.iteration,"Native Verifier iteration"),attempt:Qs(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:CH(t.acceptance),risks:t.risks,summary:Xn(t.summary,"Native Verifier summary")}}function AH(e,t){let i=ad(e,`Native Verifier check request ${t}`);if(Xs(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let r=Qs(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(r<1)throw new Error("Native Verifier check timeout must be positive");return{id:Xn(i.id,`Native Verifier check request ${t} ID`),name:Xn(i.name,`Native Verifier check request ${t} name`),executable:Xn(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:Xn(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:r,repeatable:i.repeatable}}function hm(e){let t=ad(e,"Native Verifier response");if(t.kind==="final-result")return Xs(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:xH(t.result)};if(t.kind==="request-checks"){if(Xs(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Qs(t.iteration,"Native Verifier iteration"),attempt:Qs(t.attempt,"Native Verifier attempt"),checks:t.checks.map(AH)}}throw new Error("Native Verifier response kind is invalid")}function Dk(e){if(!nd(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:i}=e;if(t.candidateId!==i.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==i.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===i.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let r=hm(t.payload),n=r.kind==="final-result"?r.result.iteration:r.iteration,a=r.kind==="final-result"?r.result.attempt:r.attempt;if(n!==i.iteration||a!==i.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(r.kind==="request-checks")return r;let o=[...i.acceptanceIds],s=r.result.acceptance.map(({id:f})=>f),c=s.filter((f,h)=>s.indexOf(f)!==h),l=s.filter(f=>!o.includes(f)),u=o.filter(f=>!s.includes(f));if(c.length>0||l.length>0||u.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${u.join(", ")||"none"})`);if(!i.requiredChecksPassed&&r.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=r.result.acceptance.map(({result:f})=>f);if(r.result.verdict==="pass"&&d.some(f=>f!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(r.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(r.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return r}var Zs=3,pm=2;function Kt(e){return e.state_version+1}function TH(e,t,i){let r=[...e];if(new Set(r).size!==r.length)throw new Error(`${i} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${i} contains unknown IDs: ${a.join(", ")}`);return r}function mm(e){return e.map(t=>({...t,result:"pending",reason:null}))}function IH(e){return(e??[]).map(t=>({name:ue(t.name),result:t.result,note:t.note?ue(t.note):null}))}function Qn(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:ue(e.summary),completed_at:e.completedAt}}function Fk(e){let t=X(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let i=e.acceptance.map(({id:r})=>r);if(new Set(i).size!==i.length)throw new Error("Native acceptance IDs must be unique");return X({...t,phase:"build",state_version:Kt(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(r=>({...r,result:"pending",reason:null}))})}function vm(e){let t=X(e.state),{input:i}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Hk(i.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");let r=TH(i.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=(i.now??new Date).toISOString();return X({...t,phase:"verify",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:mm(t.acceptance),builder_handoff:{candidate_id:i.candidateId??_H(),identity_provider:i.identity.identityProvider,builder_execution_ref:i.identity.executionRef,iteration:t.loop.iteration,summary:ue(i.summary),addressed_acceptance_ids:r,checks:IH(i.checks),checks_truncated:!1,known_limits:(i.knownLimits??[]).map(a=>ue(a)),known_limits_truncated:!1,submitted_at:n},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Mk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt is not ready to dispatch");return X({...t,state_version:Kt(t),loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function jH(e,t){let i=e.loop.previous_unresolved_ids;if(i.length===0)return 0;let r=new Set(i),n=new Set(t);return n.sizer.has(o))?0:e.loop.no_progress_count+1}function $H(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Ge?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:ue(e.response.result.summary),risks:e.response.result.risks.map(t=>ue(t)),risks_truncated:!1,completed_at:e.completedAt}}function Bk(e){let t=X(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let i=Dk({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:t.acceptance.map(({id:m})=>m),requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let r=(e.now??new Date).toISOString(),n=new Map(i.result.acceptance.map(m=>[m.id,m])),a=t.acceptance.map(m=>{let p=n.get(m.id);return{...m,result:p.result,reason:ue(p.reason)}}),o=a.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),s=$H({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:r});if(i.result.verdict==="pass"){let m=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"pass",summary:i.result.summary,completedAt:r})),p=t.builder_handoff.identity_provider===Ge;return{response:i,state:X({...m,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:Kt(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:ue("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"blocked",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...m,status:"await-user",state_version:Kt(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:ue(i.result.summary),acceptance_ids:o,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:o,next_action:"resolve-verifier-blocker"}})}}let c=t.loop.failed_iteration_count+1,l=jH(t,o),u=c>=e.maxVerifyFailures,d=l>=3,f=u||d,h=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"fail",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...h,phase:f?"verify":"build",status:f?"await-user":"active",state_version:Kt(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:f?[{owner:"user",reason:ue(u?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:o,resolution_action:"await-user"}]:l>=2?[{owner:"builder",reason:ue("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:o,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:f?"await-user":"repairing",iteration:f?t.loop.iteration:t.loop.iteration+1,attempt:f?t.loop.attempt:0,failed_iteration_count:c,no_progress_count:l,execution_failure_count:0,previous_unresolved_ids:o,next_action:f?"await-user":"repair-failed-acceptance"}})}}function Lk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Ge||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return X({...t,phase:"archive",status:"active",state_version:Kt(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function qk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Ge||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let i=(e.now??new Date).toISOString(),r=t.acceptance.map(({id:a})=>a),n=ri(t,Qn({state:t,outcome:"blocked",unresolvedIds:r,summary:e.summary,completedAt:i}));return X({...n,status:"await-user",state_version:Kt(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:ue(e.summary),risks:[ue("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:i},blockers:[{owner:"user",reason:ue("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:r,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:r,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Vk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let i=(e.now??new Date).toISOString(),r=ue(e.summary),n=ri(t,Qn({state:t,outcome:"pass",summary:e.summary,completedAt:i}));return X({...n,phase:"archive",status:"active",state_version:Kt(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:r,completed_at:i},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:ue(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Wk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return X({...t,status:"active",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,acceptance:mm(t.acceptance),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function zk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let i=(e.now??new Date).toISOString(),r=t.loop.execution_failure_count+1,n=r>=Zs,a=ri(t,Qn({state:t,outcome:"execution-error",summary:e.summary,completedAt:i}));return X({...a,status:n?"blocked":"active",state_version:Kt(t),blockers:n?[{owner:"runtime",reason:ue(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:r,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Jk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return X({...t,status:"active",state_version:Kt(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function ec(e){let t=X(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=ri(t,Qn({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return X({...r,phase:"build",status:"active",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:mm(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 Uk}from"node:fs";import tc from"node:path";function od(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function sd(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 Ui(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 Gk(e,t){return e===null?null:Ui(e,t)}function ld(e,t,i=0){if(!Number.isSafeInteger(e)||eUi(l,`${i}.argv[${u}]`,!0)),a=cd(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=gm(r.startedAt,`${i}.startedAt`),s=gm(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=ld(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ui(r.id,`${i}.id`),name:Ui(r.name,`${i}.name`),operationId:Ui(r.operationId,`${i}.operationId`),status:a,repeatable:HH(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:ld(r.executionCount,`${i}.executionCount`),argv:n,cwd:wm(r.cwd,`${i}.cwd`),exitCode:OH(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ui(r.log,`${i}.log`)}}function ym(e){let t="Native local execution state",i=od(e,t);if(sd(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ps)throw new Error(`Native local execution schema must be ${Ps}`);let r=od(i.workspace,"Native local workspace");sd(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=od(i.execution,"Native local execution");sd(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=gm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ui(o.operationId,"Native local execution.operationId"),stage:cd(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:cd(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Gk(o.executionId,"Native local execution.executionId"),status:cd(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ld(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(DH);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:Ps,change:Ui(i.change,"Native local change"),basedOnStateVersion:ld(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:wm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:wm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Gk(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Be(e){return ym({schema:Ps,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:tc.resolve(e.projectRoot),worktreeRoot:tc.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ci(e){let t;try{t=await Uk.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 ym(i)}async function ce(e,t,i={}){let r=ym(t);await Uk.mkdir(tc.dirname(e),{recursive:!0}),await ve(e,r,i)}async function Nm(e){let t=null,i=null;try{t=await Ci(e.file),t===null&&(i="missing")}catch(n){if(n.code)throw n;i="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(i="version-mismatch"),t&&i===null)return{state:t,rebuilt:!1,reason:null};let r=Be(e);return await ce(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:r,rebuilt:!0,reason:i??"missing"}}import{promises as FH}from"node:fs";function en(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` -`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function mr(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"
")}function MH(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 BH(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===Ge?Ge:"host-attested")}function LH(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${mr(o.id)} | ${mr(o.result)} | ${mr(o.source)} | ${mr(o.text)} | ${mr(en(o.reason))} |`).join(` +`)}),l.once("close",(h,m)=>{clearTimeout(f);let p=(e.now??(()=>new Date))();o.end(()=>{let v=u||d!==null||m!==null;s({id:t.id,name:t.name,argvDisplay:um(t.argv),cwdRef:t.cwdRef,status:v?"interrupted":h===0?"passed":"failed",exitCode:h,signal:m,timedOut:u,durationMs:Math.max(0,p.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:p.toISOString(),repeatable:t.repeatable,logRef:Ut.relative(e.runtimeDir,n).split(Ut.sep).join("/")})})}),o.once("error",h=>{clearTimeout(f),td(l).catch(()=>l.kill("SIGKILL")),c(h)})})}import{randomUUID as TH}from"node:crypto";var Ok=Symbol("comet.native.trusted-execution-identity"),Hk=Symbol("comet.native.trusted-verifier-envelope"),Ge="skill-coordinated";function fm(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Ys(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){fm(t.identityProvider,"Native identity provider");let i=Object.freeze({identityProvider:Ge,executionRef:fm(t.executionRef,"Native execution ref"),[Ok]:!0});return e.add(i),i},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:fm(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Hk]:!0})}})}function nd(e){return typeof e=="object"&&e!==null&&e[Hk]===!0}function Dk(e){return typeof e=="object"&&e!==null&&e[Ok]===!0}function ad(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xs(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Qs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Xn(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function xH(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,i)=>{let r=ad(t,`Native Verifier acceptance ${i}`);Xs(r,["id","result","reason"],`Native Verifier acceptance ${i}`);let n=Xn(r.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(r.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:r.result,reason:Xn(r.reason,`Native Verifier acceptance ${n} reason`)}})}function AH(e){let t=ad(e,"Native Verifier final result");if(Xs(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Qs(t.iteration,"Native Verifier iteration"),attempt:Qs(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:xH(t.acceptance),risks:t.risks,summary:Xn(t.summary,"Native Verifier summary")}}function _H(e,t){let i=ad(e,`Native Verifier check request ${t}`);if(Xs(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let r=Qs(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(r<1)throw new Error("Native Verifier check timeout must be positive");return{id:Xn(i.id,`Native Verifier check request ${t} ID`),name:Xn(i.name,`Native Verifier check request ${t} name`),executable:Xn(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:Xn(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:r,repeatable:i.repeatable}}function hm(e){let t=ad(e,"Native Verifier response");if(t.kind==="final-result")return Xs(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:AH(t.result)};if(t.kind==="request-checks"){if(Xs(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Qs(t.iteration,"Native Verifier iteration"),attempt:Qs(t.attempt,"Native Verifier attempt"),checks:t.checks.map(_H)}}throw new Error("Native Verifier response kind is invalid")}function Fk(e){if(!nd(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:i}=e;if(t.candidateId!==i.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==i.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===i.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let r=hm(t.payload),n=r.kind==="final-result"?r.result.iteration:r.iteration,a=r.kind==="final-result"?r.result.attempt:r.attempt;if(n!==i.iteration||a!==i.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(r.kind==="request-checks")return r;let o=[...i.acceptanceIds],s=r.result.acceptance.map(({id:f})=>f),c=s.filter((f,h)=>s.indexOf(f)!==h),l=s.filter(f=>!o.includes(f)),u=o.filter(f=>!s.includes(f));if(c.length>0||l.length>0||u.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${u.join(", ")||"none"})`);if(!i.requiredChecksPassed&&r.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=r.result.acceptance.map(({result:f})=>f);if(r.result.verdict==="pass"&&d.some(f=>f!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(r.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(r.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return r}var Zs=3,pm=2;function Kt(e){return e.state_version+1}function IH(e,t,i){let r=[...e];if(new Set(r).size!==r.length)throw new Error(`${i} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${i} contains unknown IDs: ${a.join(", ")}`);return r}function mm(e){return e.map(t=>({...t,result:"pending",reason:null}))}function jH(e){return(e??[]).map(t=>({name:de(t.name),result:t.result,note:t.note?de(t.note):null}))}function Qn(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:de(e.summary),completed_at:e.completedAt}}function Mk(e){let t=X(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let i=e.acceptance.map(({id:r})=>r);if(new Set(i).size!==i.length)throw new Error("Native acceptance IDs must be unique");return X({...t,phase:"build",state_version:Kt(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(r=>({...r,result:"pending",reason:null}))})}function vm(e){let t=X(e.state),{input:i}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Dk(i.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");let r=IH(i.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=(i.now??new Date).toISOString();return X({...t,phase:"verify",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:mm(t.acceptance),builder_handoff:{candidate_id:i.candidateId??TH(),identity_provider:i.identity.identityProvider,builder_execution_ref:i.identity.executionRef,iteration:t.loop.iteration,summary:de(i.summary),addressed_acceptance_ids:r,checks:jH(i.checks),checks_truncated:!1,known_limits:(i.knownLimits??[]).map(a=>de(a)),known_limits_truncated:!1,submitted_at:n},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Bk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt is not ready to dispatch");return X({...t,state_version:Kt(t),loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function $H(e,t){let i=e.loop.previous_unresolved_ids;if(i.length===0)return 0;let r=new Set(i),n=new Set(t);return n.sizer.has(o))?0:e.loop.no_progress_count+1}function OH(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Ge?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:de(e.response.result.summary),risks:e.response.result.risks.map(t=>de(t)),risks_truncated:!1,completed_at:e.completedAt}}function Lk(e){let t=X(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let i=Fk({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:t.acceptance.map(({id:m})=>m),requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let r=(e.now??new Date).toISOString(),n=new Map(i.result.acceptance.map(m=>[m.id,m])),a=t.acceptance.map(m=>{let p=n.get(m.id);return{...m,result:p.result,reason:de(p.reason)}}),o=a.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),s=OH({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:r});if(i.result.verdict==="pass"){let m=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"pass",summary:i.result.summary,completedAt:r})),p=t.builder_handoff.identity_provider===Ge;return{response:i,state:X({...m,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:Kt(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:de("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"blocked",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...m,status:"await-user",state_version:Kt(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:de(i.result.summary),acceptance_ids:o,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:o,next_action:"resolve-verifier-blocker"}})}}let c=t.loop.failed_iteration_count+1,l=$H(t,o),u=c>=e.maxVerifyFailures,d=l>=3,f=u||d,h=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"fail",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...h,phase:f?"verify":"build",status:f?"await-user":"active",state_version:Kt(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:f?[{owner:"user",reason:de(u?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:o,resolution_action:"await-user"}]:l>=2?[{owner:"builder",reason:de("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:o,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:f?"await-user":"repairing",iteration:f?t.loop.iteration:t.loop.iteration+1,attempt:f?t.loop.attempt:0,failed_iteration_count:c,no_progress_count:l,execution_failure_count:0,previous_unresolved_ids:o,next_action:f?"await-user":"repair-failed-acceptance"}})}}function qk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Ge||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return X({...t,phase:"archive",status:"active",state_version:Kt(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Vk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Ge||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let i=(e.now??new Date).toISOString(),r=t.acceptance.map(({id:a})=>a),n=ri(t,Qn({state:t,outcome:"blocked",unresolvedIds:r,summary:e.summary,completedAt:i}));return X({...n,status:"await-user",state_version:Kt(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:de(e.summary),risks:[de("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:i},blockers:[{owner:"user",reason:de("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:r,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:r,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Wk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let i=(e.now??new Date).toISOString(),r=de(e.summary),n=ri(t,Qn({state:t,outcome:"pass",summary:e.summary,completedAt:i}));return X({...n,phase:"archive",status:"active",state_version:Kt(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:r,completed_at:i},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:de(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function zk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return X({...t,status:"active",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,acceptance:mm(t.acceptance),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Jk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let i=(e.now??new Date).toISOString(),r=t.loop.execution_failure_count+1,n=r>=Zs,a=ri(t,Qn({state:t,outcome:"execution-error",summary:e.summary,completedAt:i}));return X({...a,status:n?"blocked":"active",state_version:Kt(t),blockers:n?[{owner:"runtime",reason:de(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:r,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Gk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return X({...t,status:"active",state_version:Kt(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function ec(e){let t=X(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=ri(t,Qn({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return X({...r,phase:"build",status:"active",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:mm(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 Kk}from"node:fs";import tc from"node:path";function od(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function sd(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 Ui(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 Uk(e,t){return e===null?null:Ui(e,t)}function ld(e,t,i=0){if(!Number.isSafeInteger(e)||eUi(l,`${i}.argv[${u}]`,!0)),a=cd(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=gm(r.startedAt,`${i}.startedAt`),s=gm(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=ld(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ui(r.id,`${i}.id`),name:Ui(r.name,`${i}.name`),operationId:Ui(r.operationId,`${i}.operationId`),status:a,repeatable:DH(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:ld(r.executionCount,`${i}.executionCount`),argv:n,cwd:wm(r.cwd,`${i}.cwd`),exitCode:HH(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ui(r.log,`${i}.log`)}}function ym(e){let t="Native local execution state",i=od(e,t);if(sd(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ps)throw new Error(`Native local execution schema must be ${Ps}`);let r=od(i.workspace,"Native local workspace");sd(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=od(i.execution,"Native local execution");sd(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=gm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ui(o.operationId,"Native local execution.operationId"),stage:cd(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:cd(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Uk(o.executionId,"Native local execution.executionId"),status:cd(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ld(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(FH);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:Ps,change:Ui(i.change,"Native local change"),basedOnStateVersion:ld(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:wm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:wm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Uk(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Be(e){return ym({schema:Ps,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:tc.resolve(e.projectRoot),worktreeRoot:tc.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ci(e){let t;try{t=await Kk.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 ym(i)}async function ce(e,t,i={}){let r=ym(t);await Kk.mkdir(tc.dirname(e),{recursive:!0}),await ve(e,r,i)}async function Nm(e){let t=null,i=null;try{t=await Ci(e.file),t===null&&(i="missing")}catch(n){if(n.code)throw n;i="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(i="version-mismatch"),t&&i===null)return{state:t,rebuilt:!1,reason:null};let r=Be(e);return await ce(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:r,rebuilt:!0,reason:i??"missing"}}import{promises as MH}from"node:fs";function en(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,` +`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function mr(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"
")}function BH(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 LH(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===Ge?Ge:"host-attested")}function qH(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${mr(o.id)} | ${mr(o.result)} | ${mr(o.source)} | ${mr(o.text)} | ${mr(en(o.reason))} |`).join(` `),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(en).join(" ");return`| ${mr(en(o.name))} | ${mr(s||"—")} | ${mr(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(` `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${en(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(` `),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${en(o)}`).join(` @@ -207,8 +207,8 @@ generated_from_state_version: ${e.state_version} ## Current result -- Result: **${MH(e)}** -- Assurance: **${BH(e)}** +- Result: **${BH(e)}** +- Assurance: **${LH(e)}** - Goal cycle: ${e.loop.goal_cycle} - Iteration: ${e.verification.iteration} - Verifier attempt: ${e.verification.attempt} @@ -242,7 +242,7 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ `:""}## Conclusion ${en(e.verification.summary)} -`}function qH(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 ic(e){let t;try{t=await FH.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=qH(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function vr(e){await Ne(e.file,LH(e.state))}var pd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VH="comet-state.yaml",WH="state.json",zH=`# Outcome +`}function VH(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 ic(e){let t;try{t=await MH.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=VH(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function vr(e){await Ne(e.file,qH(e.state))}var pd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WH="comet-state.yaml",zH="state.json",JH=`# Outcome # Scope @@ -257,42 +257,42 @@ ${en(e.verification.summary)} # Open questions # Verification expectations -`;function we(e,t){if(!pd.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=He.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function Ht(e,t){return He.join(we(e,t),VH)}function ae(e,t){return He.join(ze(e,t),WH)}async function ke(e,t){try{let i=await di.readFile(Ht(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function JH(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Et(e){return me(e).currentBranch}function GH(e,t){if(!t)return;let i=me(e);if(t.changeBranch!==null&&(!i.isGitWorktree||i.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Yk(e){return F(e.paths,`create portable change ${e.name}`,async()=>{if(!pd.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await Y(e.paths.projectRoot)===null&&await Vt(e.paths.projectRoot,e.initialProjectConfig),GH(e.paths.projectRoot,e.workspaceBinding);let t=(await kk(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Qa(e.workspaceBinding?.isolation??"current",t);let i=we(e.paths,e.name),r=ze(e.paths,e.name);await Promise.all([T(e.paths.nativeRoot,i),T(e.paths.runtimeDir,r)]);let n=!1,a=!1;try{await di.mkdir(e.paths.changesDir,{recursive:!0}),await di.mkdir(i,{recursive:!1}),n=!0,await di.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await di.mkdir(r,{recursive:!1}),a=!0,await di.mkdir(He.join(i,"specs"),{recursive:!0}),await Ne(He.join(i,"brief.md"),zH);let o=VN({name:e.name,language:e.language,workspace:JH(e.workspaceBinding),createdAt:e.now,nextAction:"confirm-shape"});return await Rs(Ht(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await ce(ae(e.paths,e.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await di.rm(r,{recursive:!0,force:!0}),n&&await di.rm(i,{recursive:!0,force:!0}),o}})}async function K(e,t){return wt(Ht(e,t))}async function dt(e){let t=await Bn({file:Ht(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=He.join(we(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await di.rm(i,{force:!0})}return t}async function Xk(e){let t=we(e.paths,e.state.name),i=He.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await di.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(!pd.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=He.join(t,...s.split("/")),l=await di.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=He.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await di.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Qk(e){let t=we(e.paths,e.state.name),i=await ee({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return mu({briefMarkdown:i.text,specs:r})}async function Zk(e){return F(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await Xk({paths:e.paths,state:t}),r=await Qk({paths:e.paths,state:t,specChanges:i}),n=await Us({changeDir:we(e.paths,t.name),acceptanceIds:r.map(({id:s})=>s)});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=Fk({state:{...t,spec_changes:i},acceptance:r.map(s=>({...s}))});if(delete a.children_contract_hash,n){a.children_contract_hash=ed({acceptance:a.acceptance,children:n.contract});let s=[...t.history].reverse().find(({outcome:c})=>c==="pass"||c==="fail");if(s?.outcome==="fail"&&s.unresolved_ids.length>0){let c=await Gt({paths:e.paths,state:a}),l=new Set((c?.children??[]).filter(({status:d})=>d!=="done").flatMap(({covers:d})=>d)),u=s.unresolved_ids.filter(d=>!l.has(d));if(u.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${u.join(", ")}`)}}let o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}async function Zn(e){let t=await Xk(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 Qk({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!LN(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Us({changeDir:we(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?ed({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 gr(e){let t=await Zn(e);if(!t.drifted)return;let i=t.reason??"Native confirmed requirements changed";throw await md({paths:e.paths,state:e.state,reason:i}),new Error(`${i}; Native change returned to Shape and requires confirmation`)}async function eS(e){return F(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(await gr({paths:e.paths,state:t}),await Us({changeDir:we(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a)})||t.children_contract_hash)throw new Error("Native parent Build advances child changes instead of a parent Builder");let r=vm({state:t,input:e.input}),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function tS(e){return F(e.paths,`complete portable parent Build ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.phase!=="build"||t.status!=="active")throw new Error("Native parent integration can only complete from active Build");await gr({paths:e.paths,state:t});let i=await Gt({paths:e.paths,state:t});if(!i||!t.children_contract_hash)throw new Error(`Native change ${t.name} has no confirmed child contract`);if(!i.confirmed)throw new Error("Native parent child declarations require Shape confirmation");if(!i.allDone)throw new Error("Native parent cannot enter Verify before every child is merged");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; add and confirm a repair child");let n=Ys().captureExecutionIdentity({identityProvider:"skill-coordinated",executionRef:`native-parent-integration:${hd()}`}),a=vm({state:t,input:{identity:n,summary:e.summary,addressedAcceptanceIds:t.acceptance.map(({id:s})=>s),checks:[],knownLimits:[]}}),o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}function km(e,t,i){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:id(i,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function iS(e,t,i,r){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...km(t,i,r),executionCount:e.executionCount}}function rS(e,t){let i=He.relative(He.resolve(e),He.resolve(t));if(He.isAbsolute(i)||i===".."||i.startsWith(`..${He.sep}`))throw new Error("Native local check cwd escaped the project root");let r=i.length===0?".":i.split(He.sep).join("/");return id(e,r),r}function bm(e,t){let[i,...r]=e.argv;if(!i)throw new Error(`Native local check ${e.id} has no executable`);return Ks({id:e.id,name:e.id,executable:i,argv:r,cwdRef:rS(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function UH(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function io(e){let t=new Map;for(let i of e.supplied){if(t.has(i.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${i.id}`);t.set(i.id,i)}return e.local.checks.map(i=>{if(i.status==="planned"||i.status==="running")throw new Error(`Native Runtime check ${i.id} has not completed`);let r=e.requestedNames?.get(i.id)??i.name;return{id:i.id,name:ue(r),argv_display:um(i.argv.slice(1)).map(n=>ue(n)),argv_truncated:!1,cwd_ref:rS(e.projectRoot,i.cwd),status:i.status,exit_code:i.exitCode,duration_ms:UH(i)}})}function KH(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function rc(e){if(e.local===null||e.local.change!==e.state.name)return Be({portableState:e.state,projectRoot:e.projectRoot,branch:Et(e.projectRoot)});let t=e.local.execution?.operationId??hd();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(i=>i.status==="running"||i.status==="planned"?{...i,operationId:t,status:"interrupted"}:{...i,operationId:t})}}async function ro(e){try{let t=await Ci(ae(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function nS(e){let{state:t,local:i,expected:r}=e;if(t.state_version!==r.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==r.iteration||t.loop.attempt!==r.attempt||t.builder_handoff===null||i===null||i.basedOnStateVersion!==t.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return i}function YH(e){let{state:t,local:i,envelope:r}=e;if(!nd(r))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(r.candidateId!==t.builder_handoff.candidate_id||r.identityProvider!==t.builder_handoff.identity_provider||r.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(i===null||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==null&&i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return r}function XH(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function fd(e){let t=await ro({paths:e.paths,state:e.state}),i=zk({state:e.state,summary:e.summary}),r=await dt({paths:e.paths,previous:e.state,next:i});return await ce(ae(e.paths,e.state.name),rc({local:t,state:r,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),r}function Kk(e,t,i){return e.checks.length!==t.length?!1:e.checks.every((r,n)=>bm(r,i)===Ks(t[n]))}async function QH(e){return F(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(await gr({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let i=ae(e.paths,t.name),r=(await Nm({file:i,portableState:t,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(r.execution?.stage==="checking"&&r.execution.actor==="runtime"&&Kk(r,e.plans,e.paths.projectRoot)){let o=r.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=r.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:u})=>[l,u]));return{kind:"reuse",state:t,checks:io({local:r,projectRoot:e.paths.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=ec({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(u=>!u.repeatable).map(({id:u})=>u).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await dt({paths:e.paths,previous:t,next:c});throw await ce(ae(e.paths,t.name),Be({portableState:l,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(u=>!u.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(r.execution!==null&&r.checks.length>0){if(!(r.execution.stage==="checking"&&r.execution.actor==="runtime"&&r.checks.some(s=>s.status==="interrupted")&&Kk(r,e.plans,e.paths.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(r.execution!==null||r.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=hd(),a={...r,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=r.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?iS(s,o,n,e.paths.projectRoot):s?{...s,operationId:n}:km(o,n,e.paths.projectRoot)})};return await ce(i,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=r.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function ud(e){return F(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await K(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let i=ae(e.paths,t.name),r=await Ci(i);if(r===null||r.basedOnStateVersion!==t.state_version||r.execution?.operationId!==e.operationId||r.execution.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(r);return await ce(i,n,{containedRoot:e.paths.runtimeDir}),n})}async function aS(e){if(new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let t=[],i=new Set;for(let s of e.plans){rd(e.paths.projectRoot,s);let c=Ks(s);i.has(c)||(i.add(c),t.push(s))}let r=await QH({...e,plans:t});if(r.kind==="reuse")return r;let n=r.local.execution.operationId,a=ze(e.paths,r.state.name);try{for(let s of r.plans){let c=new Date().toISOString();await ud({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:c}:d)})});let l=await dm({projectRoot:e.paths.projectRoot,runtimeDir:a,operationId:n,plan:s});await ud({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:l.status,exitCode:l.exitCode,startedAt:l.startedAt,completedAt:l.completedAt,log:l.logRef}:d)})})}await ud({paths:e.paths,state:r.state,operationId:n,update:s=>({...s,execution:{...s.execution,status:"completed"}})})}catch(s){try{await ud({paths:e.paths,state:r.state,operationId:n,update:c=>({...c,execution:{...c.execution,status:"interrupted"},checks:c.checks.map(l=>l.status==="planned"||l.status==="running"?{...l,status:"interrupted"}:l)})})}catch{}throw s}let o=await Ci(ae(e.paths,r.state.name));if(o===null)throw new Error("Native Runtime check state disappeared after execution");return{state:r.state,checks:io({local:o,projectRoot:e.paths.projectRoot,supplied:[]})}}async function ZH(e){let t=ae(e.paths,e.state.name),i=e.local;if(i===null||i.change!==e.state.name||i.basedOnStateVersion!==e.state.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(i.execution.executionId!==null&&i.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(i.execution.requestCheckRounds>=pm)throw new Error(`Native Verifier request-checks exceeded ${pm} rounds for this attempt`);let r=new Map,n=new Map,a=new Map;for(let h of i.checks){let m=bm(h,e.paths.projectRoot);n.set(m,h),h.status!=="interrupted"&&r.set(m,h),a.set(h.id,m)}let o=new Map,s=new Map;for(let h of e.response.checks){let m=KH(h);rd(e.paths.projectRoot,m);let p=Ks(m),v=s.get(m.id);if(v!==void 0&&v!==p)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let g=a.get(m.id);if(g!==void 0&&g!==p)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,p);let y=n.get(p);if(y?.status==="interrupted"&&!y.repeatable)throw new Error(`Native check ${y.id} was interrupted and is not repeatable; user resolution is required`);o.has(p)||o.set(p,m)}let c=[...o.entries()],l=c.filter(([h])=>!r.has(h));if(i.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=i.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),f={...i,execution:{...i.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...i.checks.map(h=>{let m=bm(h,e.paths.projectRoot),p=o.get(m);return p&&h.status==="interrupted"?iS(h,p,i.execution.operationId,e.paths.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>km(h,i.execution.operationId,e.paths.projectRoot))]};return await ce(t,f,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:f,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>r.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function dd(e){return F(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await K(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let i=ae(e.paths,t.name),r=await Ci(i),n=r?.execution;if(r===null||r.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(r);return await ce(i,a,{containedRoot:e.paths.runtimeDir}),a})}async function eD(e){let t;try{for(let i of e.reservation.novelPlans){let r=new Date().toISOString();t=await dd({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:r}:o)})});let n=await dm({projectRoot:e.paths.projectRoot,runtimeDir:ze(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:i});t=await dd({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await dd({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(i){try{await dd({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,status:"interrupted"},checks:r.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw i}return{checks:io({local:t,projectRoot:e.paths.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:i})=>i)}}}async function oS(e){return F(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=(await Nm({file:ae(e.paths,t.name),portableState:t,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");io({local:i,projectRoot:e.paths.projectRoot,supplied:e.checks});let r=Mk(t),n=await dt({paths:e.paths,previous:t,next:r}),a=ae(e.paths,t.name),o=hd();return await ce(a,{...i,basedOnStateVersion:n.state_version,execution:{operationId:o,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(s=>({...s,operationId:o}))},{containedRoot:e.paths.runtimeDir}),n})}async function sS(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await F(e.paths,`apply portable verifier ${e.name}`,async()=>{let i=await K(e.paths,e.name);await gr({paths:e.paths,state:i});let r=await ro({paths:e.paths,state:i}),n=YH({state:i,local:r,envelope:e.envelope}),a;try{a=hm(n.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await fd({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${Zs} was recorded`,{cause:u})}let o=XH(a);if(o.iteration!==i.loop.iteration||o.attempt!==i.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let s=[],c;try{r!==null&&(s=io({local:r,projectRoot:e.paths.projectRoot,supplied:e.checks}));let u=Bk({state:i,envelope:n,checks:s,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(r===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await ZH({paths:e.paths,state:i,local:r,envelope:n,response:u.response,suppliedChecks:s});return{kind:"request-checks",state:i,response:u.response,reservation:d}}if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==n.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");c=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await fd({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${Zs} was recorded`,{cause:u})}let l=await dt({paths:e.paths,previous:i,next:c.state});return await ce(ae(e.paths,i.name),l.loop.next_action==="resolve-verifier-blocker"?rc({local:r,state:l,projectRoot:e.paths.projectRoot}):Be({portableState:l,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),l.verification!==null&&await vr({file:He.join(we(e.paths,i.name),"verification.md"),state:l}),{kind:"final-result",result:{state:l,response:c.response,checks:s,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let i=await eD({paths:e.paths,reservation:t.reservation});return{state:t.state,response:t.response,checks:i.checks,requestChecks:i.requestChecks}}catch(i){let r=`Native Verifier response was invalid: ${i.message}`,n=await F(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await K(e.paths,e.name);return a.state_version!==t.state.state_version?null:fd({paths:e.paths,state:a,summary:r})});throw new Error(n?`${r}; execution error ${n.loop.execution_failure_count}/${Zs} was recorded`:`${r}; the portable state changed before the execution error could be recorded`,{cause:i})}}async function cS(e){return F(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await ro({paths:e.paths,state:t});if(nS({state:t,local:i,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return fd({paths:e.paths,state:t,summary:e.summary})})}async function lS(e){return F(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=await ro({paths:e.paths,state:t}),r=nS({state:t,local:i,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=io({local:r,projectRoot:e.paths.projectRoot,supplied:[]}),a=qk({state:t,checks:n,verifierExecutionRef:r.execution.executionId,summary:e.summary}),o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),rc({local:r,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:o}),o})}async function uS(e){return F(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=Lk(t),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function dS(e){return F(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=Vk({state:t,summary:e.summary}),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function fS(e){return F(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=await ro({paths:e.paths,state:t}),r=Wk(t),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),rc({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function hS(e){return F(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await ro({paths:e.paths,state:t}),r=Jk(t),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),rc({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function no(e){return F(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await K(e.paths,e.name);if(t.phase==="build")return t;let i=ec({state:t,reason:e.reason}),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}async function pS(e){if(!pd.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return F(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await K(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i=t.spec_changes.filter(({capability:a})=>a!==e.capability),r={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...i,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function mS(e){return F(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await K(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 dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function nc(e){return F(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await K(e.paths,e.name);return t.phase==="shape"?t:md({paths:e.paths,state:t,reason:e.reason})})}async function md(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...ri(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ue(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 dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function vd(e){if(e.state.verification===null)return"not-applicable";let t=He.join(we(e.paths,e.state.name),"verification.md");return await ic({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await vr({file:t,state:e.state}),"rebuilt")}async function vS(e){let t=await K(e.paths,e.name),i=ae(e.paths,e.name);try{let r=await Ci(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}import{randomUUID as tD}from"crypto";import{promises as ac}from"fs";import wS from"path";var Sm="comet.selection.v2",iD=16*1024;function oc(e){return wS.join(e,".comet","current-change.json")}function rD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function gS(e){return e===null||typeof e=="string"}function yS(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(!rD(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&&!gS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Sm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Sm)throw new Error(`current change selection schema must be ${Sm}`);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(!gS(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 Em(e){let t;try{let r=oc(e),{bytes:n}=await jn(r,iD,{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",...yS(t)}}async function NS(e,t){let i=yS(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=oc(e),n=`${r}.${tD()}.tmp`;await ac.mkdir(wS.dirname(r),{recursive:!0});try{await ac.writeFile(n,`${JSON.stringify(i.selection,null,2)} -`,"utf8"),await ac.rename(n,r)}catch(a){throw await ac.rm(n,{force:!0}),a}}async function bS(e){await ac.rm(oc(e),{force:!0})}async function kS(e,t,i){let r=await Em(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await bS(e),!0)}var WU=16*1024;async function sc(e){let t=await Em(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Un(t.selection.change),t.selection)}function cc(e){return oc(e.projectRoot)}async function gd(e,t){return F(e,`select change ${t}`,async()=>{Un(t),await ke(e,t)?await K(e,t):await je(e,t),await NS(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function SS(e){let t=await sc(e);return t?(await ke(e,t.change)?await K(e,t.change):await je(e,t.change),t.change):null}async function lc(e,t){return await Ia(e.projectRoot),kS(e.projectRoot,"native",t)}var uc=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 Pm(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Rm(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=Pt.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function wd(e){try{return await tt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ES(e,t){let i=Pt.normalize(Pt.resolve(e)),r=Pt.normalize(Pt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function PS(e,t){let i;try{i=await tt.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=Pt.join(e.archiveDir,n.name);try{let o=await wt(Pt.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 Cm(e,t){let i=await Ha(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function RS(e,t){return await Cm(e,t)!==null||await PS(e,t)!==null}async function ea(e,t){await tt.mkdir(e.transactionsDir,{recursive:!0}),await ve(Vr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function CS(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Zt(e.paths.projectRoot);i.some(a=>ES(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Y(a);if(!o)continue;let s=await re(a,o.native.artifact_root);r.some(c=>ES(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 tt.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 wt(Pt.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 Kn(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 aD(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 oD(e){let t=Pt.join(e.paths.specsDir,e.change.capability),i=Pt.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await tt.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 tt.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([tt.realpath(e.paths.specsDir),tt.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await tt.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await tt.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await tt.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=Pt.join(we(e.paths,e.state.name),e.change.source);await Ne(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await tt.mkdir(t,{recursive:!0}),await Ne(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function xm(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 sD(e,t){let i=we(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await ee({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function cD(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(xm(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Am(e){let t=await K(e.paths,e.name),i=[];try{xm(t)}catch(o){i.push(o.message)}if(await Cm(e.paths,e.name)===null)try{let o=await Zn({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 ic({file:Pt.join(we(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await CS({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:Rm(e.paths,Pm(t)),stateVersion:t.state_version}}async function dc(e){return F(e.paths,`archive portable change ${e.name}`,async()=>{let t=aD(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await Cm(e.paths,e.name),r=we(e.paths,e.name),n=await wd(r),a=n?null:await PS(e.paths,e.name),o;if(n)o=await K(e.paths,e.name);else if(i)o=await wt(Pt.join(Rm(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 Zn({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await md({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=Rm(e.paths,i?.archive_ref??Pm(o)),c=await wd(s);if(i&&cD(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 lc(e.paths,o.name),await tt.rm(ze(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)xm(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await CS({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new uc(l);i={schema:ku,id:nD(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Pm(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await sD(e.paths,o),created_at:new Date().toISOString()},await ea(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await ea(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({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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 lD}from"node:crypto";import{promises as ao}from"node:fs";import $S from"node:path";var OS=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function uD(e){try{return await ao.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _m(e,t){let i=te(e,t),r=[Vr(e,{kind:"migration",change:t}),On(e,t),...OS.map(n=>$S.join(i,n))];return(await Promise.all(r.map(uD))).some(Boolean)}async function dD(e,t){let i=await Ha(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function xS(e,t){await ao.mkdir(e.transactionsDir,{recursive:!0}),await ve(Vr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function AS(e,t){await Promise.all([ao.rm(ze(e,t),{recursive:!0,force:!0}),ao.rm(On(e,t),{recursive:!0,force:!0}),...OS.map(i=>ao.rm($S.join(te(e,t),i),{force:!0}))])}async function _S(e,t){await ce(ae(e,t.name),Be({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function TS(e,t){try{let i=await lt(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 IS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=me(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 fD(e){let t=te(e.paths,e.state.name),i=await ee({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 ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return mu({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function jS(e,t){let i=await Kn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function xi(e){return F(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await dD(e.paths,e.name),i=await ke(e.paths,e.name)?await wt(Ht(e.paths,e.name)):null;if(!t&&i)return await AS(e.paths,e.name),await _S(e.paths,i),i;let r=null,n=null;for(t||(r=await jS(e.paths,e.name),n=await TS(e.paths,e.name),IS(e.paths,n),t={schema:bu,id:lD(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await xS(e.paths,t));;){let a=zN(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await jS(e.paths,e.name),n??=await TS(e.paths,e.name),IS(e.paths,n),i=WN({state:r,acceptance:await fD({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Rs(Ht(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await AS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await wt(Ht(e.paths,e.name)),await _S(e.paths,i)),t={...t,status:a.nextStatus},await xS(e.paths,t)}return await ao.rm(Vr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??wt(Ht(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as HS}from"node:fs";import DS from"node:path";function hD(e,t){let i=me(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 pD(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function mD(e,t){let i=new Date().toISOString(),r=e.verification===null?e:ri(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ue(t),completed_at:i});return X({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:pD(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 vD(e){try{let t=await Ci(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 ta(e){return F(e.paths,`recover portable change ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.status==="done")return await vd({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=hD(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=ae(e.paths,e.name),n=await vD(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(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await ce(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await vd({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(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=ec({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Bn({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await HS.rm(DS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Be({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await ce(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,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 f=mD(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 Bn({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=Be({portableState:t,projectRoot:e.paths.projectRoot,branch:me(e.paths.projectRoot).currentBranch});return await HS.mkdir(DS.dirname(ae(e.paths,t.name)),{recursive:!0}),await ce(r,d,{containedRoot:e.paths.runtimeDir}),await vd({paths:e.paths,state:t}),{state:t,local:d,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{promises as SD}from"node:fs";import oo from"node:path";import{execFileSync as gD}from"node:child_process";var wD=6e4,yD=8*1024*1024,Tm=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 Im(e,t,i={}){let r=i.timeoutMs??wD,n=i.maxBufferBytes??yD;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 gD(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","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 Tm(e,t,o,{cause:a})}}import{promises as jm}from"fs";import FS from"path";var MS=["Outcome","Scope","Non-goals","Acceptance examples"],ND=[...MS,"Constraints and invariants","Decisions","Open questions","Verification expectations"],bD=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],BS={maxFileBytes:$o};function LS(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(` -`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function kD(e,t){let i=FS.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await jm.realpath(e),n=await jm.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await jm.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function fc(e){return{valid:e.length===0,findings:e}}async function $m(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:BS.maxFileBytes})).text}catch(o){return fc([{code:"brief-missing",message:o.message,path:t}])}let n=LS(r);for(let o of ND)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of MS)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),fc(i)}async function Om(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:BS.maxFileBytes})).text}catch(a){return fc([{code:"verification-missing",message:a.message,path:t}])}let n=LS(r);for(let a of bD)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return fc(i)}function ia(e,t){return FS.join(e.specsDir,t,"spec.md")}async function qS(e,t){let i=[],r=te(e,t.name);for(let n of t.spec_changes){let a=ia(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await oi(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await kD(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return fc(i)}var hc=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function ED(e,t){let i=oo.relative(e,t);return i===""||!oo.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${oo.sep}`)}function ra(e,t){let i=oo.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||oo.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function VS(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function PD(e){try{if(he(e,["config","--get","user.name"])&&he(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function RD(e,t){for(let i of Zt(e))if(me(i).currentBranch===t)return i;return null}function CD(e,t){try{Im(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function Hm(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=me(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`);PD(t.projectRoot);let a=[ra(t.projectRoot,cc(t))];e.archiveDir&&a.push(ra(t.projectRoot,te(t,i.name)),ra(t.projectRoot,e.archiveDir));let o=im(t.projectRoot).filter(l=>!VS(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:RD(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(!Gs(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Ek(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&CD("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function xD(e,t){try{return Im("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function AD(e){try{return await SD.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function _D(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function WS(e){let t=_D(e.plan),i=null;try{let r=[ra(e.paths.projectRoot,te(e.paths,e.name)),ra(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(c=>ra(e.paths.projectRoot,ia(e.paths,c.capability))),ra(e.paths.projectRoot,cc(e.paths))],n=im(e.plan.changeRoot).filter(c=>!VS(c,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=[];for(let c of r){let l=oo.resolve(e.paths.projectRoot,...c.split("/")),u=he(e.plan.changeRoot,["ls-files","--",c])!=="";(await AD(l)||u)&&a.push(c)}if(a.length>0&&he(e.plan.changeRoot,["add","-A","--",...a]),he(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&he(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=he(e.plan.changeRoot,["rev-parse","HEAD"]),!Gs(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"){if(he(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=xD(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(l=>/^https?:\/\//u.test(l.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let c=ED(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!c?(he(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 s=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(he(s,["switch",e.plan.targetBranch]),i=s),he(s,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=s,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(i!==null){let n;try{he(i,["merge","--abort"])}catch{}try{me(i).currentBranch===e.plan.targetBranch&&he(i,["switch",e.plan.changeBranch]),n=me(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==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new hc(t)}}import Fv from"path";import{promises as UP}from"fs";import Eo from"path";import{isDeepStrictEqual as tL}from"util";import{createHash as TD}from"crypto";function zS(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function JS(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))JS(e[t]);return Object.freeze(e)}function tn(e){return JS(structuredClone(e))}function Dm(e,t,i,r){return e.resolveStep({pkg:tn(t),state:tn(i),context:tn(r)})}function GS(e,t,i,r,n,a){return e.resolveNext({pkg:tn(t),state:tn(i),step:tn(r),outcome:tn(n),context:tn(a)})}function ID(e,t,i){return TD("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Fm(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function US(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Dm(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Fm(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:ID(s.runId,s.iteration,o.id),stepId:o.id};return jD(e,s,c,i)}function jD(e,t,i,r){let n=zS(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function KS(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Dm(r,e,t,n):void 0,o=a?Fm(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?GS(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Fm(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as AB}from"node:fs";import jP from"node:path";import YS from"node:path";var $D="comet.native.archive-preflight.v1",OD="comet.native.archive-preflight.v1",HD="comet.native.archive-operation.v1",DD=/^[a-f0-9]{64}$/u,XS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function yd(e,t){return et?1:0}function MD(e,t){if(typeof e!="string"||!DD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wr(e,t){return e===null?null:MD(e,t)}function BD(e,t){let i=YS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||YS.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function LD(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function qD(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function VD(e,t){if(!XS.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=wr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=wr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=wr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function WD(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:wr(e.contractHash,"Native archive contract hash"),acceptanceHash:wr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:wr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:wr(e.reportHash,"Native archive report hash"),envelopeHash:wr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:wr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function zD(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!FD.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(yd);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function JD(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(yd)}function QS(e){if(!XS.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(VD).sort((l,u)=>yd(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(HD,l)})),r=WD(e.evidence),n=qD(e.workspace),a=[...new Set([...zD(e.findingCodes??[]),...JD({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(yd),o=LD(e.revision),s=BD(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:$D,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(OD,c)}}import{createHash as GD}from"node:crypto";import ZS from"node:path";var UD="comet.native.conflict-radar.v1",Dt=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}),KD="comet.native.conflict-radar.v1",YD="comet.native.conflict-radar-signals.v1",XD=/^[a-f0-9]{64}$/u,iE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QD=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),ZD=new Set(["capability","operation","baseHash"]),eF=new Set(["path","kind"]);function so(e,t){return et?1:0}function Mm(e){return Buffer.byteLength(e,"utf8")}function Bm(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Lm(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Mm(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function tF(e,t){let i=Lm(e,t,Dt.maxArtifactPathBytes),r=ZS.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||ZS.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function rE(e,t){if(typeof e!="string"||!XD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function iF(e,t){let i=Bm(e,ZD,t),r=Lm(i.capability,`${t} capability`,Dt.maxCapabilityBytes);if(!iE.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:rE(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function rF(e,t){let i=Bm(e,eF,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:tF(i.path,`${t} path`),kind:i.kind}}function nF(e,t){let i=Bm(e,QD,`Conflict radar change ${t}`),r=Lm(i.name,`Conflict radar change ${t} name`,Dt.maxNameBytes);if(!iE.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>Dt.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>Dt.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>iF(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>so(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>rF(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>so(c.path,l.path)||so(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:rE(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function aF(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Dt.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(nF).sort((n,a)=>so(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Dt.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Dt.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function oF(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function sF(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function cF(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function lF(e,t){let i=[],r=GD("sha256").update(`${YD} -[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(ks(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(oF(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=sF(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:cF(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function eE(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function uF(e,t){return eE(e.classification)-eE(t.classification)||so(e.left,t.left)||so(e.right,t.right)}function tE(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:UD,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function nE(e){let t=aF(e),i=[];for(let s=0;s({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D(KD,{changes:t,relationships:r}),a=i.slice(0,Dt.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=tE(t,i,a,n);for(;a.length>0&&Mm(JSON.stringify(o))>Dt.maxSerializedBytes;)a=a.slice(0,-1),o=tE(t,i,a,n);if(Mm(JSON.stringify(o))>Dt.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as pM}from"node:crypto";import{promises as _i}from"node:fs";import Xi from"node:path";import{createHash as fE}from"node:crypto";import aE from"path";var qm="comet.native.implementation-scope.v2",hE="comet.native.content-snapshot-projection.v1",pc="comet.native.content-snapshot-projection.v1",pE="comet.native.implementation-scope.v2",dF="comet.native.unresolved-scope-id.v1",fF="comet.native.scope-detail-overflow.v1",hF="comet.native.snapshot-projection-overflow.v2",Jm=/^[a-f0-9]{64}$/u,aa=1024*1024,pF=128,mF=128;function ft(e,t){return et?1:0}function Vm(e){if(!Jm.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function vF(e,t){return e===t?0:e===null?-1:t===null?1:ft(e,t)}function nn(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=aE.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||aE.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function mE(e,t){return e==="."?e:nn(e,t)}function co(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function gF(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:nn(e.path,`${t} path`),hash:e.hash,size:co(e.size,`${t} size`),type:"file"}}function wF(e,t){return{path:mE(e.path,`${t} path`),size:e.size===null?null:co(e.size,`${t} size`),type:e.type,reason:e.reason}}function yF(e,t){return ft(e.path,t.path)||ft(e.hash,t.hash)||e.size-t.size}function NF(e,t){return ft(e.path,t.path)||ft(e.reason,t.reason)||ft(e.type,t.type)||(e.size??-1)-(t.size??-1)}function vc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` +`;function we(e,t){if(!pd.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=He.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function Ht(e,t){return He.join(we(e,t),WH)}function ae(e,t){return He.join(ze(e,t),zH)}async function ke(e,t){try{let i=await di.readFile(Ht(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function GH(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Et(e){return me(e).currentBranch}function UH(e,t){if(!t)return;let i=me(e);if(t.changeBranch!==null&&(!i.isGitWorktree||i.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Xk(e){return F(e.paths,`create portable change ${e.name}`,async()=>{if(!pd.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await Y(e.paths.projectRoot)===null&&await Vt(e.paths.projectRoot,e.initialProjectConfig),UH(e.paths.projectRoot,e.workspaceBinding);let t=(await Sk(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Qa(e.workspaceBinding?.isolation??"current",t);let i=we(e.paths,e.name),r=ze(e.paths,e.name);await Promise.all([T(e.paths.nativeRoot,i),T(e.paths.runtimeDir,r)]);let n=!1,a=!1;try{await di.mkdir(e.paths.changesDir,{recursive:!0}),await di.mkdir(i,{recursive:!1}),n=!0,await di.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await di.mkdir(r,{recursive:!1}),a=!0,await di.mkdir(He.join(i,"specs"),{recursive:!0}),await Ne(He.join(i,"brief.md"),JH);let o=WN({name:e.name,language:e.language,workspace:GH(e.workspaceBinding),createdAt:e.now,nextAction:"confirm-shape"});return await Rs(Ht(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await ce(ae(e.paths,e.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await di.rm(r,{recursive:!0,force:!0}),n&&await di.rm(i,{recursive:!0,force:!0}),o}})}async function K(e,t){return wt(Ht(e,t))}async function dt(e){let t=await Bn({file:Ht(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=He.join(we(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await di.rm(i,{force:!0})}return t}async function Qk(e){let t=we(e.paths,e.state.name),i=He.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await di.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(!pd.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=He.join(t,...s.split("/")),l=await di.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=He.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await di.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Zk(e){let t=we(e.paths,e.state.name),i=await ee({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return mu({briefMarkdown:i.text,specs:r})}async function eS(e){return F(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await Qk({paths:e.paths,state:t}),r=await Zk({paths:e.paths,state:t,specChanges:i}),n=await Us({changeDir:we(e.paths,t.name),acceptanceIds:r.map(({id:s})=>s)});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=Mk({state:{...t,spec_changes:i},acceptance:r.map(s=>({...s}))});if(delete a.children_contract_hash,n){a.children_contract_hash=ed({acceptance:a.acceptance,children:n.contract});let s=[...t.history].reverse().find(({outcome:c})=>c==="pass"||c==="fail");if(s?.outcome==="fail"&&s.unresolved_ids.length>0){let c=await Gt({paths:e.paths,state:a}),l=new Set((c?.children??[]).filter(({status:d})=>d!=="done").flatMap(({covers:d})=>d)),u=s.unresolved_ids.filter(d=>!l.has(d));if(u.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${u.join(", ")}`)}}let o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}async function Zn(e){let t=await Qk(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 Zk({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!qN(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Us({changeDir:we(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?ed({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 gr(e){let t=await Zn(e);if(!t.drifted)return;let i=t.reason??"Native confirmed requirements changed";throw await md({paths:e.paths,state:e.state,reason:i}),new Error(`${i}; Native change returned to Shape and requires confirmation`)}async function tS(e){return F(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(await gr({paths:e.paths,state:t}),await Us({changeDir:we(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a)})||t.children_contract_hash)throw new Error("Native parent Build advances child changes instead of a parent Builder");let r=vm({state:t,input:e.input}),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function iS(e){return F(e.paths,`complete portable parent Build ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.phase!=="build"||t.status!=="active")throw new Error("Native parent integration can only complete from active Build");await gr({paths:e.paths,state:t});let i=await Gt({paths:e.paths,state:t});if(!i||!t.children_contract_hash)throw new Error(`Native change ${t.name} has no confirmed child contract`);if(!i.confirmed)throw new Error("Native parent child declarations require Shape confirmation");if(!i.allDone)throw new Error("Native parent cannot enter Verify before every child is merged");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; add and confirm a repair child");let n=Ys().captureExecutionIdentity({identityProvider:"skill-coordinated",executionRef:`native-parent-integration:${hd()}`}),a=vm({state:t,input:{identity:n,summary:e.summary,addressedAcceptanceIds:t.acceptance.map(({id:s})=>s),checks:[],knownLimits:[]}}),o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}function km(e,t,i){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:id(i,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function rS(e,t,i,r){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...km(t,i,r),executionCount:e.executionCount}}function nS(e,t){let i=He.relative(He.resolve(e),He.resolve(t));if(He.isAbsolute(i)||i===".."||i.startsWith(`..${He.sep}`))throw new Error("Native local check cwd escaped the project root");let r=i.length===0?".":i.split(He.sep).join("/");return id(e,r),r}function bm(e,t){let[i,...r]=e.argv;if(!i)throw new Error(`Native local check ${e.id} has no executable`);return Ks({id:e.id,name:e.id,executable:i,argv:r,cwdRef:nS(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function KH(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function io(e){let t=new Map;for(let i of e.supplied){if(t.has(i.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${i.id}`);t.set(i.id,i)}return e.local.checks.map(i=>{if(i.status==="planned"||i.status==="running")throw new Error(`Native Runtime check ${i.id} has not completed`);let r=e.requestedNames?.get(i.id)??i.name;return{id:i.id,name:de(r),argv_display:um(i.argv.slice(1)).map(n=>de(n)),argv_truncated:!1,cwd_ref:nS(e.projectRoot,i.cwd),status:i.status,exit_code:i.exitCode,duration_ms:KH(i)}})}function YH(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function rc(e){if(e.local===null||e.local.change!==e.state.name)return Be({portableState:e.state,projectRoot:e.projectRoot,branch:Et(e.projectRoot)});let t=e.local.execution?.operationId??hd();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(i=>i.status==="running"||i.status==="planned"?{...i,operationId:t,status:"interrupted"}:{...i,operationId:t})}}async function ro(e){try{let t=await Ci(ae(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function aS(e){let{state:t,local:i,expected:r}=e;if(t.state_version!==r.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==r.iteration||t.loop.attempt!==r.attempt||t.builder_handoff===null||i===null||i.basedOnStateVersion!==t.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return i}function XH(e){let{state:t,local:i,envelope:r}=e;if(!nd(r))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(r.candidateId!==t.builder_handoff.candidate_id||r.identityProvider!==t.builder_handoff.identity_provider||r.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(i===null||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==null&&i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return r}function QH(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function fd(e){let t=await ro({paths:e.paths,state:e.state}),i=Jk({state:e.state,summary:e.summary}),r=await dt({paths:e.paths,previous:e.state,next:i});return await ce(ae(e.paths,e.state.name),rc({local:t,state:r,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),r}function Yk(e,t,i){return e.checks.length!==t.length?!1:e.checks.every((r,n)=>bm(r,i)===Ks(t[n]))}async function ZH(e){return F(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(await gr({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let i=ae(e.paths,t.name),r=(await Nm({file:i,portableState:t,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(r.execution?.stage==="checking"&&r.execution.actor==="runtime"&&Yk(r,e.plans,e.paths.projectRoot)){let o=r.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=r.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:u})=>[l,u]));return{kind:"reuse",state:t,checks:io({local:r,projectRoot:e.paths.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=ec({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(u=>!u.repeatable).map(({id:u})=>u).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await dt({paths:e.paths,previous:t,next:c});throw await ce(ae(e.paths,t.name),Be({portableState:l,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(u=>!u.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(r.execution!==null&&r.checks.length>0){if(!(r.execution.stage==="checking"&&r.execution.actor==="runtime"&&r.checks.some(s=>s.status==="interrupted")&&Yk(r,e.plans,e.paths.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(r.execution!==null||r.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=hd(),a={...r,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=r.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?rS(s,o,n,e.paths.projectRoot):s?{...s,operationId:n}:km(o,n,e.paths.projectRoot)})};return await ce(i,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=r.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function ud(e){return F(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await K(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let i=ae(e.paths,t.name),r=await Ci(i);if(r===null||r.basedOnStateVersion!==t.state_version||r.execution?.operationId!==e.operationId||r.execution.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(r);return await ce(i,n,{containedRoot:e.paths.runtimeDir}),n})}async function oS(e){if(new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let t=[],i=new Set;for(let s of e.plans){rd(e.paths.projectRoot,s);let c=Ks(s);i.has(c)||(i.add(c),t.push(s))}let r=await ZH({...e,plans:t});if(r.kind==="reuse")return r;let n=r.local.execution.operationId,a=ze(e.paths,r.state.name);try{for(let s of r.plans){let c=new Date().toISOString();await ud({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:c}:d)})});let l=await dm({projectRoot:e.paths.projectRoot,runtimeDir:a,operationId:n,plan:s});await ud({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:l.status,exitCode:l.exitCode,startedAt:l.startedAt,completedAt:l.completedAt,log:l.logRef}:d)})})}await ud({paths:e.paths,state:r.state,operationId:n,update:s=>({...s,execution:{...s.execution,status:"completed"}})})}catch(s){try{await ud({paths:e.paths,state:r.state,operationId:n,update:c=>({...c,execution:{...c.execution,status:"interrupted"},checks:c.checks.map(l=>l.status==="planned"||l.status==="running"?{...l,status:"interrupted"}:l)})})}catch{}throw s}let o=await Ci(ae(e.paths,r.state.name));if(o===null)throw new Error("Native Runtime check state disappeared after execution");return{state:r.state,checks:io({local:o,projectRoot:e.paths.projectRoot,supplied:[]})}}async function eD(e){let t=ae(e.paths,e.state.name),i=e.local;if(i===null||i.change!==e.state.name||i.basedOnStateVersion!==e.state.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(i.execution.executionId!==null&&i.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(i.execution.requestCheckRounds>=pm)throw new Error(`Native Verifier request-checks exceeded ${pm} rounds for this attempt`);let r=new Map,n=new Map,a=new Map;for(let h of i.checks){let m=bm(h,e.paths.projectRoot);n.set(m,h),h.status!=="interrupted"&&r.set(m,h),a.set(h.id,m)}let o=new Map,s=new Map;for(let h of e.response.checks){let m=YH(h);rd(e.paths.projectRoot,m);let p=Ks(m),v=s.get(m.id);if(v!==void 0&&v!==p)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let g=a.get(m.id);if(g!==void 0&&g!==p)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,p);let y=n.get(p);if(y?.status==="interrupted"&&!y.repeatable)throw new Error(`Native check ${y.id} was interrupted and is not repeatable; user resolution is required`);o.has(p)||o.set(p,m)}let c=[...o.entries()],l=c.filter(([h])=>!r.has(h));if(i.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=i.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),f={...i,execution:{...i.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...i.checks.map(h=>{let m=bm(h,e.paths.projectRoot),p=o.get(m);return p&&h.status==="interrupted"?rS(h,p,i.execution.operationId,e.paths.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>km(h,i.execution.operationId,e.paths.projectRoot))]};return await ce(t,f,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:f,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>r.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function dd(e){return F(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await K(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let i=ae(e.paths,t.name),r=await Ci(i),n=r?.execution;if(r===null||r.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(r);return await ce(i,a,{containedRoot:e.paths.runtimeDir}),a})}async function tD(e){let t;try{for(let i of e.reservation.novelPlans){let r=new Date().toISOString();t=await dd({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:r}:o)})});let n=await dm({projectRoot:e.paths.projectRoot,runtimeDir:ze(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:i});t=await dd({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await dd({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(i){try{await dd({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,status:"interrupted"},checks:r.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw i}return{checks:io({local:t,projectRoot:e.paths.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:i})=>i)}}}async function sS(e){return F(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=(await Nm({file:ae(e.paths,t.name),portableState:t,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");io({local:i,projectRoot:e.paths.projectRoot,supplied:e.checks});let r=Bk(t),n=await dt({paths:e.paths,previous:t,next:r}),a=ae(e.paths,t.name),o=hd();return await ce(a,{...i,basedOnStateVersion:n.state_version,execution:{operationId:o,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(s=>({...s,operationId:o}))},{containedRoot:e.paths.runtimeDir}),n})}async function cS(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await F(e.paths,`apply portable verifier ${e.name}`,async()=>{let i=await K(e.paths,e.name);await gr({paths:e.paths,state:i});let r=await ro({paths:e.paths,state:i}),n=XH({state:i,local:r,envelope:e.envelope}),a;try{a=hm(n.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await fd({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${Zs} was recorded`,{cause:u})}let o=QH(a);if(o.iteration!==i.loop.iteration||o.attempt!==i.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let s=[],c;try{r!==null&&(s=io({local:r,projectRoot:e.paths.projectRoot,supplied:e.checks}));let u=Lk({state:i,envelope:n,checks:s,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(r===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await eD({paths:e.paths,state:i,local:r,envelope:n,response:u.response,suppliedChecks:s});return{kind:"request-checks",state:i,response:u.response,reservation:d}}if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==n.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");c=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await fd({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${Zs} was recorded`,{cause:u})}let l=await dt({paths:e.paths,previous:i,next:c.state});return await ce(ae(e.paths,i.name),l.loop.next_action==="resolve-verifier-blocker"?rc({local:r,state:l,projectRoot:e.paths.projectRoot}):Be({portableState:l,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),l.verification!==null&&await vr({file:He.join(we(e.paths,i.name),"verification.md"),state:l}),{kind:"final-result",result:{state:l,response:c.response,checks:s,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let i=await tD({paths:e.paths,reservation:t.reservation});return{state:t.state,response:t.response,checks:i.checks,requestChecks:i.requestChecks}}catch(i){let r=`Native Verifier response was invalid: ${i.message}`,n=await F(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await K(e.paths,e.name);return a.state_version!==t.state.state_version?null:fd({paths:e.paths,state:a,summary:r})});throw new Error(n?`${r}; execution error ${n.loop.execution_failure_count}/${Zs} was recorded`:`${r}; the portable state changed before the execution error could be recorded`,{cause:i})}}async function lS(e){return F(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await ro({paths:e.paths,state:t});if(aS({state:t,local:i,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return fd({paths:e.paths,state:t,summary:e.summary})})}async function uS(e){return F(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=await ro({paths:e.paths,state:t}),r=aS({state:t,local:i,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=io({local:r,projectRoot:e.paths.projectRoot,supplied:[]}),a=Vk({state:t,checks:n,verifierExecutionRef:r.execution.executionId,summary:e.summary}),o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),rc({local:r,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:o}),o})}async function dS(e){return F(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=qk(t),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function fS(e){return F(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=Wk({state:t,summary:e.summary}),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function hS(e){return F(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=await ro({paths:e.paths,state:t}),r=zk(t),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),rc({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function pS(e){return F(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await ro({paths:e.paths,state:t}),r=Gk(t),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),rc({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function no(e){return F(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await K(e.paths,e.name);if(t.phase==="build")return t;let i=ec({state:t,reason:e.reason}),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}async function mS(e){if(!pd.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return F(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await K(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i=t.spec_changes.filter(({capability:a})=>a!==e.capability),r={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...i,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function vS(e){return F(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await K(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 dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function nc(e){return F(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await K(e.paths,e.name);return t.phase==="shape"?t:md({paths:e.paths,state:t,reason:e.reason})})}async function md(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...ri(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:de(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 dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function vd(e){if(e.state.verification===null)return"not-applicable";let t=He.join(we(e.paths,e.state.name),"verification.md");return await ic({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await vr({file:t,state:e.state}),"rebuilt")}async function gS(e){let t=await K(e.paths,e.name),i=ae(e.paths,e.name);try{let r=await Ci(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}import{randomUUID as iD}from"crypto";import{promises as ac}from"fs";import yS from"path";var Sm="comet.selection.v2",rD=16*1024;function oc(e){return yS.join(e,".comet","current-change.json")}function nD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function wS(e){return e===null||typeof e=="string"}function NS(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(!nD(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&&!wS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Sm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Sm)throw new Error(`current change selection schema must be ${Sm}`);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(!wS(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 Em(e){let t;try{let r=oc(e),{bytes:n}=await jn(r,rD,{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",...NS(t)}}async function bS(e,t){let i=NS(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=oc(e),n=`${r}.${iD()}.tmp`;await ac.mkdir(yS.dirname(r),{recursive:!0});try{await ac.writeFile(n,`${JSON.stringify(i.selection,null,2)} +`,"utf8"),await ac.rename(n,r)}catch(a){throw await ac.rm(n,{force:!0}),a}}async function kS(e){await ac.rm(oc(e),{force:!0})}async function SS(e,t,i){let r=await Em(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await kS(e),!0)}var UU=16*1024;async function sc(e){let t=await Em(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Un(t.selection.change),t.selection)}function cc(e){return oc(e.projectRoot)}async function gd(e,t){return F(e,`select change ${t}`,async()=>{Un(t),await ke(e,t)?await K(e,t):await je(e,t),await bS(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function ES(e){let t=await sc(e);return t?(await ke(e,t.change)?await K(e,t.change):await je(e,t.change),t.change):null}async function lc(e,t){return await Ia(e.projectRoot),SS(e.projectRoot,"native",t)}var uc=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 Pm(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Rm(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=Pt.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function wd(e){try{return await tt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function PS(e,t){let i=Pt.normalize(Pt.resolve(e)),r=Pt.normalize(Pt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function RS(e,t){let i;try{i=await tt.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=Pt.join(e.archiveDir,n.name);try{let o=await wt(Pt.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 Cm(e,t){let i=await Ha(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function CS(e,t){return await Cm(e,t)!==null||await RS(e,t)!==null}async function ea(e,t){await tt.mkdir(e.transactionsDir,{recursive:!0}),await ve(Vr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function xS(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Zt(e.paths.projectRoot);i.some(a=>PS(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Y(a);if(!o)continue;let s=await re(a,o.native.artifact_root);r.some(c=>PS(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 tt.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 wt(Pt.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 Kn(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 oD(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 sD(e){let t=Pt.join(e.paths.specsDir,e.change.capability),i=Pt.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await tt.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 tt.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([tt.realpath(e.paths.specsDir),tt.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await tt.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await tt.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await tt.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=Pt.join(we(e.paths,e.state.name),e.change.source);await Ne(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await tt.mkdir(t,{recursive:!0}),await Ne(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function xm(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 cD(e,t){let i=we(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await ee({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function lD(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(xm(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Am(e){let t=await K(e.paths,e.name),i=[];try{xm(t)}catch(o){i.push(o.message)}if(await Cm(e.paths,e.name)===null)try{let o=await Zn({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 ic({file:Pt.join(we(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await xS({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:Rm(e.paths,Pm(t)),stateVersion:t.state_version}}async function dc(e){return F(e.paths,`archive portable change ${e.name}`,async()=>{let t=oD(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await Cm(e.paths,e.name),r=we(e.paths,e.name),n=await wd(r),a=n?null:await RS(e.paths,e.name),o;if(n)o=await K(e.paths,e.name);else if(i)o=await wt(Pt.join(Rm(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 Zn({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await md({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=Rm(e.paths,i?.archive_ref??Pm(o)),c=await wd(s);if(i&&lD(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 lc(e.paths,o.name),await tt.rm(ze(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)xm(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await xS({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new uc(l);i={schema:ku,id:aD(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Pm(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await cD(e.paths,o),created_at:new Date().toISOString()},await ea(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await ea(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({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:["comet","native","next",e.name,"--summary","","--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.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","","--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:["comet","native","next",e.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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?["comet","native","next",e.name,"--retry-verifier","--summary",""]: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:["comet","native","next",e.name,"--summary","","--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",""],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",""],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",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{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",""],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:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:""}]:{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 uD}from"node:crypto";import{promises as ao}from"node:fs";import OS from"node:path";var _m=["evidence.md","repair.md","archive.md","checkpoint.md"],dD="verification.md";async function fD(e){try{return await ao.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Tm(e,t){let i=te(e,t),r=[Vr(e,{kind:"migration",change:t}),On(e,t),..._m.map(n=>OS.join(i,n))];return(await Promise.all(r.map(fD))).some(Boolean)}async function hD(e,t){let i=await Ha(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function AS(e,t){await ao.mkdir(e.transactionsDir,{recursive:!0}),await ve(Vr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function _S(e,t,i={}){let r=i.removeVerificationReport===!1?_m:[..._m,dD];await Promise.all([ao.rm(ze(e,t),{recursive:!0,force:!0}),ao.rm(On(e,t),{recursive:!0,force:!0}),...r.map(n=>ao.rm(OS.join(te(e,t),n),{force:!0}))])}async function TS(e,t){await ce(ae(e,t.name),Be({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function IS(e,t){try{let i=await lt(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 jS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=me(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 pD(e){let t=te(e.paths,e.state.name),i=await ee({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 ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return mu({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function $S(e,t){let i=await Kn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function xi(e){return F(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await hD(e.paths,e.name),i=await ke(e.paths,e.name)?await wt(Ht(e.paths,e.name)):null;if(!t&&i)return await _S(e.paths,e.name,{removeVerificationReport:!1}),await TS(e.paths,i),i;let r=null,n=null;for(t||(r=await $S(e.paths,e.name),n=await IS(e.paths,e.name),jS(e.paths,n),t={schema:bu,id:uD(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await AS(e.paths,t));;){let a=JN(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await $S(e.paths,e.name),n??=await IS(e.paths,e.name),jS(e.paths,n),i=zN({state:r,acceptance:await pD({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Rs(Ht(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await _S(e.paths,e.name):a.action==="commit-transaction"&&(i??=await wt(Ht(e.paths,e.name)),await TS(e.paths,i)),t={...t,status:a.nextStatus},await AS(e.paths,t)}return await ao.rm(Vr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??wt(Ht(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as HS}from"node:fs";import DS from"node:path";function mD(e,t){let i=me(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 vD(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function gD(e,t){let i=new Date().toISOString(),r=e.verification===null?e:ri(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:de(t),completed_at:i});return X({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:vD(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 wD(e){try{let t=await Ci(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 ta(e){return F(e.paths,`recover portable change ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.status==="done")return await vd({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=mD(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=ae(e.paths,e.name),n=await wD(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(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await ce(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await vd({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(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=ec({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Bn({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await HS.rm(DS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Be({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await ce(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,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 f=gD(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 Bn({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=Be({portableState:t,projectRoot:e.paths.projectRoot,branch:me(e.paths.projectRoot).currentBranch});return await HS.mkdir(DS.dirname(ae(e.paths,t.name)),{recursive:!0}),await ce(r,d,{containedRoot:e.paths.runtimeDir}),await vd({paths:e.paths,state:t}),{state:t,local:d,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{promises as PD}from"node:fs";import oo from"node:path";import{execFileSync as yD}from"node:child_process";var ND=6e4,bD=8*1024*1024,Im=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 jm(e,t,i={}){let r=i.timeoutMs??ND,n=i.maxBufferBytes??bD;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 yD(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","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 Im(e,t,o,{cause:a})}}import{promises as $m}from"fs";import FS from"path";var MS=["Outcome","Scope","Non-goals","Acceptance examples"],kD=[...MS,"Constraints and invariants","Decisions","Open questions","Verification expectations"],SD=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],BS={maxFileBytes:$o};function LS(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(` +`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function ED(e,t){let i=FS.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await $m.realpath(e),n=await $m.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await $m.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function fc(e){return{valid:e.length===0,findings:e}}async function Om(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:BS.maxFileBytes})).text}catch(o){return fc([{code:"brief-missing",message:o.message,path:t}])}let n=LS(r);for(let o of kD)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of MS)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),fc(i)}async function Hm(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:BS.maxFileBytes})).text}catch(a){return fc([{code:"verification-missing",message:a.message,path:t}])}let n=LS(r);for(let a of SD)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return fc(i)}function ia(e,t){return FS.join(e.specsDir,t,"spec.md")}async function qS(e,t){let i=[],r=te(e,t.name);for(let n of t.spec_changes){let a=ia(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await oi(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await ED(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return fc(i)}var hc=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function RD(e,t){let i=oo.relative(e,t);return i===""||!oo.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${oo.sep}`)}function ra(e,t){let i=oo.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||oo.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function VS(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function WS(e){return e.split("\0").filter(Boolean)}function CD(e,t){return WS(le(e,["ls-files","-z","--",t]))}function xD(e,t){return WS(le(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function AD(e){try{if(le(e,["config","--get","user.name"])&&le(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function _D(e,t){for(let i of Zt(e))if(me(i).currentBranch===t)return i;return null}function TD(e,t){try{jm(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function Dm(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=me(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`);AD(t.projectRoot);let a=[ra(t.projectRoot,cc(t))];e.archiveDir&&a.push(ra(t.projectRoot,te(t,i.name)),ra(t.projectRoot,e.archiveDir));let o=im(t.projectRoot).filter(l=>!VS(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:_D(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(!Gs(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Pk(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&TD("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function ID(e,t){try{return jm("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function jD(e){try{return await PD.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function $D(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function zS(e){let t=$D(e.plan),i=null;try{let r=[ra(e.paths.projectRoot,te(e.paths,e.name)),ra(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>ra(e.paths.projectRoot,ia(e.paths,l.capability))),ra(e.paths.projectRoot,cc(e.paths))],n=im(e.plan.changeRoot).filter(l=>!VS(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=oo.resolve(e.paths.projectRoot,...l.split("/"));if(CD(e.plan.changeRoot,l).length>0&&a.push(l),await jD(u))for(let f of xD(e.plan.changeRoot,l))o.add(f)}if(a.length>0&&le(e.plan.changeRoot,["add","-u","--",...a]),o.size>0&&le(e.plan.changeRoot,["add","--",...o]),le(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&le(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=le(e.plan.changeRoot,["rev-parse","HEAD"]),!Gs(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"){if(le(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=ID(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(u=>/^https?:\/\//u.test(u.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let l=RD(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!l?(le(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"&&(le(c,["switch",e.plan.targetBranch]),i=c),le(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(i!==null){let n;try{le(i,["merge","--abort"])}catch{}try{me(i).currentBranch===e.plan.targetBranch&&le(i,["switch",e.plan.changeBranch]),n=me(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==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new hc(t)}}import Mv from"path";import{promises as KP}from"fs";import Eo from"path";import{isDeepStrictEqual as aL}from"util";import{createHash as OD}from"crypto";function JS(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function GS(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))GS(e[t]);return Object.freeze(e)}function tn(e){return GS(structuredClone(e))}function Fm(e,t,i,r){return e.resolveStep({pkg:tn(t),state:tn(i),context:tn(r)})}function US(e,t,i,r,n,a){return e.resolveNext({pkg:tn(t),state:tn(i),step:tn(r),outcome:tn(n),context:tn(a)})}function HD(e,t,i){return OD("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Mm(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function KS(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Fm(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Mm(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:HD(s.runId,s.iteration,o.id),stepId:o.id};return DD(e,s,c,i)}function DD(e,t,i,r){let n=JS(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function YS(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Fm(r,e,t,n):void 0,o=a?Mm(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?US(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Mm(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as jB}from"node:fs";import $P from"node:path";import XS from"node:path";var FD="comet.native.archive-preflight.v1",MD="comet.native.archive-preflight.v1",BD="comet.native.archive-operation.v1",LD=/^[a-f0-9]{64}$/u,QS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function yd(e,t){return et?1:0}function VD(e,t){if(typeof e!="string"||!LD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wr(e,t){return e===null?null:VD(e,t)}function WD(e,t){let i=XS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||XS.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function zD(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function JD(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function GD(e,t){if(!QS.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=wr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=wr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=wr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function UD(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:wr(e.contractHash,"Native archive contract hash"),acceptanceHash:wr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:wr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:wr(e.reportHash,"Native archive report hash"),envelopeHash:wr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:wr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function KD(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!qD.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(yd);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function YD(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(yd)}function ZS(e){if(!QS.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(GD).sort((l,u)=>yd(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(BD,l)})),r=UD(e.evidence),n=JD(e.workspace),a=[...new Set([...KD(e.findingCodes??[]),...YD({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(yd),o=zD(e.revision),s=WD(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:FD,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(MD,c)}}import{createHash as XD}from"node:crypto";import eE from"node:path";var QD="comet.native.conflict-radar.v1",Dt=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}),ZD="comet.native.conflict-radar.v1",eF="comet.native.conflict-radar-signals.v1",tF=/^[a-f0-9]{64}$/u,rE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,iF=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),rF=new Set(["capability","operation","baseHash"]),nF=new Set(["path","kind"]);function so(e,t){return et?1:0}function Bm(e){return Buffer.byteLength(e,"utf8")}function Lm(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function qm(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Bm(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function aF(e,t){let i=qm(e,t,Dt.maxArtifactPathBytes),r=eE.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||eE.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function nE(e,t){if(typeof e!="string"||!tF.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function oF(e,t){let i=Lm(e,rF,t),r=qm(i.capability,`${t} capability`,Dt.maxCapabilityBytes);if(!rE.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:nE(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function sF(e,t){let i=Lm(e,nF,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:aF(i.path,`${t} path`),kind:i.kind}}function cF(e,t){let i=Lm(e,iF,`Conflict radar change ${t}`),r=qm(i.name,`Conflict radar change ${t} name`,Dt.maxNameBytes);if(!rE.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>Dt.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>Dt.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>oF(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>so(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>sF(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>so(c.path,l.path)||so(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:nE(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function lF(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Dt.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(cF).sort((n,a)=>so(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Dt.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Dt.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function uF(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function dF(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function fF(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function hF(e,t){let i=[],r=XD("sha256").update(`${eF} +[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(ks(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(uF(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=dF(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:fF(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function tE(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function pF(e,t){return tE(e.classification)-tE(t.classification)||so(e.left,t.left)||so(e.right,t.right)}function iE(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:QD,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function aE(e){let t=lF(e),i=[];for(let s=0;s({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D(ZD,{changes:t,relationships:r}),a=i.slice(0,Dt.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=iE(t,i,a,n);for(;a.length>0&&Bm(JSON.stringify(o))>Dt.maxSerializedBytes;)a=a.slice(0,-1),o=iE(t,i,a,n);if(Bm(JSON.stringify(o))>Dt.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as wM}from"node:crypto";import{promises as _i}from"node:fs";import Xi from"node:path";import{createHash as hE}from"node:crypto";import oE from"path";var Vm="comet.native.implementation-scope.v2",pE="comet.native.content-snapshot-projection.v1",pc="comet.native.content-snapshot-projection.v1",mE="comet.native.implementation-scope.v2",mF="comet.native.unresolved-scope-id.v1",vF="comet.native.scope-detail-overflow.v1",gF="comet.native.snapshot-projection-overflow.v2",Gm=/^[a-f0-9]{64}$/u,aa=1024*1024,wF=128,yF=128;function ft(e,t){return et?1:0}function Wm(e){if(!Gm.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function NF(e,t){return e===t?0:e===null?-1:t===null?1:ft(e,t)}function nn(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=oE.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||oE.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function vE(e,t){return e==="."?e:nn(e,t)}function co(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function bF(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:nn(e.path,`${t} path`),hash:e.hash,size:co(e.size,`${t} size`),type:"file"}}function kF(e,t){return{path:vE(e.path,`${t} path`),size:e.size===null?null:co(e.size,`${t} size`),type:e.type,reason:e.reason}}function SF(e,t){return ft(e.path,t.path)||ft(e.hash,t.hash)||e.size-t.size}function EF(e,t){return ft(e.path,t.path)||ft(e.reason,t.reason)||ft(e.type,t.type)||(e.size??-1)-(t.size??-1)}function vc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+` `,"utf8")}function rn(e,t,i){let r=`${t} -${ks(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function bF(e){if(vc(e)<=aa)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=fE("sha256");a.update(`${hF} -`),e.omissionOverflow&&rn(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,rn(a,"omission",f)},s=f=>{r+=1,n+=1,rn(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;vc(u)>aa;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let m=0;m0){let h=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-h))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function Wm(e){let t=fr(e),i=t.entries.map((n,a)=>gF(n,`Snapshot entry ${a}`));if(i.sort(yF),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>wF(n,`Snapshot omission ${a}`));return r.sort(NF),bF({schema:hE,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function gc(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:nn(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>ft(i.path,r.path)||ft(i.kind,r.kind))}function wc(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function oE(e){return e?{hash:e.hash,size:e.size}:null}function Gm(e,t,i){let r=0,n=0;for(;r=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:oE(c),after:oE(l)})}}function vE(e,t){return{...e,attributedTo:t.filter(i=>wc(i,e.path))}}function Um(e){let t=gc(e.declaredArtifacts),i=[];return Gm(e.baseline,e.current,r=>{i.push(vE(r,t))}),i}function yr(e,t){return{id:`scope:${D(dF,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function kF(e,t){let i=t.omitted.map(r=>yr({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(yr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(yr({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function sE(e,t){return kF(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function zm(e,t){return ft(e.kind,t.kind)||ft(e.source,t.source)||vF(e.path,t.path)||ft(e.id,t.id)}function SF(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(zm)}function gE(e){return[...new Set(e.map((t,i)=>nn(t,`Git path ${i}`)))].sort(ft)}function cE(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function EF(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function wE(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=gE(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:cE(e.baseCommit,"Native external drift base commit"),targetBranch:EF(e.targetBranch,"Native external drift target branch"),targetCommit:cE(e.targetCommit,"Native external drift target commit"),paths:t}}function yE(e){if(typeof e.contractHash!="string"||!Jm.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:gc(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:gE(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:wE(e.externalDrift)}}}function PF(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Gm(e,t,h=>{let m=i.some(p=>wc(p,h.path));if(d+=1,c.push(h.path),!m&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length{if(i>=e.detailedChangeCount){rn(t,"change",n);let a=0;for(let o of e.declaredArtifacts)wc(o,n.path)&&(a+=1,rn(t,"change-attribution",o));rn(t,"change-end",{attributionCount:a}),a===0&&rn(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&rn(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function bE(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=PF(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(L=>wc(L,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(pc,e),c=D(pc,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=mF)break;l.push(yr({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...sE("baseline",e),...sE("current",t),...o.totalChanges===0&&a===null?[yr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},m=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(vi=>vi.attributedTo.length===0&&!u.has(vi.path)),P=o.totalChanges-N.length,L=o.totalUnattributed-w.length,H=d-R.detailedOmissionCount,nt=L+H,Pe=[...w.map(vi=>yr({kind:"unattributed-change",source:"implementation-scope",path:vi.path,evidence:{after:vi.after,before:vi.before,changeKind:vi.kind}},`Changed path is not covered by a declared artifact: ${vi.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...nt>0?[NE(R.overflowHash,{changes:P,unattributed:L,unresolved:nt})]:[]],fe=SF(Pe),Oi=R.includeGitAdvisory?h():void 0;return{schema:qm,contractHash:r,baselineProjectionRef:Vm(s),baselineProjectionHash:s,currentProjectionRef:Vm(c),currentProjectionHash:c,complete:fe.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:fe,noCodeReason:a,...Oi?{gitAdvisory:Oi}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,v=l.length,g=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:y});if(vc({...R,scopeHash:y})<=aa)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>p||d>v?CF({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:v}):y,k=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:S}),b={...k,scopeHash:D(pE,k)};if(vc(b)>aa)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Km(e){let t=Wm(e.baseline),i=Wm(e.current),r=yE(e);return{authority:r,baseline:t,current:i,scope:bE(t,i,r)}}var xF=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function Ki(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function na(e,t){if(typeof e!="string"||!Jm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function lE(e,t,i){let r=Vm(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function lo(e,t){let i=Ki(e,"Native snapshot projection");if(Yi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==hE)throw new Error("Native snapshot projection schema is invalid");let r=fr({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=Wm(r);if(D(pc,i)!==D(pc,n))throw new Error("Native snapshot projection is not canonical");let a=D(pc,n);if(t!==void 0&&na(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Ym(e,t){let i=Ki(e,`Declared artifact ${t}`);if(Yi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:nn(i.path,`Declared artifact ${t} path`),kind:i.kind}}function uE(e,t){if(e===null)return null;let i=Ki(e,t);return Yi(i,["hash","size"],[],t),{hash:na(i.hash,`${t} hash`),size:co(i.size,`${t} size`)}}function dE(e,t){let i=Ki(e,`Implementation change ${t}`);if(Yi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Ym),n=gc(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=uE(i.before,`Implementation change ${t} before`),o=uE(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:nn(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function AF(e,t){let i=Ki(e,`Unresolved scope ${t}`);Yi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?mE(i.path,`Unresolved scope ${t} path`):nn(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function mc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>nn(n,`${t} ${a}`)),r=[...new Set(i)].sort(ft);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function kE(e){let t=Ki(e,"Native implementation external drift");if(Yi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=mc(t.paths,"Native external drift paths");return wE({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function uo(e){let t=Ki(e,"Native implementation scope"),i=[...xF].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(Yi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==qm)throw new Error("Native implementation scope schema is invalid");let r=na(t.contractHash,"Implementation scope contractHash"),n=na(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=lE(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=na(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=lE(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Ym);if(JSON.stringify(c)!==JSON.stringify(gc(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(dE),u=[...l].sort((w,P)=>ft(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>wc(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(dE),h=t.externalDrift===void 0?void 0:kE(t.externalDrift),m=new Set(h?.paths??[]),p=l.filter(w=>w.attributedTo.length===0&&!m.has(w.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(AF),g=v.filter(w=>w.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=g[0]===void 0?null:RF(g[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,S=[...p.map(w=>yr({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&E===null?[yr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=v.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(zm))||new Set(v.map(w=>w.id)).size!==v.length||JSON.stringify(k)!==JSON.stringify(S.sort(zm))||t.complete!==(v.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=Ki(t.gitAdvisory,"Implementation scope Git advisory");if(Yi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=mc(w.changedPaths,"Git changed paths"),L=mc(w.pathsPresentInSnapshotChanges,"Git present paths"),H=mc(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),nt=[...L,...H].sort(ft);if(JSON.stringify(nt)!==JSON.stringify(P)||H.some(Pe=>l.some(fe=>fe.path===Pe)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:L,pathsAbsentFromSnapshotChanges:H}}let R={schema:qm,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:E,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},N=na(t.scopeHash,"Implementation scope scopeHash");if(D(pE,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function _F(e){let t=Ki(e,"Native implementation scope authority");if(Yi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Ym);if(JSON.stringify(i)!==JSON.stringify(gc(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=mc(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:kE(t.externalDrift),a=yE({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function yc(e){let t=Ki(e,"Native implementation scope bundle");Yi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=_F(t.authority),r=lo(t.baseline),n=lo(t.current),a=uo(t.scope),o=bE(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function SE(e){let t=uo(e.scope);return yc({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import EE from"node:path";var RE=/^[a-f0-9]{64}$/u;var TF="comet.native.acceptance-trace.v2",IF="comet.native.partial-allowance.v1",jF="comet.native.verification-evidence.v2";function Nr(e,t){if(!RE.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function CE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function xE(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Xm(e,t,i=2e3){let r=St(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Nc(e,t){let i=EE.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||EE.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function $F(e,t,i){let r=Nc(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=Hi(r),a=r.toLowerCase(),o=i?Nc(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Qm(e){let t=Nc(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function fo(e,t){return et?1:0}function Nd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bd(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function AE(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function PE(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function OF(e){let t=Nd(e,"Native acceptance trace");if(bd(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!RE.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Nc(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Nd(o,`Native acceptance trace entry ${s}`);if(bd(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Qm(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(fo))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Nc(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Xm(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>fo(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Nr(t.traceHash,"Native acceptance trace hash");if(D(TF,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function kd(e){let t=Nd(e,"Native partial allowance");if(bd(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(fo))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:xE(t.change),scopeHash:Nr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Xm(t.reason,"Partial allowance reason"),confirmedSummary:Xm(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:CE(t.sourceRevision),confirmedAt:AE(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Nr(t.allowanceHash,"Native partial allowance hash");if(D(IF,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function bc(e){let t=Nd(e,"Native verification evidence");if(bd(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Nr(t.implementationScopeHash,"Native verification implementation scope hash"),r=OF(t.acceptanceTrace),n=Nr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Nr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Qm(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(fo)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(fo);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Qm(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(fo)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:xE(t.change),sourceRevision:CE(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Nr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:PE(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:$F(t.reportRef,"Native verification report ref"),reportHash:Nr(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:PE(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:AE(t.createdAt,"Native verification timestamp")},d=Nr(t.envelopeHash,"Native verification envelope hash");if(D(jF,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import _E from"node:path";var TE="comet.native.check-receipt.v1",HF="comet.native.check-receipt.v1",ho="scoped-text-safety",Zm=1,Ft=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),DF=/^[a-f0-9]{64}$/u,FF=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MF="comet.native.checker-policy.v1",BF="comet.native.check-input.v1",LF=2048,IE=D(MF,{policy:ho,version:Zm,limits:Ft,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),qF=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),jE=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],OE=["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"],VF=new Set(OE);function an(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function on(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function br(e,t){if(typeof e!="string"||!DF.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function HE(e,t){let i=Yt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function $E(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function WF(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>LF||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=_E.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||_E.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function zF(e){let t=an(e,"Native check receipt checker");on(t,["policy","version","hash","limits"],"Native check receipt checker");let i=an(t.limits,"Native check receipt limits");if(on(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ho||t.version!==Zm||t.hash!==IE||i.maxFiles!==Ft.maxFiles||i.maxFileBytes!==Ft.maxFileBytes||i.maxTotalBytes!==Ft.maxTotalBytes||i.maxIssues!==Ft.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ho,version:Zm,hash:IE,limits:{...Ft}}}function JF(e){let t=an(e,"Native check receipt contract");return on(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:br(t.expectedHash,"Native check expected contract hash"),beforeHash:br(t.beforeHash,"Native check before contract hash"),afterHash:br(t.afterHash,"Native check after contract hash")}}function GF(e){let t=an(e,"Native check receipt implementation");return on(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:br(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:br(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:br(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:br(t.afterSnapshotHash,"Native check after snapshot hash")}}function UF(e,t){let i=an(e,`Native check batch ${t}`);on(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Yt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Yt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Yt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Yt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Yt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Yt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Ft.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Ft.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function KF(e){let t=an(e,"Native check receipt counts");on(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Yt(t.filesSelected,"Native check filesSelected"),filesScanned:Yt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Yt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Yt(t.bytesScanned,"Native check bytesScanned"),issueCount:Yt(t.issueCount,"Native check issueCount"),recordedIssueCount:Yt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(UF):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ft.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Ft.maxFiles||i.bytesScanned>Ft.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function YF(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||jE.indexOf(e.kind)-jE.indexOf(t.kind)}function XF(e){if(!Array.isArray(e)||e.length>Ft.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=an(r,`Native check issue ${n}`);if(on(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!qF.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:WF(a.path,`Native check issue ${n} path`),line:HE(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(YF);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function QF(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!VF.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=OE.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function ZF(e){return D(BF,e)}function Sd(e){let t=an(e,"Native check receipt");if(on(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==TE)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!FF.test(t.change))throw new Error("Native check receipt change name is invalid");let i=HE(t.sourceRevision,"Native check source revision"),r=zF(t.checker),n=JF(t.contract),a=GF(t.implementation),o=ZF({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(br(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=$E(t.startedAt,"Native check receipt startedAt"),c=$E(t.endedAt,"Native check receipt endedAt");if(cu.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=QF(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ft.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Ft.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:TE,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=br(t.receiptHash,"Native check receipt content hash");if(D(HF,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}var tv="comet.native.verification-receipt.v3",eM=tv,tM="comet.native.declared-artifacts.v1",iM=/^[a-f0-9]{64}$/u,rM=/^acceptance-[a-f0-9]{64}$/u,nM=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aM=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,oM=4096,sM=256,cM=1024;function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function sn(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function kr(e,t){if(typeof e!="string"||!iM.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ai(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=St(e).trim();if(!i||i.length>oM||i!==e.trim())throw new Error(`${t} is invalid`);return i}function ev(e,t){let i=Ai(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function kc(e,t,i=Ai,r=!1,n=sM){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function lM(e,t){if(typeof e!="string"||!rM.test(e))throw new Error(`${t} is invalid`);return e}function uM(e){let t=po(e,"Native verification receipt bindings");if(sn(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!nM.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:kr(t.contractHash,"Native verification receipt contract hash"),scopeHash:kr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:kr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:kr(t.artifactHash,"Native verification receipt artifact hash")}}function dM(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=aM.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function fM(e,t,i,r){let n=po(t,`Native ${e} evidence`);if(e==="automated-check"){if(sn(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=ev(n.startedAt,"Native automated-check start time"),o=ev(n.endedAt,"Native automated-check end time");if(Date.parse(o)({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var BE=/^[a-f0-9]{64}$/u,cn=aa,qY=3*cn;function rv(e,t){let i=Xi.relative(e,t);return i===""||!Xi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xi.sep}`)}function mM(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pd(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function DE(e){let t=await _i.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await _i.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function vM(e,t){let i=Xi.resolve(e),r=Xi.resolve(t);if(!rv(i,r))throw new Error("Native evidence path is outside its change");let n=[await DE(i)],a=i;for(let o of Xi.relative(i,r).split(Xi.sep).filter(Boolean)){a=Xi.join(a,o);let s=await DE(a);if(!rv(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function FE(e){for(let t of e){let i=await _i.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!mM(t,i)||await _i.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function gM(e,t,i={}){let r=await vM(t,Xi.dirname(e));await i.afterParentChainCaptured?.();let n=await _i.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await _i.realpath(e);if(!rv(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await _i.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),_i.lstat(e),_i.realpath(e)]);if(await FE(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Pd(s,n)||!Pd(s,c))throw new Error("Native evidence document changed while opening");if(s.size>cn)throw new Error(`Native evidence document exceeds ${cn} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=cn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>cn)throw new Error(`Native evidence document exceeds ${cn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await i.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),_i.lstat(e),_i.realpath(e)]);if(await FE(r),!m.isFile()||m.isSymbolicLink()||p!==a||!Pd(s,h)||!Pd(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function vo(e,t){if(!BE.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function LE(e){return vo("reports",e)}async function wM(e,t,i,r,n){if(!BE.test(i))throw new Error("Native report evidence hash is invalid");let a=await oa({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||pM("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function mo(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function yM(e,t,i,r,n){let a=vo(i,r);return n?Xi.join(n,...a.split("/")):Lr(M(e,t),a)}async function oa(e){let t=yM(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),gM(t,i,e.hooks)}function ME(e,t){return lo(e,t)}function NM(e,t){let i=uo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function bM(e,t,i){let r=kd(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function kM(e,t,i){let r=bc(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function SM(e,t,i,r=!1,n){let a=await Rd(e,t,i.implementationScopeRef,void 0,n);if(r&&await wM(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await qE(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Sc(e,t,i,r,n){let a=mo(i,"scopes"),o=NM(await oa({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=mo(o.baselineProjectionRef,"snapshots"),c=mo(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([oa({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ME(d,s)),oa({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ME(d,c))]);return SE({baseline:l,current:u,scope:o})}async function Rd(e,t,i,r,n){return(await Sc(e,t,i,r,n)).scope}async function qE(e,t,i,r,n){let a=mo(i,"allowances");return bM(await oa({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Ec(e,t,i,r,n){let a=mo(i,"receipts"),o=Ed(await oa({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function go(e,t,i,r,n){let a=mo(i,"verifications"),o=kM(await oa({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await SM(e,t,o,!1,n),o}var EM=4096;async function PM(e,t=Dt.maxChanges){try{let i=await $t({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function VE(e,t){let i=await je(e,t),[r,n]=await Promise.all([i.implementation_scope?Rd(e,t,i.implementation_scope):null,lt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Cd(e,t,i={}){let n=(await PM(e,EM)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await VE(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await VE(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=nE([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as qM}from"fs";import VM from"path";import{isDeepStrictEqual as _d}from"util";var wo={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var RM=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function CM(e,t){return et?1:0}function xM(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!RM.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(CM)}function nv(e=[]){return xM(e,"Native repair failed check IDs",wo.maxFailedCheckIds,!0)}function WE(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function AM(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:WE(e.failedAcceptanceIds,t.failedAcceptanceIds)&&WE(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length=0;n-=1){let a=t[n];if(AM(r,a))break;i+=1,r=a}return i}function xd(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var zE="repairStagnation",Xt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},TM=/^[a-f0-9]{64}$/u;var IM=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),jM=["data","runId","sequence","timestamp","type"],JE=["disposition","overrideSummaryHash","signatureHash"],$M=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],GE=12;function sv(e,t){return et?1:0}function UE(e,t,i){let r=Object.keys(e).sort(sv);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Ad(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Pc(e,t){if(typeof e!="string"||!TM.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function OM(e){if(!Array.isArray(e)||e.length>wo.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(sv)}function KE(e){if(typeof e!="string"||e.length===0||e.length>Xt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function ov(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Xt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Xt.maxTextCharacters&&(!n||e.length>Xt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Xt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Xt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>ov(s,t+1,i,`${r}[${c}]`));return}let a=Ad(e,r),o=Object.keys(a);if(o.length>Xt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Xt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");ov(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function HM(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function DM(e,t,i){let r=Ad(e,`Native repair trajectory event ${t+1}`);if(UE(r,jM,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(HM(r.timestamp),typeof r.type!="string"||!IM.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(KE(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return ov(r.data,0,n,"Native trajectory event data"),Ad(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function cv(e){let t=Ad(e,"Native repair trajectory projection"),i=Object.keys(t).sort(sv),r=i.length===JE.length&&i.every((l,u)=>l===JE[u]);r||UE(t,$M,"Native repair trajectory projection");let n=Pc(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Pc(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Pc(t.contractHash,"Native repair trajectory contract hash"),s=OM(t.failedAcceptanceIds),c=nv(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function FM(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function MM(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??GE;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=av({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":aa.kind==="failure"),n=i?.maxVerifyFailures??GE;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function YE(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=KE(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;lXt.maxTotalDataNodes||c>Xt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Pc(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Pc(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,zE)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=cv(f[zE]);if(FM(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),MM(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");BM(m,i,r);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(r=m,i.length>wo.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function XE(e){return YE(e).history}function QE(e){let t=YE(e).latestProjection;return t?{...t}:null}var Qi={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:[]},Rc=B("comet-native-runtime:v3:scope-reopen"),LM=[{skillVersion:"3",skillHash:B("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];function ZE(e){return e.skillVersion===Qi.definition.metadata.version&&e.skillHash===Rc||LM.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var lv={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function ln(e){let i={sequence:(await kt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Yb(e.changeDir,e.run.trajectoryRef,i),i}async function sa(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:B(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Xb(e.changeDir,e.run.checkpointRef,t),t}function eP(e){return B(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var cP=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],WM=new Set(cP),lP=new Set([...cP,"minimum_runtime_version","revision"]),zM=new Set([...lP,"operation"]),JM=512*1024,uv=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),GM=new Set([...uv,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Cc=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ht(e,t){return VM.join(M(e,t),"transition.json")}function UM(e){return`transition-${e}`}async function KM(e,t,i){let r=UM(t);return cr(e,r,i)}async function un(e,t,i,r){let n=await KM(e,t,i);try{return await r()}finally{await lr(n)}}function Id(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function fv(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Td(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zi(e,t){return _d(e,t)}function dv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!GM.has(u)),a=[...uv].find(u=>!Object.hasOwn(i,u)),o=uv.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(xd(i.summary,"Native transition journal event summary"),St(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(xd(i.noCodeReason,"Native transition journal event no-code reason"),St(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?cv(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function YM(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return dv({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return dv(e,t)}function hv(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?YM(e.eventData,e.evidenceHash):dv(e.eventData,e.evidenceHash),n=Qr(e.nextRun),a=e.previousRun===null?null:Qr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function tP(e,t,i=!1){if(e.skill!==Qi.definition.metadata.name||(i?!ZE(e):e.skillVersion!==Qi.definition.metadata.version||e.skillHash!==Rc)||e.orchestration!==Qi.definition.orchestration.mode||e.pendingRef!==zt.pendingRef||e.trajectoryRef!==zt.trajectoryRef||e.contextRef!==zt.contextRef||e.artifactsRef!==zt.artifactsRef||e.checkpointRef!==zt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function iP(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function rP(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function pv(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(tP(o,"next Run",r||a!==null),rP(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(tP(a,"previous Run",!0),rP(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!_d(iP(a),iP(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function XM(e,t,i){return B(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function uP(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function nP(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function mv(e,t,i,r,n=!1){let a=i.eventData,o=nP(e),s=nP(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&_d(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&_d(e.spec_changes,t.spec_changes),l=eP({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=XM(e.name,a.summary,t.spec_changes),l=B(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function vv(e,t){let i=Id(e);if(fv(i,zM),i.schema!==qr)throw new Error(`Expected Native transition schema ${qr}`);let r=Td(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${qr} minimum_runtime_version must be ${3}`);let n=Td(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=hv(i,t),o=jt(i.previousState),s=jt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(mv(o,s,a,i.operation),pv(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:qr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function QM(e,t){let i=Id(e);if(fv(i,WM),i.schema!==Ln)throw new Error(`Expected Native transition schema ${Ln}`);let r=hv(i,t,!0),n=qn(i.previousState),a=qn(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return mv(n,a,r,uP(n,a,r.eventData),!0),pv(n,a,r,!0),{schema:Ln,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function gv(e,t){let i=Id(e);if(fv(i,lP),i.schema!==dr)throw new Error(`Expected Native transition schema ${dr}`);if(Td(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${dr} minimum_runtime_version must be 2`);let n=Td(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=hv(i,t,!0),o=Vi(i.previousState),s=Vi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(mv(o,s,a,uP(o,s,a.eventData),!0),pv(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:dr,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function ZM(e,t){let i=Id(e);if(i.schema===qr)return{status:"current",journal:vv(i,t)};if(i.schema===Ln)return{status:"migration-required",journal:QM(i,t)};if(i.schema===dr)return{status:"migration-required",journal:gv(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function wv(e,t){let i=ht(e,t),r=j(e,i);await T(r,i);try{let n=await ge({root:r,file:i,maxBytes:JM,label:`Native transition journal ${t}`});return ZM(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Sr(e,t){let i=await wv(e,t);if(!i)return null;if(i.status==="migration-required")throw new Cc(t);return i.journal}function aP(e,t){if(Zi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Zi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function oP(e,t){if(Zi(e,t.nextState))return"next";if(Zi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function eB(e){let{journal:t}=e;return dP({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function dP(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function sP(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=eB({sequence:a.index+1,journal:t,type:a.event.type});if(!Zi(dP(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function xc(e,t,i){if(await eo(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Gu(e,t);let r=await Sr(e,t);if(!r)return null;let n=M(e,t),a=sP(await kt(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Je(n),je(e,t)]),c=aP(o,r),l=oP(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Jn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!Zi(await Je(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let v=await Js(e,r.nextState,r.previousState.revision);if(!Zi(v,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!Zi(await je(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Sr(e,t);if(!u||!Zi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=sP(await kt(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await ln({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await ln({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await sa({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,m]=await Promise.all([Je(n),je(e,t)]);aP(h,{...r,previousRun:r.nextRun}),oP(m,{...r,previousState:r.nextState});let p=await Sr(e,t);if(!p||!Zi(p,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await qM.rm(ht(e,t),{force:!0}),r.nextState}async function fP(e,t,i){return F(e,`continue transition ${t}`,()=>un(e,t,`continue transition ${t}`,()=>xc(e,t,i)))}import hP from"node:path";var tB="comet.native.contract.v1",iB="comet.native.acceptance-set.v1",pP=/^[a-f0-9]{64}$/u,Ac={maxAcceptanceCriteria:Es.maxCriteria};function mP(e,t){let i=hP.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||hP.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function vP(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,` -`))}function rB(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(pP))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(pP))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=mP(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:vP(e.markdown)},markdown:e.markdown}}function nB(e,t){return gP(e.id,t.id)}function gP(e,t){return et?1:0}function wP(e){let t=mP(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(rB).sort((d,f)=>gP(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=fu(e.briefMarkdown,t,Ac.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...hu(f,d.source,Ac.maxAcceptanceCriteria-a.length)),a.push(...pu(f,d.source,Ac.maxAcceptanceCriteria-a.length)));if(a.sort(nB),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ac.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ac.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:vP(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(iB,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(tB,u)}}var Ti={maxSpecs:64,maxFileBytes:$o,maxTotalBytes:4*1024*1024};async function yo(e){if(e.specChanges.length>Ti.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ee({root:e.changeDir,ref:e.briefRef,maxBytes:Ti.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ee({root:e.changeDir,ref:n.source,maxBytes:Ti.maxFileBytes});if(i+=a.size,i>Ti.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:wP({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as NB}from"node:child_process";import{promisify as bB}from"node:util";import{promises as dB}from"fs";import No from"path";var fn={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},bo=/^[a-f0-9]{64}$/u;function jd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $d(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function dn(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function yP(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function yv(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function aB(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||No.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=No.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Nv(e,t){return No.join(M(e,t),"checkpoints","progress.json")}function hn(e,t){return No.join(M(e,t),"checkpoint-journal.json")}function bv(e,t,i){if(!bo.test(i))throw new Error("Native checkpoint manifest hash is invalid");return No.join(M(e,t),"checkpoints","manifests",`${i}.json`)}function oB(e){if(!bo.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function kv(e,t,i){let r=await ge({root:e,file:t,maxBytes:fn.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function sB(e,t){let i=jd(e,`checkpoint manifest artifact ${t}`);$d(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=aB(dn(i.path,`checkpoint artifact ${t} path`,4096)),n=Hi(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!bo.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:yv(i.size,`checkpoint artifact ${t} size`)}}function Od(e,t){let i=jd(e,"Native checkpoint manifest");if($d(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>fn.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(sB),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=yv(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>fn.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Sv(e){return B(JSON.stringify(Od(e,e.change)))}function Ev(e,t){let i=jd(e,"Native progress checkpoint");if($d(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=yP(i.previousRevision,"Native checkpoint previousRevision"),a=yP(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=dn(i.manifestHash,"Native checkpoint manifestHash",64);if(!bo.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=oB(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=dn(i.inputHash,"Native checkpoint inputHash",64);if(!bo.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=dn(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=yv(i.artifactCount,"Native checkpoint artifactCount");if(u>fn.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=dn(i.summary,"Native checkpoint summary"),f=dn(i.nextAction,"Native checkpoint nextAction");if(St(d)!==d||St(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:dn(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function cB(e,t){let i=jd(e,"Native checkpoint journal");if($d(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=jt(i.previousState),n=jt(i.nextState),a=Ev(i.checkpoint,t),o=Od(i.manifest,t),s=dn(i.inputHash,"Native checkpoint journal inputHash",64),c=B(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!bo.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Sv(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function lB(e,t,i){let r=No.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=pf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ge({root:e.projectRoot,file:r,maxBytes:fn.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function uB(e,t){let i=Nv(e,t),r=j(e,i);await T(r,i);try{return Ev(await kv(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Pv(e,t,i){let r=bv(e,t,i),n=j(e,r);await T(n,r);let a=await kv(n,r,"Native checkpoint manifest"),o=Od(a,t);if(Rv(e,o),Sv(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function pn(e,t){let i=hn(e,t),r=j(e,i);await T(r,i);try{let n=cB(await kv(r,i,"Native checkpoint journal"),t);return Rv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function NP(e,t,i,r){let n=Od(i,t);Rv(e,n);let a=Sv(n),o=bv(e,t,a),s=j(e,o);await T(s,o);try{let c=await Pv(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ve(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function Rv(e,t){for(let i of t.artifacts){let r=pf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function bP(e,t){let i=Ev(t,t.change),r=await Pv(e,i.change,i.manifestHash),n=B(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Nv(e,t.change),o=j(e,a);await T(o,a),await ve(a,i,{containedRoot:o})}async function kP(e){let t;try{t=await uB(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Nv(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Pv(e.paths,e.name,t.manifestHash);let a=B(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await lB(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:bv(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function SP(e,t,i){let r=await pn(e,t);if(!r)return null;if(await NP(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Js(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await bP(e,r.checkpoint),await i?.afterProgressWritten?.(r),await dB.rm(hn(e,t),{force:!0}),r}async function EP(e,t,i){return F(e,`continue checkpoint ${t}`,()=>un(e,t,`continue checkpoint ${t}`,async()=>(await xc(e,t),SP(e,t,i))))}import{constants as Cv,promises as fi}from"node:fs";import ko from"node:path";var fB=/^[a-f0-9]{64}$/u,hB=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,_c=512*1024;function pB(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Hd(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mB(e,t){let i=ko.resolve(e),r=ko.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...ko.relative(i,r).split(ko.sep).filter(Boolean)]){o&&(a=ko.join(a,o));let s=await fi.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await fi.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function PP(e){for(let t of e){let i=await fi.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pB(t,i)||await fi.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function vB(e){if(!fB.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function gB(e){let t=hB.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function wB(e,t,i){return Lr(M(e,t),vB(i))}async function yB(e,t,i){let r=await mB(i,ko.dirname(e)),n=await fi.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>_c)throw new Error(`Native check receipt exceeds ${_c} bytes`);let[a,o]=await Promise.all([fi.realpath(t),fi.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Cv.O_RDONLY|Cv.O_NOFOLLOW|Cv.O_NONBLOCK,c=await fi.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),fi.lstat(e),fi.realpath(e)]);if(await PP(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Hd(n,l)||!Hd(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let y=_c+1-h,E=await c.read(m,0,Math.min(m.length,y),null);if(E.bytesRead===0)break;if(h+=E.bytesRead,h>_c)throw new Error(`Native check receipt exceeds ${_c} bytes`);f.push(Buffer.from(m.subarray(0,E.bytesRead)))}let[p,v,g]=await Promise.all([c.stat(),fi.lstat(e),fi.realpath(e)]);if(await PP(r),!v.isFile()||v.isSymbolicLink()||g!==o||!$(a,g)||!Hd(l,p)||!Hd(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function RP(e,t,i){let r=gB(i),n=M(e,t),a=wB(e,t,r),o=j(e,a);await T(o,a);let s=Sd(await yB(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Tc=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var H4=64*1024;var D4=3600*1e3;var F4=bB(NB);var kB=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function xP(e,t){let i=[];for(let r of kB){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function AP(e){if(e.receipt.kind!=="static-inspection")return null;let t=await RP(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mn=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}};function SB(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function EB(e){let t=SB(e.bundle.baseline),i=await qp(e.paths,t,{origin:"explicit",now:e.now});return Km({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function TP(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Sc(e.paths,e.state.name,e.state.implementation_scope),i=await yo({changeDir:te(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await EB({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function IP(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await TP(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function PB(e){let t=await ee({root:te(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:DN(t.text)}}function RB(e){let{receipt:t,implementationScope:i}=e,r=[],n=Um({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function CB(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:iv(e.implementationScope.scope.declaredArtifacts)}}async function _P(e){let t=await Ec(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=xP(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mn([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await AP({paths:e.paths,state:e.state,receipt:t});if(n){let a=RB({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function xB(e){let t=CB({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await _P({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mn)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await _P({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mn)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mn(i)}function xv(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Dd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:xv(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([TP(e),go(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:xv(e.state.verification_result,"stale"),envelope:null};let r=await PB({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await xB({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:xv(e.state.verification_result,"invalid"),envelope:null}}}function _B(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function $P(e){try{return await AB.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function TB(e,t){try{return(await ee({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function IB(e,t,i){let r=ia(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=jP.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await TB(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ee({root:te(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function jB(e,t){return $P(ht(e,t))}async function Fd(e){let t=e.now??new Date,i=await je(e.paths,e.name),r=await lt(e.paths,e.name),n=await Y(e.paths.projectRoot),a=_B(i.name,t),o=jP.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(m=>IB(e.paths,i.name,m))),Dd({paths:e.paths,state:i,now:t}),Cd(e.paths,i.name),eo(e.paths,i.name),to(e.paths,i.name),jB(e.paths,i.name),$P(o)]);return QS({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Av}from"node:fs";import Er from"node:path";var $B="comet.native.archive-tree.v1",OB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function DP(e){let t={...OB,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function OP(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function HP(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function FP(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await $t({root:e,directory:t,label:`Native Archive content directory ${Er.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=OP(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Er.join(t,u.name),f=Er.relative(e,d).replaceAll("\\","/"),h=await Av.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){HP(i,{ref:f,kind:"directory"},r,n),await FP(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ge({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=m.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);HP(i,{ref:f,kind:"file",hash:m.hash,size:m.size},r,n),await o.verify()}await o.verify();let l=await $t({root:e,directory:t,label:`Native Archive content directory ${Er.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(OP(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Er.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function MP(e,t={}){let i=DP(t);e=Er.resolve(e);let r=await Av.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await FP(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return B(`${$B}\0${o}`)}async function Ii(e,t={}){let i=DP(t);e=Er.resolve(e);let r;try{r=await Av.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ge({root:Er.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Er.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await MP(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Rt}from"node:fs";import We from"node:path";var Tv=16*1024*1024,HB=256*1024,DB=16*1024,Ic="comet.native.archive-cas.v1";function FB(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=We.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function it(e,t){let i=FB(e,t);return T(j(e,i),i)}function vn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function So(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function Mt(e){let t=await Ii(e.target);if(!vn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${So(t)}`);return t}async function Iv(e,t){let i=await zi(e,t),r=await ge({root:e.runtimeDir,file:i.journal,maxBytes:HB,label:`Native Archive transaction journal ${t}`}),n=Au(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Md(e,t,i){let r=Au({...t,status:i}),n=await zi(e,r.id);return await ve(n.journal,r,{containedRoot:e.runtimeDir}),r}function Bd(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function BP(e){return{...Bd(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function gn(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function MB(e,t){return gn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pe(e){try{return await Rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function er(e){let t=await Rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=BP(t),r=await ge({root:j(e.paths,e.file),file:e.file,maxBytes:Tv,label:e.label}),n=await Rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!MB(i,BP(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Bd(n),size:r.size}}function BB(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==Ic||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Ic,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function tr(e,t,i,r){let n=await zi(e,t.id),a=We.join(n.backups,".cas"),o=`.${We.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:We.join(a,`${i.id}.original.json`),postRecord:We.join(a,`${i.id}.post.json`),candidate:We.join(a,`${i.id}.candidate`),originalQuarantine:We.join(We.dirname(r),`${o}.original`),rollbackQuarantine:We.join(We.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function hi(e){if(!await pe(e.file))return null;let t=await ge({root:e.paths.runtimeDir,file:e.file,maxBytes:DB,label:`Archive CAS ${e.operation.id} ${e.role} record`});return BB(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Ld(e){let t=await hi(e);if(t){if(!gn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Wi({root:e.paths.runtimeDir,directory:We.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Ic,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ve(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await hi(e);if(!r||!gn(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Le(e){let t=await er({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!gn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function LB(e){let t=await er({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Ld({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Le({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function qB(e){if(!await pe(e.quarantine)||await pe(e.target))return;let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Rt.lstat(e.quarantine),Rt.lstat(e.target)]);if(!gn(Bd(i),Bd(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Rt.unlink(e.quarantine),await t.verify()}async function WP(e){if(await pe(e.quarantine)){await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Rt.rename(e.target,e.quarantine),await t.verify(),await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await qB(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function ca(e){if(!await pe(e.file))return;await Le(e);let t=await Wt({root:j(e.paths,e.file),directory:We.dirname(e.file),label:e.label});await t.verify(),await Le(e),await Rt.unlink(e.file),await t.verify()}async function LP(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await it(e,t.target),n=await it(e,t.backup),a=await Ii(n);if(a!==null){if(!vn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await Mt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Jr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Tv,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await Mt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function zP(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await tr(e.paths,e.journal,e.operation,e.target),r=await hi({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await pe(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Le({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await LP(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await pe(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await LB({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Le({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await LP(e.paths,e.operation,e.hooks),await WP({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function qP(e){let t=await tr(e.paths,e.journal,e.operation,e.target);return await pe(t.candidate)?(await er({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Wi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Jr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Tv,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function VB(e){let t=e.operation.stagedHash,i=await tr(e.paths,e.journal,e.operation,e.target),r=await hi({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await pe(e.target))return await Le({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await pe(i.candidate)&&await ca({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await pe(e.target)){let c=await qP(e),l=await er({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await er({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!gn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Ld({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await ca({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await qP(e),a=await er({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Wi({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Le({paths:e.paths,file:n,operation:e.operation,record:{schema:Ic,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await er({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!gn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Ld({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await ca({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function WB(e,t,i,r){let n=await it(e,i.target),a=await it(e,i.staged);if(await Mt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await tr(e,t,i,n);(!await hi({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await pe(n))&&await zP({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Ii(n);if(o!==null&&!vn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${So(o)}`)}await VB({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await Mt({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function zB(e,t,i,r){let n=await it(e,i.target);await zP({paths:e,journal:t,operation:i,target:n,hooks:r}),await Mt({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function JB(e,t){let i=await it(e,t.source),r=await it(e,t.target),[n,a]=await Promise.all([Ii(i),Ii(r)]);if(!(n===null&&vn(a,t.expectedSourceHash,"directory"))){if(!vn(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${So(n)}, target=${So(a)}`);await Rt.mkdir(We.dirname(r),{recursive:!0}),await Rt.rename(i,r),await Mt({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function GB(e,t,i,r){return i.type==="write"?WB(e,t,i,r):i.type==="remove"?zB(e,t,i,r):JB(e,i)}function UB(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function KB(e,t,i,r){let n=await it(e,i.target);if(i.type==="write"){let a=await it(e,i.staged);await Mt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await tr(e,t,i,n),s=await hi({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Le({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await Mt({target:await it(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await hi({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await pe(o.originalQuarantine))await Le({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await Mt({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await Mt({target:await it(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await tr(e,t,i,n),o=await hi({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await pe(a.originalQuarantine))await Le({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await Mt({target:await it(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await Mt({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function JP(e,t,i){let r=t.status==="prepared"?await Md(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Ur(e,r.id),a=UB({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await KB(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await ai(e,r.id,"operation-started",l.id),await GB(e,r,l,i),await ai(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Iv(e,r.id),r}async function YB(e){try{return await Le(e),!0}catch{return!1}}async function XB(e){await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function _v(e){if(e.operation.type!=="write")return;let t=await tr(e.paths,e.journal,e.operation,e.target);if(!await pe(t.candidate))return;let i=await er({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await ca({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Ic,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function QB(e,t,i,r){let n=await it(e,i.target),a=await tr(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await hi({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await hi({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await pe(a.candidate)&&await pe(n)){let l=await er({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await er({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});gn(l.identity,u.identity)&&(c=await Ld({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await pe(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Le({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await pe(n)&&!(s!==null&&await YB({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Ii(n);if(vn(u,o)){await _v({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await WP({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await pe(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await pe(n)){if(!s||!await pe(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await XB({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await pe(a.originalQuarantine)&&await ca({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await pe(a.rollbackQuarantine)&&await ca({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await _v({paths:e,journal:t,operation:i,target:n}),await Mt({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function ZB(e,t){let i=await it(e,t.source),r=await it(e,t.target),[n,a]=await Promise.all([Ii(i),Ii(r)]);if(!(vn(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!vn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${So(n)}, target=${So(a)}`);await Rt.mkdir(We.dirname(i),{recursive:!0}),await Rt.rename(r,i)}}async function GP(e,t,i){let r=await Ur(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Md(e,t,"rolling-back");await ai(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await ZB(e,o):await QB(e,n,o,i));return await ai(e,n.id,"rollback-completed"),n=await Md(e,n,"rolled-back"),n}async function VP(e,t,i){let r=await it(e,i.target);if(i.type==="write"){let n=await tr(e,t,i,r),a=await hi({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Le({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await Mt({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function eL(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await it(e,i.target),n=await tr(e,t,i,r);if(await pe(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await VP(e,t,i),i.expectedTargetHash!==null){let a=await hi({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await pe(n.originalQuarantine)&&await ca({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await _v({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await VP(e,t,i)}async function qd(e,t,i){return i==="commit"&&await eL(e,t),await ai(e,t.id,i),i==="commit"?Md(e,t,"committed"):t}var T9=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var o8=16*1024*1024,Vd=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"},jc=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"};function KP(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Eo.resolve(e.nativeRoot,...i.target.split("/"))}async function YP(e,t,i){let r=await Ur(e,t.id);if(r.some(v=>v.type==="archive-finalized"))return;let n=r.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(y=>y.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await Ii(KP(e,t));if(g?.kind!=="directory"||g.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=KP(e,t),o=Eo.join(a,Ve),s=await bk(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=M(e,s.name),l=await Je(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let v=US(Qi,l,new Set,lv,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=KS(Qi,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},lv,void 0)}let d=B(`archive:${t.id}:${s.name}`),f=await kt(c,u.trajectoryRef),h=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let m=h.find(v=>v.type==="state_transitioned"),p={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(m&&t.schema==="comet.native.transaction.v2"&&(!tL(m.data,p)||m.runId!==u.runId||m.timestamp!==t.createdAt||m!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await qd(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await La(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await Nk(o,v)}m||(m=await ln({changeDir:c,run:u,type:"state_transitioned",data:p,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await sa({changeDir:c,run:u,trajectoryOffset:m.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Jn(c,u),await lc(e,s.name),t.schema==="comet.native.transaction.v2"?await qd(e,t,"archive-finalized"):await La(e,t,"archive-finalized")}async function jv(e,t){let i=ze(e,t);try{let r=await UP.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await UP.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function iL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Ur(e,t.id)).some(c=>c.type==="operation-started")){let c=await Fd({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new jc(c,"Native Archive facts changed before the first transaction operation")}let o=await JP(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await je(e,t.change),u=await Dd({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await YP(e,o,i);let s=await qd(e,o,"commit");return{journal:s,runtimeCleanupWarning:await jv(e,s.change)}}let r=await db(e,t);await YP(e,r,i);let n=await La(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await jv(e,n.change):null}}function rL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Eo.resolve(t.projectRoot)!==Eo.resolve(e.projectRoot)||Eo.resolve(t.nativeRoot)!==Eo.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function XP(e){return F(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await cr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await Ot(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Iv(e.paths,e.transactionId):i;return rL(e.paths,r),r.status==="committed"?(r.change&&await jv(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await iL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?GP(e.paths,r):Tu(e.paths,r)}finally{await lr(t)}},{allowedTransactionId:e.transactionId})}import{promises as $c}from"node:fs";import pt from"node:path";var wn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};function $v(e,t){let i=pt.normalize(e),r=pt.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function eR(e,t){let i=pt.relative(e,t);return i===""||!pt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${pt.sep}`)}function QP(e){return JSON.stringify(e.native)}async function Wd(e,t){let i=await Y(e);if(i&&t){if(QP(i)!==QP(t))throw new Error(`Native worktree configuration differs from the source project: ${pt.join(e,".comet","config.yaml")}`);return!1}return!i&&t?(await Vt(e,t),!0):!1}async function nL(e,t){if(!eR(e,t))return!1;let r=`/${pt.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=he(e,["rev-parse","--git-common-dir"]),a=pt.resolve(e,n),o=pt.join(a,"info","exclude"),s="";try{s=await $c.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(r))return!1;await $c.mkdir(pt.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(` +${ks(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function PF(e){if(vc(e)<=aa)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=hE("sha256");a.update(`${gF} +`),e.omissionOverflow&&rn(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,rn(a,"omission",f)},s=f=>{r+=1,n+=1,rn(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;vc(u)>aa;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let m=0;m0){let h=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-h))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function zm(e){let t=fr(e),i=t.entries.map((n,a)=>bF(n,`Snapshot entry ${a}`));if(i.sort(SF),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>kF(n,`Snapshot omission ${a}`));return r.sort(EF),PF({schema:pE,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function gc(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:nn(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>ft(i.path,r.path)||ft(i.kind,r.kind))}function wc(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function sE(e){return e?{hash:e.hash,size:e.size}:null}function Um(e,t,i){let r=0,n=0;for(;r=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:sE(c),after:sE(l)})}}function gE(e,t){return{...e,attributedTo:t.filter(i=>wc(i,e.path))}}function Km(e){let t=gc(e.declaredArtifacts),i=[];return Um(e.baseline,e.current,r=>{i.push(gE(r,t))}),i}function yr(e,t){return{id:`scope:${D(mF,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function RF(e,t){let i=t.omitted.map(r=>yr({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(yr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(yr({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function cE(e,t){return RF(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Jm(e,t){return ft(e.kind,t.kind)||ft(e.source,t.source)||NF(e.path,t.path)||ft(e.id,t.id)}function CF(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Jm)}function wE(e){return[...new Set(e.map((t,i)=>nn(t,`Git path ${i}`)))].sort(ft)}function lE(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function xF(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function yE(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=wE(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:lE(e.baseCommit,"Native external drift base commit"),targetBranch:xF(e.targetBranch,"Native external drift target branch"),targetCommit:lE(e.targetCommit,"Native external drift target commit"),paths:t}}function NE(e){if(typeof e.contractHash!="string"||!Gm.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:gc(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:wE(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:yE(e.externalDrift)}}}function AF(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Um(e,t,h=>{let m=i.some(p=>wc(p,h.path));if(d+=1,c.push(h.path),!m&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length{if(i>=e.detailedChangeCount){rn(t,"change",n);let a=0;for(let o of e.declaredArtifacts)wc(o,n.path)&&(a+=1,rn(t,"change-attribution",o));rn(t,"change-end",{attributionCount:a}),a===0&&rn(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&rn(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function kE(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=AF(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(L=>wc(L,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(pc,e),c=D(pc,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=yF)break;l.push(yr({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...cE("baseline",e),...cE("current",t),...o.totalChanges===0&&a===null?[yr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},m=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(vi=>vi.attributedTo.length===0&&!u.has(vi.path)),P=o.totalChanges-N.length,L=o.totalUnattributed-w.length,H=d-R.detailedOmissionCount,nt=L+H,Pe=[...w.map(vi=>yr({kind:"unattributed-change",source:"implementation-scope",path:vi.path,evidence:{after:vi.after,before:vi.before,changeKind:vi.kind}},`Changed path is not covered by a declared artifact: ${vi.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...nt>0?[bE(R.overflowHash,{changes:P,unattributed:L,unresolved:nt})]:[]],he=CF(Pe),Oi=R.includeGitAdvisory?h():void 0;return{schema:Vm,contractHash:r,baselineProjectionRef:Wm(s),baselineProjectionHash:s,currentProjectionRef:Wm(c),currentProjectionHash:c,complete:he.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:he,noCodeReason:a,...Oi?{gitAdvisory:Oi}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,v=l.length,g=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:y});if(vc({...R,scopeHash:y})<=aa)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>p||d>v?TF({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:v}):y,k=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:S}),b={...k,scopeHash:D(mE,k)};if(vc(b)>aa)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Ym(e){let t=zm(e.baseline),i=zm(e.current),r=NE(e);return{authority:r,baseline:t,current:i,scope:kE(t,i,r)}}var IF=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function Ki(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function na(e,t){if(typeof e!="string"||!Gm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uE(e,t,i){let r=Wm(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function lo(e,t){let i=Ki(e,"Native snapshot projection");if(Yi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==pE)throw new Error("Native snapshot projection schema is invalid");let r=fr({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=zm(r);if(D(pc,i)!==D(pc,n))throw new Error("Native snapshot projection is not canonical");let a=D(pc,n);if(t!==void 0&&na(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Xm(e,t){let i=Ki(e,`Declared artifact ${t}`);if(Yi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:nn(i.path,`Declared artifact ${t} path`),kind:i.kind}}function dE(e,t){if(e===null)return null;let i=Ki(e,t);return Yi(i,["hash","size"],[],t),{hash:na(i.hash,`${t} hash`),size:co(i.size,`${t} size`)}}function fE(e,t){let i=Ki(e,`Implementation change ${t}`);if(Yi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Xm),n=gc(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=dE(i.before,`Implementation change ${t} before`),o=dE(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:nn(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function jF(e,t){let i=Ki(e,`Unresolved scope ${t}`);Yi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?vE(i.path,`Unresolved scope ${t} path`):nn(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function mc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>nn(n,`${t} ${a}`)),r=[...new Set(i)].sort(ft);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function SE(e){let t=Ki(e,"Native implementation external drift");if(Yi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=mc(t.paths,"Native external drift paths");return yE({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function uo(e){let t=Ki(e,"Native implementation scope"),i=[...IF].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(Yi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Vm)throw new Error("Native implementation scope schema is invalid");let r=na(t.contractHash,"Implementation scope contractHash"),n=na(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=uE(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=na(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=uE(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Xm);if(JSON.stringify(c)!==JSON.stringify(gc(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(fE),u=[...l].sort((w,P)=>ft(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>wc(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(fE),h=t.externalDrift===void 0?void 0:SE(t.externalDrift),m=new Set(h?.paths??[]),p=l.filter(w=>w.attributedTo.length===0&&!m.has(w.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(jF),g=v.filter(w=>w.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=g[0]===void 0?null:_F(g[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,S=[...p.map(w=>yr({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&E===null?[yr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=v.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(Jm))||new Set(v.map(w=>w.id)).size!==v.length||JSON.stringify(k)!==JSON.stringify(S.sort(Jm))||t.complete!==(v.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=Ki(t.gitAdvisory,"Implementation scope Git advisory");if(Yi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=mc(w.changedPaths,"Git changed paths"),L=mc(w.pathsPresentInSnapshotChanges,"Git present paths"),H=mc(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),nt=[...L,...H].sort(ft);if(JSON.stringify(nt)!==JSON.stringify(P)||H.some(Pe=>l.some(he=>he.path===Pe)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:L,pathsAbsentFromSnapshotChanges:H}}let R={schema:Vm,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:E,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},N=na(t.scopeHash,"Implementation scope scopeHash");if(D(mE,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function $F(e){let t=Ki(e,"Native implementation scope authority");if(Yi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Xm);if(JSON.stringify(i)!==JSON.stringify(gc(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=mc(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:SE(t.externalDrift),a=NE({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function yc(e){let t=Ki(e,"Native implementation scope bundle");Yi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=$F(t.authority),r=lo(t.baseline),n=lo(t.current),a=uo(t.scope),o=kE(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function EE(e){let t=uo(e.scope);return yc({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import PE from"node:path";var CE=/^[a-f0-9]{64}$/u;var OF="comet.native.acceptance-trace.v2",HF="comet.native.partial-allowance.v1",DF="comet.native.verification-evidence.v2";function Nr(e,t){if(!CE.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function xE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function AE(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Qm(e,t,i=2e3){let r=St(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Nc(e,t){let i=PE.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||PE.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function FF(e,t,i){let r=Nc(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=Hi(r),a=r.toLowerCase(),o=i?Nc(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Zm(e){let t=Nc(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function fo(e,t){return et?1:0}function Nd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bd(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function _E(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function RE(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function MF(e){let t=Nd(e,"Native acceptance trace");if(bd(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!CE.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=Nc(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Nd(o,`Native acceptance trace entry ${s}`);if(bd(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Zm(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(fo))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Nc(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Qm(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>fo(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Nr(t.traceHash,"Native acceptance trace hash");if(D(OF,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function kd(e){let t=Nd(e,"Native partial allowance");if(bd(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(fo))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:AE(t.change),scopeHash:Nr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Qm(t.reason,"Partial allowance reason"),confirmedSummary:Qm(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:xE(t.sourceRevision),confirmedAt:_E(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Nr(t.allowanceHash,"Native partial allowance hash");if(D(HF,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function bc(e){let t=Nd(e,"Native verification evidence");if(bd(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Nr(t.implementationScopeHash,"Native verification implementation scope hash"),r=MF(t.acceptanceTrace),n=Nr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Nr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Zm(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(fo)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(fo);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Zm(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(fo)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:AE(t.change),sourceRevision:xE(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Nr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:RE(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:FF(t.reportRef,"Native verification report ref"),reportHash:Nr(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:RE(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:_E(t.createdAt,"Native verification timestamp")},d=Nr(t.envelopeHash,"Native verification envelope hash");if(D(DF,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import TE from"node:path";var IE="comet.native.check-receipt.v1",BF="comet.native.check-receipt.v1",ho="scoped-text-safety",ev=1,Ft=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),LF=/^[a-f0-9]{64}$/u,qF=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VF="comet.native.checker-policy.v1",WF="comet.native.check-input.v1",zF=2048,jE=D(VF,{policy:ho,version:ev,limits:Ft,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),JF=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),$E=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],HE=["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"],GF=new Set(HE);function an(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function on(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function br(e,t){if(typeof e!="string"||!LF.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function DE(e,t){let i=Yt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function OE(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function UF(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>zF||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=TE.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||TE.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function KF(e){let t=an(e,"Native check receipt checker");on(t,["policy","version","hash","limits"],"Native check receipt checker");let i=an(t.limits,"Native check receipt limits");if(on(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ho||t.version!==ev||t.hash!==jE||i.maxFiles!==Ft.maxFiles||i.maxFileBytes!==Ft.maxFileBytes||i.maxTotalBytes!==Ft.maxTotalBytes||i.maxIssues!==Ft.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ho,version:ev,hash:jE,limits:{...Ft}}}function YF(e){let t=an(e,"Native check receipt contract");return on(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:br(t.expectedHash,"Native check expected contract hash"),beforeHash:br(t.beforeHash,"Native check before contract hash"),afterHash:br(t.afterHash,"Native check after contract hash")}}function XF(e){let t=an(e,"Native check receipt implementation");return on(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:br(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:br(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:br(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:br(t.afterSnapshotHash,"Native check after snapshot hash")}}function QF(e,t){let i=an(e,`Native check batch ${t}`);on(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Yt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Yt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Yt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Yt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Yt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Yt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Ft.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Ft.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function ZF(e){let t=an(e,"Native check receipt counts");on(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Yt(t.filesSelected,"Native check filesSelected"),filesScanned:Yt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Yt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Yt(t.bytesScanned,"Native check bytesScanned"),issueCount:Yt(t.issueCount,"Native check issueCount"),recordedIssueCount:Yt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(QF):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ft.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Ft.maxFiles||i.bytesScanned>Ft.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function eM(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||$E.indexOf(e.kind)-$E.indexOf(t.kind)}function tM(e){if(!Array.isArray(e)||e.length>Ft.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=an(r,`Native check issue ${n}`);if(on(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!JF.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:UF(a.path,`Native check issue ${n} path`),line:DE(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(eM);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function iM(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!GF.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=HE.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function rM(e){return D(WF,e)}function Sd(e){let t=an(e,"Native check receipt");if(on(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==IE)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!qF.test(t.change))throw new Error("Native check receipt change name is invalid");let i=DE(t.sourceRevision,"Native check source revision"),r=KF(t.checker),n=YF(t.contract),a=XF(t.implementation),o=rM({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(br(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=OE(t.startedAt,"Native check receipt startedAt"),c=OE(t.endedAt,"Native check receipt endedAt");if(cu.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=iM(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ft.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Ft.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:IE,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=br(t.receiptHash,"Native check receipt content hash");if(D(BF,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}var iv="comet.native.verification-receipt.v3",nM=iv,aM="comet.native.declared-artifacts.v1",oM=/^[a-f0-9]{64}$/u,sM=/^acceptance-[a-f0-9]{64}$/u,cM=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lM=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,uM=4096,dM=256,fM=1024;function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function sn(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function kr(e,t){if(typeof e!="string"||!oM.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ai(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=St(e).trim();if(!i||i.length>uM||i!==e.trim())throw new Error(`${t} is invalid`);return i}function tv(e,t){let i=Ai(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function kc(e,t,i=Ai,r=!1,n=dM){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function hM(e,t){if(typeof e!="string"||!sM.test(e))throw new Error(`${t} is invalid`);return e}function pM(e){let t=po(e,"Native verification receipt bindings");if(sn(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!cM.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:kr(t.contractHash,"Native verification receipt contract hash"),scopeHash:kr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:kr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:kr(t.artifactHash,"Native verification receipt artifact hash")}}function mM(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=lM.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function vM(e,t,i,r){let n=po(t,`Native ${e} evidence`);if(e==="automated-check"){if(sn(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=tv(n.startedAt,"Native automated-check start time"),o=tv(n.endedAt,"Native automated-check end time");if(Date.parse(o)({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var LE=/^[a-f0-9]{64}$/u,cn=aa,JY=3*cn;function nv(e,t){let i=Xi.relative(e,t);return i===""||!Xi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xi.sep}`)}function yM(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pd(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function FE(e){let t=await _i.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await _i.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function NM(e,t){let i=Xi.resolve(e),r=Xi.resolve(t);if(!nv(i,r))throw new Error("Native evidence path is outside its change");let n=[await FE(i)],a=i;for(let o of Xi.relative(i,r).split(Xi.sep).filter(Boolean)){a=Xi.join(a,o);let s=await FE(a);if(!nv(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ME(e){for(let t of e){let i=await _i.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!yM(t,i)||await _i.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function bM(e,t,i={}){let r=await NM(t,Xi.dirname(e));await i.afterParentChainCaptured?.();let n=await _i.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await _i.realpath(e);if(!nv(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await _i.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),_i.lstat(e),_i.realpath(e)]);if(await ME(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Pd(s,n)||!Pd(s,c))throw new Error("Native evidence document changed while opening");if(s.size>cn)throw new Error(`Native evidence document exceeds ${cn} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=cn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>cn)throw new Error(`Native evidence document exceeds ${cn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await i.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),_i.lstat(e),_i.realpath(e)]);if(await ME(r),!m.isFile()||m.isSymbolicLink()||p!==a||!Pd(s,h)||!Pd(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function vo(e,t){if(!LE.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function qE(e){return vo("reports",e)}async function kM(e,t,i,r,n){if(!LE.test(i))throw new Error("Native report evidence hash is invalid");let a=await oa({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||wM("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function mo(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function SM(e,t,i,r,n){let a=vo(i,r);return n?Xi.join(n,...a.split("/")):Lr(M(e,t),a)}async function oa(e){let t=SM(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),bM(t,i,e.hooks)}function BE(e,t){return lo(e,t)}function EM(e,t){let i=uo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function PM(e,t,i){let r=kd(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function RM(e,t,i){let r=bc(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function CM(e,t,i,r=!1,n){let a=await Rd(e,t,i.implementationScopeRef,void 0,n);if(r&&await kM(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await VE(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Sc(e,t,i,r,n){let a=mo(i,"scopes"),o=EM(await oa({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=mo(o.baselineProjectionRef,"snapshots"),c=mo(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([oa({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>BE(d,s)),oa({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>BE(d,c))]);return EE({baseline:l,current:u,scope:o})}async function Rd(e,t,i,r,n){return(await Sc(e,t,i,r,n)).scope}async function VE(e,t,i,r,n){let a=mo(i,"allowances");return PM(await oa({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Ec(e,t,i,r,n){let a=mo(i,"receipts"),o=Ed(await oa({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function go(e,t,i,r,n){let a=mo(i,"verifications"),o=RM(await oa({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await CM(e,t,o,!1,n),o}var xM=4096;async function AM(e,t=Dt.maxChanges){try{let i=await $t({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function WE(e,t){let i=await je(e,t),[r,n]=await Promise.all([i.implementation_scope?Rd(e,t,i.implementation_scope):null,lt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Cd(e,t,i={}){let n=(await AM(e,xM)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await WE(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await WE(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=aE([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as JM}from"fs";import GM from"path";import{isDeepStrictEqual as _d}from"util";var wo={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var _M=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function TM(e,t){return et?1:0}function IM(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!_M.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(TM)}function av(e=[]){return IM(e,"Native repair failed check IDs",wo.maxFailedCheckIds,!0)}function zE(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function jM(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:zE(e.failedAcceptanceIds,t.failedAcceptanceIds)&&zE(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length=0;n-=1){let a=t[n];if(jM(r,a))break;i+=1,r=a}return i}function xd(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var JE="repairStagnation",Xt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},OM=/^[a-f0-9]{64}$/u;var HM=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),DM=["data","runId","sequence","timestamp","type"],GE=["disposition","overrideSummaryHash","signatureHash"],FM=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],UE=12;function cv(e,t){return et?1:0}function KE(e,t,i){let r=Object.keys(e).sort(cv);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Ad(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Pc(e,t){if(typeof e!="string"||!OM.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MM(e){if(!Array.isArray(e)||e.length>wo.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(cv)}function YE(e){if(typeof e!="string"||e.length===0||e.length>Xt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function sv(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Xt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Xt.maxTextCharacters&&(!n||e.length>Xt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Xt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Xt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>sv(s,t+1,i,`${r}[${c}]`));return}let a=Ad(e,r),o=Object.keys(a);if(o.length>Xt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Xt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");sv(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function BM(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function LM(e,t,i){let r=Ad(e,`Native repair trajectory event ${t+1}`);if(KE(r,DM,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(BM(r.timestamp),typeof r.type!="string"||!HM.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(YE(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return sv(r.data,0,n,"Native trajectory event data"),Ad(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function lv(e){let t=Ad(e,"Native repair trajectory projection"),i=Object.keys(t).sort(cv),r=i.length===GE.length&&i.every((l,u)=>l===GE[u]);r||KE(t,FM,"Native repair trajectory projection");let n=Pc(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Pc(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Pc(t.contractHash,"Native repair trajectory contract hash"),s=MM(t.failedAcceptanceIds),c=av(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function qM(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function VM(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??UE;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=ov({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":aa.kind==="failure"),n=i?.maxVerifyFailures??UE;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function XE(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=YE(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;lXt.maxTotalDataNodes||c>Xt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Pc(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Pc(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,JE)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=lv(f[JE]);if(qM(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),VM(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");WM(m,i,r);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(r=m,i.length>wo.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function QE(e){return XE(e).history}function ZE(e){let t=XE(e).latestProjection;return t?{...t}:null}var Qi={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:[]},Rc=B("comet-native-runtime:v3:scope-reopen"),zM=[{skillVersion:"3",skillHash:B("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];function eP(e){return e.skillVersion===Qi.definition.metadata.version&&e.skillHash===Rc||zM.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var uv={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function ln(e){let i={sequence:(await kt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Xb(e.changeDir,e.run.trajectoryRef,i),i}async function sa(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:B(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Qb(e.changeDir,e.run.checkpointRef,t),t}function tP(e){return B(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var lP=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],UM=new Set(lP),uP=new Set([...lP,"minimum_runtime_version","revision"]),KM=new Set([...uP,"operation"]),YM=512*1024,dv=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),XM=new Set([...dv,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Cc=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ht(e,t){return GM.join(M(e,t),"transition.json")}function QM(e){return`transition-${e}`}async function ZM(e,t,i){let r=QM(t);return cr(e,r,i)}async function un(e,t,i,r){let n=await ZM(e,t,i);try{return await r()}finally{await lr(n)}}function Id(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function hv(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Td(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zi(e,t){return _d(e,t)}function fv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!XM.has(u)),a=[...dv].find(u=>!Object.hasOwn(i,u)),o=dv.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(xd(i.summary,"Native transition journal event summary"),St(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(xd(i.noCodeReason,"Native transition journal event no-code reason"),St(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?lv(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function eB(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return fv({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return fv(e,t)}function pv(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?eB(e.eventData,e.evidenceHash):fv(e.eventData,e.evidenceHash),n=Qr(e.nextRun),a=e.previousRun===null?null:Qr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function iP(e,t,i=!1){if(e.skill!==Qi.definition.metadata.name||(i?!eP(e):e.skillVersion!==Qi.definition.metadata.version||e.skillHash!==Rc)||e.orchestration!==Qi.definition.orchestration.mode||e.pendingRef!==zt.pendingRef||e.trajectoryRef!==zt.trajectoryRef||e.contextRef!==zt.contextRef||e.artifactsRef!==zt.artifactsRef||e.checkpointRef!==zt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function rP(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function nP(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function mv(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(iP(o,"next Run",r||a!==null),nP(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(iP(a,"previous Run",!0),nP(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!_d(rP(a),rP(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function tB(e,t,i){return B(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function dP(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function aP(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function vv(e,t,i,r,n=!1){let a=i.eventData,o=aP(e),s=aP(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&_d(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&_d(e.spec_changes,t.spec_changes),l=tP({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=tB(e.name,a.summary,t.spec_changes),l=B(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function gv(e,t){let i=Id(e);if(hv(i,KM),i.schema!==qr)throw new Error(`Expected Native transition schema ${qr}`);let r=Td(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${qr} minimum_runtime_version must be ${3}`);let n=Td(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=pv(i,t),o=jt(i.previousState),s=jt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(vv(o,s,a,i.operation),mv(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:qr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function iB(e,t){let i=Id(e);if(hv(i,UM),i.schema!==Ln)throw new Error(`Expected Native transition schema ${Ln}`);let r=pv(i,t,!0),n=qn(i.previousState),a=qn(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return vv(n,a,r,dP(n,a,r.eventData),!0),mv(n,a,r,!0),{schema:Ln,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function wv(e,t){let i=Id(e);if(hv(i,uP),i.schema!==dr)throw new Error(`Expected Native transition schema ${dr}`);if(Td(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${dr} minimum_runtime_version must be 2`);let n=Td(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=pv(i,t,!0),o=Vi(i.previousState),s=Vi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(vv(o,s,a,dP(o,s,a.eventData),!0),mv(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:dr,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function rB(e,t){let i=Id(e);if(i.schema===qr)return{status:"current",journal:gv(i,t)};if(i.schema===Ln)return{status:"migration-required",journal:iB(i,t)};if(i.schema===dr)return{status:"migration-required",journal:wv(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function yv(e,t){let i=ht(e,t),r=j(e,i);await T(r,i);try{let n=await ge({root:r,file:i,maxBytes:YM,label:`Native transition journal ${t}`});return rB(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Sr(e,t){let i=await yv(e,t);if(!i)return null;if(i.status==="migration-required")throw new Cc(t);return i.journal}function oP(e,t){if(Zi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Zi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function sP(e,t){if(Zi(e,t.nextState))return"next";if(Zi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function nB(e){let{journal:t}=e;return fP({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function fP(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function cP(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=nB({sequence:a.index+1,journal:t,type:a.event.type});if(!Zi(fP(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function xc(e,t,i){if(await eo(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Gu(e,t);let r=await Sr(e,t);if(!r)return null;let n=M(e,t),a=cP(await kt(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Je(n),je(e,t)]),c=oP(o,r),l=sP(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Jn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!Zi(await Je(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let v=await Js(e,r.nextState,r.previousState.revision);if(!Zi(v,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!Zi(await je(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Sr(e,t);if(!u||!Zi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=cP(await kt(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await ln({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await ln({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await sa({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,m]=await Promise.all([Je(n),je(e,t)]);oP(h,{...r,previousRun:r.nextRun}),sP(m,{...r,previousState:r.nextState});let p=await Sr(e,t);if(!p||!Zi(p,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await JM.rm(ht(e,t),{force:!0}),r.nextState}async function hP(e,t,i){return F(e,`continue transition ${t}`,()=>un(e,t,`continue transition ${t}`,()=>xc(e,t,i)))}import pP from"node:path";var aB="comet.native.contract.v1",oB="comet.native.acceptance-set.v1",mP=/^[a-f0-9]{64}$/u,Ac={maxAcceptanceCriteria:Es.maxCriteria};function vP(e,t){let i=pP.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||pP.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function gP(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,` +`))}function sB(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(mP))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(mP))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=vP(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:gP(e.markdown)},markdown:e.markdown}}function cB(e,t){return wP(e.id,t.id)}function wP(e,t){return et?1:0}function yP(e){let t=vP(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(sB).sort((d,f)=>wP(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=fu(e.briefMarkdown,t,Ac.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...hu(f,d.source,Ac.maxAcceptanceCriteria-a.length)),a.push(...pu(f,d.source,Ac.maxAcceptanceCriteria-a.length)));if(a.sort(cB),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ac.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ac.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:gP(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(oB,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(aB,u)}}var Ti={maxSpecs:64,maxFileBytes:$o,maxTotalBytes:4*1024*1024};async function yo(e){if(e.specChanges.length>Ti.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ee({root:e.changeDir,ref:e.briefRef,maxBytes:Ti.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ee({root:e.changeDir,ref:n.source,maxBytes:Ti.maxFileBytes});if(i+=a.size,i>Ti.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:yP({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as EB}from"node:child_process";import{promisify as PB}from"node:util";import{promises as mB}from"fs";import No from"path";var fn={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},bo=/^[a-f0-9]{64}$/u;function jd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $d(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function dn(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function NP(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Nv(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function lB(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||No.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=No.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function bv(e,t){return No.join(M(e,t),"checkpoints","progress.json")}function hn(e,t){return No.join(M(e,t),"checkpoint-journal.json")}function kv(e,t,i){if(!bo.test(i))throw new Error("Native checkpoint manifest hash is invalid");return No.join(M(e,t),"checkpoints","manifests",`${i}.json`)}function uB(e){if(!bo.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Sv(e,t,i){let r=await ge({root:e,file:t,maxBytes:fn.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function dB(e,t){let i=jd(e,`checkpoint manifest artifact ${t}`);$d(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=lB(dn(i.path,`checkpoint artifact ${t} path`,4096)),n=Hi(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!bo.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Nv(i.size,`checkpoint artifact ${t} size`)}}function Od(e,t){let i=jd(e,"Native checkpoint manifest");if($d(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>fn.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(dB),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Nv(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>fn.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Ev(e){return B(JSON.stringify(Od(e,e.change)))}function Pv(e,t){let i=jd(e,"Native progress checkpoint");if($d(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=NP(i.previousRevision,"Native checkpoint previousRevision"),a=NP(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=dn(i.manifestHash,"Native checkpoint manifestHash",64);if(!bo.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=uB(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=dn(i.inputHash,"Native checkpoint inputHash",64);if(!bo.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=dn(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Nv(i.artifactCount,"Native checkpoint artifactCount");if(u>fn.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=dn(i.summary,"Native checkpoint summary"),f=dn(i.nextAction,"Native checkpoint nextAction");if(St(d)!==d||St(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:dn(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function fB(e,t){let i=jd(e,"Native checkpoint journal");if($d(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=jt(i.previousState),n=jt(i.nextState),a=Pv(i.checkpoint,t),o=Od(i.manifest,t),s=dn(i.inputHash,"Native checkpoint journal inputHash",64),c=B(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!bo.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Ev(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function hB(e,t,i){let r=No.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=pf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ge({root:e.projectRoot,file:r,maxBytes:fn.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function pB(e,t){let i=bv(e,t),r=j(e,i);await T(r,i);try{return Pv(await Sv(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Rv(e,t,i){let r=kv(e,t,i),n=j(e,r);await T(n,r);let a=await Sv(n,r,"Native checkpoint manifest"),o=Od(a,t);if(Cv(e,o),Ev(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function pn(e,t){let i=hn(e,t),r=j(e,i);await T(r,i);try{let n=fB(await Sv(r,i,"Native checkpoint journal"),t);return Cv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function bP(e,t,i,r){let n=Od(i,t);Cv(e,n);let a=Ev(n),o=kv(e,t,a),s=j(e,o);await T(s,o);try{let c=await Rv(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ve(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function Cv(e,t){for(let i of t.artifacts){let r=pf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function kP(e,t){let i=Pv(t,t.change),r=await Rv(e,i.change,i.manifestHash),n=B(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=bv(e,t.change),o=j(e,a);await T(o,a),await ve(a,i,{containedRoot:o})}async function SP(e){let t;try{t=await pB(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:bv(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Rv(e.paths,e.name,t.manifestHash);let a=B(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await hB(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:kv(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function EP(e,t,i){let r=await pn(e,t);if(!r)return null;if(await bP(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Js(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await kP(e,r.checkpoint),await i?.afterProgressWritten?.(r),await mB.rm(hn(e,t),{force:!0}),r}async function PP(e,t,i){return F(e,`continue checkpoint ${t}`,()=>un(e,t,`continue checkpoint ${t}`,async()=>(await xc(e,t),EP(e,t,i))))}import{constants as xv,promises as fi}from"node:fs";import ko from"node:path";var vB=/^[a-f0-9]{64}$/u,gB=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,_c=512*1024;function wB(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Hd(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function yB(e,t){let i=ko.resolve(e),r=ko.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...ko.relative(i,r).split(ko.sep).filter(Boolean)]){o&&(a=ko.join(a,o));let s=await fi.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await fi.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function RP(e){for(let t of e){let i=await fi.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!wB(t,i)||await fi.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function NB(e){if(!vB.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function bB(e){let t=gB.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function kB(e,t,i){return Lr(M(e,t),NB(i))}async function SB(e,t,i){let r=await yB(i,ko.dirname(e)),n=await fi.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>_c)throw new Error(`Native check receipt exceeds ${_c} bytes`);let[a,o]=await Promise.all([fi.realpath(t),fi.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":xv.O_RDONLY|xv.O_NOFOLLOW|xv.O_NONBLOCK,c=await fi.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),fi.lstat(e),fi.realpath(e)]);if(await RP(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Hd(n,l)||!Hd(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let y=_c+1-h,E=await c.read(m,0,Math.min(m.length,y),null);if(E.bytesRead===0)break;if(h+=E.bytesRead,h>_c)throw new Error(`Native check receipt exceeds ${_c} bytes`);f.push(Buffer.from(m.subarray(0,E.bytesRead)))}let[p,v,g]=await Promise.all([c.stat(),fi.lstat(e),fi.realpath(e)]);if(await RP(r),!v.isFile()||v.isSymbolicLink()||g!==o||!$(a,g)||!Hd(l,p)||!Hd(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function CP(e,t,i){let r=bB(i),n=M(e,t),a=kB(e,t,r),o=j(e,a);await T(o,a);let s=Sd(await SB(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Tc=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var B4=64*1024;var L4=3600*1e3;var q4=PB(EB);var RB=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function AP(e,t){let i=[];for(let r of RB){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function _P(e){if(e.receipt.kind!=="static-inspection")return null;let t=await CP(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mn=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}};function CB(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function xB(e){let t=CB(e.bundle.baseline),i=await qp(e.paths,t,{origin:"explicit",now:e.now});return Ym({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function IP(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Sc(e.paths,e.state.name,e.state.implementation_scope),i=await yo({changeDir:te(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await xB({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function jP(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await IP(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function AB(e){let t=await ee({root:te(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:FN(t.text)}}function _B(e){let{receipt:t,implementationScope:i}=e,r=[],n=Km({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function TB(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:rv(e.implementationScope.scope.declaredArtifacts)}}async function TP(e){let t=await Ec(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=AP(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mn([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await _P({paths:e.paths,state:e.state,receipt:t});if(n){let a=_B({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function IB(e){let t=TB({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await TP({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mn)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await TP({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mn)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mn(i)}function Av(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Dd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Av(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([IP(e),go(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Av(e.state.verification_result,"stale"),envelope:null};let r=await AB({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await IB({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Av(e.state.verification_result,"invalid"),envelope:null}}}function $B(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function OP(e){try{return await jB.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function OB(e,t){try{return(await ee({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function HB(e,t,i){let r=ia(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=$P.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await OB(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ee({root:te(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function DB(e,t){return OP(ht(e,t))}async function Fd(e){let t=e.now??new Date,i=await je(e.paths,e.name),r=await lt(e.paths,e.name),n=await Y(e.paths.projectRoot),a=$B(i.name,t),o=$P.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(m=>HB(e.paths,i.name,m))),Dd({paths:e.paths,state:i,now:t}),Cd(e.paths,i.name),eo(e.paths,i.name),to(e.paths,i.name),DB(e.paths,i.name),OP(o)]);return ZS({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as _v}from"node:fs";import Er from"node:path";var FB="comet.native.archive-tree.v1",MB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function FP(e){let t={...MB,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function HP(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function DP(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function MP(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await $t({root:e,directory:t,label:`Native Archive content directory ${Er.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=HP(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Er.join(t,u.name),f=Er.relative(e,d).replaceAll("\\","/"),h=await _v.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){DP(i,{ref:f,kind:"directory"},r,n),await MP(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ge({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=m.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);DP(i,{ref:f,kind:"file",hash:m.hash,size:m.size},r,n),await o.verify()}await o.verify();let l=await $t({root:e,directory:t,label:`Native Archive content directory ${Er.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(HP(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Er.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function BP(e,t={}){let i=FP(t);e=Er.resolve(e);let r=await _v.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await MP(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return B(`${FB}\0${o}`)}async function Ii(e,t={}){let i=FP(t);e=Er.resolve(e);let r;try{r=await _v.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ge({root:Er.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Er.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await BP(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Rt}from"node:fs";import We from"node:path";var Iv=16*1024*1024,BB=256*1024,LB=16*1024,Ic="comet.native.archive-cas.v1";function qB(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=We.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function it(e,t){let i=qB(e,t);return T(j(e,i),i)}function vn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function So(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function Mt(e){let t=await Ii(e.target);if(!vn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${So(t)}`);return t}async function jv(e,t){let i=await zi(e,t),r=await ge({root:e.runtimeDir,file:i.journal,maxBytes:BB,label:`Native Archive transaction journal ${t}`}),n=Au(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Md(e,t,i){let r=Au({...t,status:i}),n=await zi(e,r.id);return await ve(n.journal,r,{containedRoot:e.runtimeDir}),r}function Bd(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function LP(e){return{...Bd(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function gn(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function VB(e,t){return gn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pe(e){try{return await Rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function er(e){let t=await Rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=LP(t),r=await ge({root:j(e.paths,e.file),file:e.file,maxBytes:Iv,label:e.label}),n=await Rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!VB(i,LP(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Bd(n),size:r.size}}function WB(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==Ic||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Ic,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function tr(e,t,i,r){let n=await zi(e,t.id),a=We.join(n.backups,".cas"),o=`.${We.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:We.join(a,`${i.id}.original.json`),postRecord:We.join(a,`${i.id}.post.json`),candidate:We.join(a,`${i.id}.candidate`),originalQuarantine:We.join(We.dirname(r),`${o}.original`),rollbackQuarantine:We.join(We.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function hi(e){if(!await pe(e.file))return null;let t=await ge({root:e.paths.runtimeDir,file:e.file,maxBytes:LB,label:`Archive CAS ${e.operation.id} ${e.role} record`});return WB(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Ld(e){let t=await hi(e);if(t){if(!gn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Wi({root:e.paths.runtimeDir,directory:We.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Ic,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ve(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await hi(e);if(!r||!gn(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Le(e){let t=await er({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!gn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function zB(e){let t=await er({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Ld({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Le({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function JB(e){if(!await pe(e.quarantine)||await pe(e.target))return;let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Rt.lstat(e.quarantine),Rt.lstat(e.target)]);if(!gn(Bd(i),Bd(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Rt.unlink(e.quarantine),await t.verify()}async function zP(e){if(await pe(e.quarantine)){await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Rt.rename(e.target,e.quarantine),await t.verify(),await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await JB(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function ca(e){if(!await pe(e.file))return;await Le(e);let t=await Wt({root:j(e.paths,e.file),directory:We.dirname(e.file),label:e.label});await t.verify(),await Le(e),await Rt.unlink(e.file),await t.verify()}async function qP(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await it(e,t.target),n=await it(e,t.backup),a=await Ii(n);if(a!==null){if(!vn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await Mt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Jr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Iv,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await Mt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function JP(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await tr(e.paths,e.journal,e.operation,e.target),r=await hi({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await pe(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Le({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await qP(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await pe(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await zB({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Le({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await qP(e.paths,e.operation,e.hooks),await zP({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function VP(e){let t=await tr(e.paths,e.journal,e.operation,e.target);return await pe(t.candidate)?(await er({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Wi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Jr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Iv,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function GB(e){let t=e.operation.stagedHash,i=await tr(e.paths,e.journal,e.operation,e.target),r=await hi({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await pe(e.target))return await Le({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await pe(i.candidate)&&await ca({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await pe(e.target)){let c=await VP(e),l=await er({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await er({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!gn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Ld({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await ca({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await VP(e),a=await er({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Wi({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Le({paths:e.paths,file:n,operation:e.operation,record:{schema:Ic,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await er({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!gn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Ld({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await ca({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function UB(e,t,i,r){let n=await it(e,i.target),a=await it(e,i.staged);if(await Mt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await tr(e,t,i,n);(!await hi({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await pe(n))&&await JP({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Ii(n);if(o!==null&&!vn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${So(o)}`)}await GB({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await Mt({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function KB(e,t,i,r){let n=await it(e,i.target);await JP({paths:e,journal:t,operation:i,target:n,hooks:r}),await Mt({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function YB(e,t){let i=await it(e,t.source),r=await it(e,t.target),[n,a]=await Promise.all([Ii(i),Ii(r)]);if(!(n===null&&vn(a,t.expectedSourceHash,"directory"))){if(!vn(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${So(n)}, target=${So(a)}`);await Rt.mkdir(We.dirname(r),{recursive:!0}),await Rt.rename(i,r),await Mt({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function XB(e,t,i,r){return i.type==="write"?UB(e,t,i,r):i.type==="remove"?KB(e,t,i,r):YB(e,i)}function QB(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function ZB(e,t,i,r){let n=await it(e,i.target);if(i.type==="write"){let a=await it(e,i.staged);await Mt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await tr(e,t,i,n),s=await hi({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Le({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await Mt({target:await it(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await hi({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await pe(o.originalQuarantine))await Le({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await Mt({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await Mt({target:await it(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await tr(e,t,i,n),o=await hi({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await pe(a.originalQuarantine))await Le({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await Mt({target:await it(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await Mt({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function GP(e,t,i){let r=t.status==="prepared"?await Md(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Ur(e,r.id),a=QB({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await ZB(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await ai(e,r.id,"operation-started",l.id),await XB(e,r,l,i),await ai(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await jv(e,r.id),r}async function eL(e){try{return await Le(e),!0}catch{return!1}}async function tL(e){await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Tv(e){if(e.operation.type!=="write")return;let t=await tr(e.paths,e.journal,e.operation,e.target);if(!await pe(t.candidate))return;let i=await er({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await ca({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Ic,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function iL(e,t,i,r){let n=await it(e,i.target),a=await tr(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await hi({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await hi({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await pe(a.candidate)&&await pe(n)){let l=await er({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await er({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});gn(l.identity,u.identity)&&(c=await Ld({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await pe(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Le({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await pe(n)&&!(s!==null&&await eL({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Ii(n);if(vn(u,o)){await Tv({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await zP({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await pe(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await pe(n)){if(!s||!await pe(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await tL({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await pe(a.originalQuarantine)&&await ca({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await pe(a.rollbackQuarantine)&&await ca({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Tv({paths:e,journal:t,operation:i,target:n}),await Mt({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function rL(e,t){let i=await it(e,t.source),r=await it(e,t.target),[n,a]=await Promise.all([Ii(i),Ii(r)]);if(!(vn(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!vn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${So(n)}, target=${So(a)}`);await Rt.mkdir(We.dirname(i),{recursive:!0}),await Rt.rename(r,i)}}async function UP(e,t,i){let r=await Ur(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Md(e,t,"rolling-back");await ai(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await rL(e,o):await iL(e,n,o,i));return await ai(e,n.id,"rollback-completed"),n=await Md(e,n,"rolled-back"),n}async function WP(e,t,i){let r=await it(e,i.target);if(i.type==="write"){let n=await tr(e,t,i,r),a=await hi({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Le({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await Mt({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function nL(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await it(e,i.target),n=await tr(e,t,i,r);if(await pe(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await WP(e,t,i),i.expectedTargetHash!==null){let a=await hi({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await pe(n.originalQuarantine)&&await ca({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Tv({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await WP(e,t,i)}async function qd(e,t,i){return i==="commit"&&await nL(e,t),await ai(e,t.id,i),i==="commit"?Md(e,t,"committed"):t}var O9=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var u8=16*1024*1024,Vd=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"},jc=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"};function YP(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Eo.resolve(e.nativeRoot,...i.target.split("/"))}async function XP(e,t,i){let r=await Ur(e,t.id);if(r.some(v=>v.type==="archive-finalized"))return;let n=r.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(y=>y.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await Ii(YP(e,t));if(g?.kind!=="directory"||g.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=YP(e,t),o=Eo.join(a,Ve),s=await kk(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=M(e,s.name),l=await Je(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let v=KS(Qi,l,new Set,uv,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=YS(Qi,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},uv,void 0)}let d=B(`archive:${t.id}:${s.name}`),f=await kt(c,u.trajectoryRef),h=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let m=h.find(v=>v.type==="state_transitioned"),p={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(m&&t.schema==="comet.native.transaction.v2"&&(!aL(m.data,p)||m.runId!==u.runId||m.timestamp!==t.createdAt||m!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await qd(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await La(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await bk(o,v)}m||(m=await ln({changeDir:c,run:u,type:"state_transitioned",data:p,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await sa({changeDir:c,run:u,trajectoryOffset:m.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Jn(c,u),await lc(e,s.name),t.schema==="comet.native.transaction.v2"?await qd(e,t,"archive-finalized"):await La(e,t,"archive-finalized")}async function $v(e,t){let i=ze(e,t);try{let r=await KP.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await KP.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function oL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Ur(e,t.id)).some(c=>c.type==="operation-started")){let c=await Fd({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new jc(c,"Native Archive facts changed before the first transaction operation")}let o=await GP(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await je(e,t.change),u=await Dd({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await XP(e,o,i);let s=await qd(e,o,"commit");return{journal:s,runtimeCleanupWarning:await $v(e,s.change)}}let r=await fb(e,t);await XP(e,r,i);let n=await La(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await $v(e,n.change):null}}function sL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Eo.resolve(t.projectRoot)!==Eo.resolve(e.projectRoot)||Eo.resolve(t.nativeRoot)!==Eo.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function QP(e){return F(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await cr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await Ot(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await jv(e.paths,e.transactionId):i;return sL(e.paths,r),r.status==="committed"?(r.change&&await $v(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await oL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?UP(e.paths,r):Tu(e.paths,r)}finally{await lr(t)}},{allowedTransactionId:e.transactionId})}import{promises as $c}from"node:fs";import pt from"node:path";var wn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};function Ov(e,t){let i=pt.normalize(e),r=pt.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function tR(e,t){let i=pt.relative(e,t);return i===""||!pt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${pt.sep}`)}function ZP(e){return JSON.stringify(e.native)}async function Wd(e,t){let i=await Y(e);if(i&&t){if(ZP(i)!==ZP(t))throw new Error(`Native worktree configuration differs from the source project: ${pt.join(e,".comet","config.yaml")}`);return!1}return!i&&t?(await Vt(e,t),!0):!1}async function cL(e,t){if(!tR(e,t))return!1;let r=`/${pt.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=le(e,["rev-parse","--git-common-dir"]),a=pt.resolve(e,n),o=pt.join(a,"info","exclude"),s="";try{s=await $c.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(r))return!1;await $c.mkdir(pt.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(` `)?"":` `;return await $c.appendFile(o,`${c}${r} -`,"utf8"),!0}function aL(e,t,i){let r=pt.resolve(e,i??pt.join(".worktrees",t)),n=pt.resolve(e,he(e,["rev-parse","--git-common-dir"]));if(eR(n,r))throw new Error("Native worktree path cannot be inside the Git common directory");if(Zt(e).some(a=>$v(a,r)))throw new Error(`Native worktree path is already registered: ${r}`);return r}async function oL(e){try{throw await $c.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function ZP(e){try{return await $c.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function tR(e){let t=pt.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let r=me(t);if(r.isGitWorktree&&r.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:r.currentBranch,targetBranch:r.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:r.currentBranch,targetBranch:r.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let i=await re(t,e.sourceConfig?.native.artifact_root??"docs");return Dn([{runtimeDir:i.runtimeDir,locksDir:i.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let r=me(t);if(!r.isGitWorktree||r.currentBranch===null||r.primaryWorktreeRoot===null||r.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;tm(t,n);let a=r.currentBranch===n,o=e.targetBranch??(a?void 0:r.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(tm(t,o),!Io(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!Gs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Io(t,n))throw new Error(`Native change branch already exists: ${n}`);he(t,["switch","-c",n,o]),h=!0}let m;try{m=await Wd(t,e.sourceConfig)}catch(p){throw new wn(`Native branch preparation is incomplete: ${p.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?pt.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!$v(h,r.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${r.currentWorktreeRoot}`);let m;try{m=await Wd(t,e.sourceConfig)}catch(p){throw new wn(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Jc(r.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await ZP(c.root)){let h=e.worktreePath?pt.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!$v(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await Wd(c.root,e.sourceConfig)}catch(p){throw new wn(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await ZP(c.root)&&(he(r.primaryWorktreeRoot,["worktree","prune"]),s=Jc(r.primaryWorktreeRoot));let l=Io(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=aL(r.primaryWorktreeRoot,e.name,e.worktreePath);await oL(u);let d=await nL(r.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{he(r.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Wd(u,e.sourceConfig)}catch(h){throw new wn(`Native worktree preparation is incomplete: ${h.message}`,f,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var iR=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Hv=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:iR,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] +`,"utf8"),!0}function lL(e,t,i){let r=pt.resolve(e,i??pt.join(".worktrees",t)),n=pt.resolve(e,le(e,["rev-parse","--git-common-dir"]));if(tR(n,r))throw new Error("Native worktree path cannot be inside the Git common directory");if(Zt(e).some(a=>Ov(a,r)))throw new Error(`Native worktree path is already registered: ${r}`);return r}async function uL(e){try{throw await $c.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function eR(e){try{return await $c.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function iR(e){let t=pt.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let r=me(t);if(r.isGitWorktree&&r.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:r.currentBranch,targetBranch:r.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:r.currentBranch,targetBranch:r.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let i=await re(t,e.sourceConfig?.native.artifact_root??"docs");return Dn([{runtimeDir:i.runtimeDir,locksDir:i.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let r=me(t);if(!r.isGitWorktree||r.currentBranch===null||r.primaryWorktreeRoot===null||r.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;tm(t,n);let a=r.currentBranch===n,o=e.targetBranch??(a?void 0:r.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(tm(t,o),!Io(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!Gs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Io(t,n))throw new Error(`Native change branch already exists: ${n}`);le(t,["switch","-c",n,o]),h=!0}let m;try{m=await Wd(t,e.sourceConfig)}catch(p){throw new wn(`Native branch preparation is incomplete: ${p.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?pt.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Ov(h,r.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${r.currentWorktreeRoot}`);let m;try{m=await Wd(t,e.sourceConfig)}catch(p){throw new wn(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Jc(r.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await eR(c.root)){let h=e.worktreePath?pt.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Ov(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await Wd(c.root,e.sourceConfig)}catch(p){throw new wn(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await eR(c.root)&&(le(r.primaryWorktreeRoot,["worktree","prune"]),s=Jc(r.primaryWorktreeRoot));let l=Io(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=lL(r.primaryWorktreeRoot,e.name,e.worktreePath);await uL(u);let d=await cL(r.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{le(r.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Wd(u,e.sourceConfig)}catch(h){throw new wn(`Native worktree preparation is incomplete: ${h.message}`,f,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var rR=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Dv=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:rR,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] comet native next --runner-input `,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 Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--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.","--runner-input 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 "Implementation changed" --return-to-build','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 "]},archive:{usage:`comet native archive --dry-run [--finish merge|push|pull-request|keep] - comet native archive [--confirmed] [--serial-first ]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first During execution only, confirm that this change archives before detected capability peers; the value must equal .","--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 [] [--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 Ov(e,t){return`${e}: + comet native archive [--confirmed] [--serial-first ]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first During execution only, confirm that this change archives before detected capability peers; the value must equal .","--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 [] [--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 Hv(e,t){return`${e}: ${t.map(i=>` ${i}`).join(` -`)}`}function sL(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Hv[i]||t.length>1&&Hv[t[0]]?.subcommands?i:t[0]}function Dv(e=[]){let t=sL(e),i=Hv[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Ov("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...iR];return n&&n.length>0&&r.push("",Ov("Options",n)),r.push("",`Output: - ${i.output}`),i.examples&&r.push("",Ov("Examples",i.examples)),t===""&&r.push("","Run `comet native --help` for command-specific details."),{topic:t,usage:`${r.join(` +`)}`}function dL(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Dv[i]||t.length>1&&Dv[t[0]]?.subcommands?i:t[0]}function Fv(e=[]){let t=dL(e),i=Dv[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Hv("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...rR];return n&&n.length>0&&r.push("",Hv("Options",n)),r.push("",`Output: + ${i.output}`),i.examples&&r.push("",Hv("Examples",i.examples)),t===""&&r.push("","Run `comet native --help` for command-specific details."),{topic:t,usage:`${r.join(` `)} -`}}var cL=Dv().usage;var nR=10*1024*1024,O=class extends Error{};function Bt(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 Ae(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 Se(e){if(e.length>0)throw new O(`Unexpected argument: ${e[0]}`)}function rt(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new O(`${t} is required`);return i}function zd(e,t="en"){let i=Ae(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new O("--language must be en or zh-CN");return i}function rR(e,t){let i=Fv.normalize(e),r=Fv.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function lL(e){let t=Fv.resolve(e),i=me(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=me(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!rR(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||rR(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function aR(e){return e?lL(e):au(process.cwd())}async function ir(e){let t=await NN({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function oR(e){let t=await Y(e);return re(e,t?.native.artifact_root??"docs")}function W(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` -`}}function sR(e,t){if(t instanceof O)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Vd)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 jc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Vs)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 Qa)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 wn)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Za)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 mn)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Tc)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 Mv(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` -`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function cR(e,t){let i=rt(e,"change name"),r=Bt(e,"--dry-run"),n=Ae(e,"--expect-preflight"),a=Bt(e,"--confirmed"),o=Ae(e,"--finish"),s=Ae(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 ir(t),u=await ke(l.paths,i),d=u?await Ha(l.paths,{kind:"archive",change:i}):null,f=u?!1:await RS(l.paths,i);if(u||f){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");Se(e);let m=u&&!r&&d?.kind!=="archive"?await ta({paths:l.paths,name:i}):null,p=m?.state??(u?await K(l.paths,i):null);if(m?.action==="reverify"||m?.action==="await-user")return W(r?"archive --dry-run":"archive",{archived:!1,state:m.state,recovery:m,continuation:de(m.state)},`${m.message} +`}}var fL=Fv().usage;var aR=10*1024*1024,O=class extends Error{};function Bt(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 Ae(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 Se(e){if(e.length>0)throw new O(`Unexpected argument: ${e[0]}`)}function rt(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new O(`${t} is required`);return i}function zd(e,t="en"){let i=Ae(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new O("--language must be en or zh-CN");return i}function nR(e,t){let i=Mv.normalize(e),r=Mv.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function hL(e){let t=Mv.resolve(e),i=me(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=me(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!nR(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||nR(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function oR(e){return e?hL(e):au(process.cwd())}async function ir(e){let t=await bN({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function sR(e){let t=await Y(e);return re(e,t?.native.artifact_root??"docs")}function W(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+` +`}}function cR(e,t){if(t instanceof O)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Vd)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 jc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Vs)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 Qa)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 wn)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Za)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 mn)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Tc)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 Bv(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+` +`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function lR(e,t){let i=rt(e,"change name"),r=Bt(e,"--dry-run"),n=Ae(e,"--expect-preflight"),a=Bt(e,"--confirmed"),o=Ae(e,"--finish"),s=Ae(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 ir(t),u=await ke(l.paths,i),d=u?await Ha(l.paths,{kind:"archive",change:i}):null,f=u?!1:await CS(l.paths,i);if(u||f){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");Se(e);let m=u&&!r&&d?.kind!=="archive"?await ta({paths:l.paths,name:i}):null,p=m?.state??(u?await K(l.paths,i):null);if(m?.action==="reverify"||m?.action==="await-user")return W(r?"archive --dry-run":"archive",{archived:!1,state:m.state,recovery:m,continuation:fe(m.state)},`${m.message} `);if(r){if(!p)return W("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} -`);if(c)p=await mS({paths:l.paths,name:i,finish:c});else if(p.workspace.isolation!=="current"&&p.workspace.finish===null)throw new O("Native branch and worktree isolation require --finish with --dry-run");let E=await Am({paths:l.paths,name:i}),S=de(p),k=E.capabilityPeers.length>0?{...S,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...S.runnerAction,kind:"none"}}:S;return W("archive --dry-run",{...E,workspaceFinish:p.workspace.finish,continuation:k},`Native Archive preview: ${E.ready?"ready":"blocked"} -`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new O("archive requires --confirmed when native.archive_confirmation is required");if(p&&p.workspace.isolation!=="current"&&p.workspace.finish===null)throw new O("Native branch and worktree isolation require a persisted --finish preview");let v=p?await Hm({paths:l.paths,state:p}):null,g;try{g=await dc({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(E){if(!(E instanceof uc)||!p)throw E;let S=await Am({paths:l.paths,name:i}),k=E.peers.length>0?["comet","native","archive",i,"--confirmed","--serial-first",i]:["comet","native","archive",i,"--confirmed"];return{command:"archive",exitCode:73,data:{...S,workspaceFinish:p.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:E.message,commandArgs:k,inputOptions:E.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:E.message}}}p=g.state,!v&&p.workspace.isolation!=="current"&&(v=await Hm({paths:l.paths,state:p,archiveDir:g.archiveDir}));let y=null;if(v)try{y=await WS({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:v})}catch(E){if(!(E instanceof hc))throw E;return{command:"archive",exitCode:73,data:{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:E.result,continuation:{disposition:"blocked",reason:E.message,commandArgs:E.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:E.message}}}return W("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:y,continuation:de(g.state)},`Archived Native change ${i} to ${g.archiveDir} -`)}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(Se(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 h=await xi({paths:l.paths,name:i});return W("archive",{migration:{from:"legacy",to:h.schema,completed:!0},state:h,continuation:de(h)},`Migrated Native change ${i}; follow the returned portable continuation before Archive -`)}import{promises as JR}from"node:fs";import cf from"node:path";import{promises as af}from"fs";import Ke from"path";import{promises as EL}from"fs";async function lR(e,t){let i=[],r=M(e,t.name),n=Lr(r,zt.stateRef),a;try{a=await Je(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Lr(r,a.trajectoryRef),s=await Ka(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await kt(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Lr(r,a.checkpointRef);try{let u=await Ua(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var uL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function dL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function fL(e){return e?e.map(dL).join(" "):null}function hL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function pi(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function pL(e){return e.map(t=>pi(t,[],null))}function mL(e){let t=["comet","native","next",e.name,"--summary",""],i=[pi("summary",["--summary"],"")];if(e.phase==="shape")return t.push("--confirmed"),i.push(pi("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact",""),i.push(pi("artifact-or-no-code-reason",["--artifact"],"",{repeatable:!0,alternativeGroup:"build-evidence"}),pi("artifact-or-no-code-reason",["--no-code-reason"],"",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(pi("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","","--report",""),i.push(pi("verification-result",["--result"],"",{choices:["pass","fail"]}),pi("verification-report",["--report"],"")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function mt(e,t){let i=t.commandArgs===void 0?hL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?fL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??pL(t.requiredInputs??[])}}function Jd(e){let i=(e.findings??[]).filter(d=>!Ya(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||uL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return mt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return mt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[pi("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return mt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return mt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return mt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary",""],requiredInputs:["summary"],inputOptions:[pi("summary",["--summary"],"")]});if(n)return mt(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary",""];return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[pi("summary",["--summary"],"")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?mt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),mt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[pi("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):mt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return mt(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=mL(e.state);return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Oc from"path";var uR=8,vL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function gL(e){let t=vL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Ya(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function wL(e,t,i){if(!i.path)return null;let r;if(Oc.isAbsolute(i.path)?r=Oc.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Oc.resolve(te(e,t.name),...i.path.split(/[\\/]/u)):r=Oc.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=Oc.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function yL(e,t,i){return e==="next"?`comet native next ${t.name} --summary ""${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Bv(e){return e.findings.map(t=>{let i=gL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:wL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:yL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Lv(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,uR),truncated:t.length>uR}}var dR=240,fR=8,Gd=50;function hR(e){let t=Array.from(e);return t.length<=dR?e:`${t.slice(0,dR-1).join("")}…`}function NL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function bL(e){let t=[...new Set(e.map(NL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,fR),reasonCount:e.length,codesTruncated:t.length>fR};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Gd),reasonsTruncated:e.length>Gd}}}async function pR(e){let t=null;try{let s=await pn(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:hn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:hn(e.paths,e.state.name)}}let i=await kP({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=bL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fn.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:hR(i.checkpoint.summary),nextAction:hR(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fn.maxArtifacts}}async function kL(e,t){let i=M(e,t.name),r=await Je(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Ua(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await kt(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function SL(e,t){let i=await kL(e,t);return{committed:i,latest:QE(i),history:XE(i)}}async function mR(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await SL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var PL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Qt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function qv(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function RL(e){return(await sc(e))?.change??null}function CL(e,t,i=!1,r){return Jd({state:e,archiveReady:t,evidenceRetreat:i}).command}async function xL(e,t){let i=te(e,t.name),r=[...(await $m(i,t.brief)).findings,...(await qS(e,t)).findings,...await lR(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ga(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Fu(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await yo({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Sr(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Om(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function yn(e,t,i){let r=await RL(e)===t,n=await Ns(e,t),a=await Ku(e,t),o;try{let w=await li(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Bv({paths:e,state:o,findings:[w]}),L=Jd({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:L.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:Lv(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:L,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await pR({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await mR(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await yo({changeDir:te(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let nt=await go(e,o.name,o.verification_evidence);for(let Pe of nt.acceptanceTrace.entries)P.set(Pe.acceptanceId,Pe.status==="failed"?"failed":Pe.status==="missing"?"missing":"satisfied")}let L=ON({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),H=L.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",L.nextCursor,"--project-root",e.projectRoot]:null;u={...L,...H?{nextPageCommand:qv(H),nextPageArgs:H}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await Cd(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await lt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await Gi({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Zr({paths:e,identity:w});f.push(...P.findingCodes.map(L=>({code:L,message:`Native workspace advisory changed: ${L} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],m=!1;if(o.phase==="verify"){let w=await IP({paths:e,state:o});m=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let p=null,v=[];if(o.phase==="archive")try{p=await Fd({paths:e,name:o.name}),v.push(...p.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await xL(e,o),...s.findings,...d,...f,...h,...l,...v].filter((w,P,L)=>L.findIndex(H=>H.code===w.code&&H.path===w.path)===P),y=Bv({paths:e,state:o,findings:g}),E=y.filter(w=>!Ya(w.code)),S=o.phase==="archive"&&p?.ready===!0&&E.length===0,k=m||o.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||R?null:CL(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:Lv(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Jd({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Gd,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function Vv(e){let t;try{t=await Wt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await EL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Qt.maxChanges))throw new Error(`Native status exceeds ${Qt.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Ud(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function AL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=PL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function _L(e,t){let i=await Vv(e),r=D("comet.native.status-names.v1",i),n=AL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Qt.maxItems).map(u=>yn(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:fQt.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function gR(e){return JSON.stringify(e,null,2)+` -`}function Uv(e){return e.schema===Oe?Qu(e):Gn(e)}function zv(e,t){return{...e,schema:Oe,minimum_runtime_version:2,revision:t}}function HL(e){return{...e,schema:dr,minimum_runtime_version:2,revision:1,previousState:zv(e.previousState,1),nextState:zv(e.nextState,2)}}function Yd(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:$e,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function DL(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?B(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:qr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Yd(e.previousState),nextState:{...Yd(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Qi.definition.metadata.version,skillHash:Rc}:e.nextRun}}function wR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Po(e,t){return JSON.stringify(Qu(e))===JSON.stringify(Qu(t))}function yR(e,t){return JSON.stringify(Gn(e))===JSON.stringify(Gn(t))}function Pr(e,t){return Gv(e,t)}function FL(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Kd(n,$L,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!la.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!la.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Qr(n.previousRun),o=Qr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Pr(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==vR.size||u.some(f=>!vR.has(f))||l.fromSchema!==Oe||l.toSchema!==$e||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=B(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function Hc(e,t){return Jv.join(M(e,t),"schema-migration.json")}function ML(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Kd(e,IL,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===yt&&i.toSchema===Oe,n=i.fromSchema===Oe&&i.toSchema===$e;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!la.test(i.sourceHash)||typeof i.targetHash!="string"||!la.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?Vi(i.nextState):jt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(B((0,Xd.stringify)(Uv(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Kd(i.transition,jL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!la.test(l.sourceHash)||typeof l.targetHash!="string"||!la.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?gv(l.nextJournal,t):vv(l.nextJournal,t);if(B(JSON.stringify(l.nextJournal,null,2)+` -`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===Oe?Po(a,u.previousState)||Po(a,u.nextState):a.schema===$e&&(yR(a,u.previousState)||yR(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==$e)throw new Error("Schema migration transition supersede target schema is invalid");s=FL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Kd(i.runRetreat,OL,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Qr(l.previousRun),d=Qr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!la.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==$e||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Dc(e,t){let i=Hc(e,t),r=j(e,i);await T(r,i);try{let n=await Eu({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return ML(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function BL(e,t,i){let r=await Ga(e,t),n=r?await Fu(e,r):await Mu(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Bp(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new Za(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Vp(e,t,n)}async function bR(e){try{return await oi(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function LL(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function kR(e,t){let i=t.transitionSupersede,r=M(e,t.change),n=await kt(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Gv(o.event,LL(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function qL(e,t,i){if(!t.transitionSupersede)return;let r=ht(e,t.change),n=await bR(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=M(e,t.change),o=await Je(a),s=await kR(e,t),c=await Ua(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Pr(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==B(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function VL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=M(e,t.change),a=await Je(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Pr(a,r.nextRun)){if(!Pr(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Jn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Pr(await Je(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await kR(e,t);if(o.sequence===null){let l=await ln({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await sa({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=ht(e,t.change),c=await bR(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await NR.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function WL(e,t,i){if(!t.runRetreat)return;let r=M(e,t.change),n=await Je(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Pr(n,t.runRetreat.nextRun)){if(!Pr(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Jn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await kt(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await ln({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await sa({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function zL(e,t,i){let r=await Dc(e,t);if(!r)return null;if(await to(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Jv.join(te(e,t),Ve),a=await oi(n);if(await qL(e,r,a===r.targetHash),await BL(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await Ne(n,(0,Xd.stringify)(Uv(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=ht(e,t),s=await oi(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ve(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await VL(e,r,i),await WL(e,r,i),await NR.rm(Hc(e,t),{force:!0}),r.nextState}async function JL(e){let t=M(e.paths,e.state.name),i=await Je(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=B(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function GL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Po(i,t.previousState),a=Po(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=M(e.paths,i.name),s=await Je(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Pr(s,t.previousRun),l=Pr(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await kt(o,t.nextRun.trajectoryRef)).map((g,y)=>({event:g,index:y})).filter(({event:g})=>g.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let g={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Gv(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...Yd(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=B(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await oi(ht(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function UL(e){let t,i,r,n;if(e.state.schema===yt){if(t=zv(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Ln)throw new Error("Native v1 change has a transition from another schema generation");let s=HL(e.pendingTransition.journal);if(wR(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(wR(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=ht(e.paths,e.name);i={sourceHash:await oi(c),targetHash:B(gR(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==dr)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await GL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=DL(s);if(Po(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Po(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=ht(e.paths,e.name);i={sourceHash:await oi(u),targetHash:B(gR(l)),nextJournal:l}}}else t=Yd(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await JL({paths:e.paths,state:e.state,migrationId:e.id}));let a=Jv.join(te(e.paths,e.name),Ve),o=(0,Xd.stringify)(Uv(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===yt?Oe:$e,sourceHash:await oi(a),targetHash:B(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function SR(e){return F(e.paths,`migrate schema for ${e.name}`,()=>un(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await zL(e.paths,e.name,e.hooks);if(i?.schema===$e)return i;let r=await li(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await to(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==yt&&n.schema!==Oe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await wv(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await UL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??TL()}),s=Hc(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ve(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Rr=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),XL=512*1024,ua=/^([a-f0-9]{64})\.json$/u,QL=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,ZL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Qd=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Xv(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function rr(e,t){return Xv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function xR(e,t){return Xv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ro(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ct(e,t){return et?1:0}function eq(e,t){let i=Ee.relative(e.projectRoot,t);if(i.length===0||Ee.isAbsolute(i)||i===".."||i.startsWith(`..${Ee.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(Ee.sep).join("/")}function AR(e,t){return Ee.join(M(e,t),"evidence")}function Zd(e,t){return eq(e,AR(e,t))}async function ef(e,t){let i=Ee.resolve(e),r=Ee.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=Ee.relative(i,r).split(Ee.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=Ee.join(o,s));let c=await se.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await se.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ro(c)})}return a}async function mi(e){for(let t of e){let i=await se.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Xv(t,i)||await se.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function _R(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:vo(e,t)}function ER(e){return e!==null&&ZL.test(e)?[e]:[]}function tq(e,t,i,r){if(e==="snapshots")return{canonical:lo(i,t),dependencies:[]};if(e==="scopes"){let a=uo(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=kd(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[vo("scopes",a.scopeHash)]}}if(e==="verifications"){let a=bc(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(ER));return{canonical:a,dependencies:[a.implementationScopeRef,LE(a.reportHash),...ER(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||KL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Ed(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=Sd(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Nn(e){let t=await se.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?XL:cn;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await se.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Kv.O_RDONLY|Kv.O_NOFOLLOW|Kv.O_NONBLOCK,a=await se.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await mi(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!rr(Ro(t),o)||!rr(Ro(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,E=await a.read(u,0,Math.min(u.length,y),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await mi(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==r||!rr(Ro(o),f)||!rr(Ro(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let g=tq(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(g.canonical,null,2)+` -`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ro(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(Ct)}}finally{await a.close()}}async function PR(e){try{return await se.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function iq(e){let t=M(e.paths,e.name),i=t,r=AR(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await ef(t,r);n=await se.readdir(r,{withFileTypes:!0}),await mi(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Qd){if(!n.some(f=>f.name===s))continue;let c=Ee.join(r,s),l=await ef(t,c),u=(await se.readdir(c,{withFileTypes:!0})).sort((f,h)=>Ct(f.name,h.name)),d=new Map;for(let f of u){let h=QL.exec(f.name);if(!h)continue;let m=d.get(h[1])??[];m.push(f),d.set(h[1],m)}for(let[f,h]of[...d.entries()].sort(([m],[p])=>Ct(m,p))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let m=h[0];if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${m.name}`);let p=Ee.join(c,f),v=ua.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${m.name}`);let g=_R(s,v),y=Ee.join(c,m.name),E=await Nn({changeRoot:i,file:y,ref:g,kind:s,hash:v,name:e.name,directoryChain:l}),S=await PR(p),k=S?null:await Nn({changeRoot:i,file:p,ref:g,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:g,original:p,quarantine:y,document:E,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Ct);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Co(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${tf(o)}`),path:Zd(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Ct(c.ref,l.ref))){if(await mi(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Nn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Nn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!rr(s.originalDocument.identity,d.identity)||!rr(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await se.rm(s.quarantine),await mi(s.document.directoryChain);continue}if(!await PR(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await se.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!rr(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await se.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Nn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Nn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!xR(s.document.identity,l.identity)||!rr(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await se.rm(s.quarantine),await mi(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Co(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${tf(o)}`),path:Zd(e.paths,e.name)}]}}async function rq(e,t){let i=M(e,t),r=i,n=Ee.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await ef(i,n);a=await se.readdir(n,{withFileTypes:!0}),await mi(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Qd.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Ct);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${tf(o)}`);let s=[],c=0;for(let l of Qd){if(!a.some(h=>h.name===l))continue;let u=Ee.join(n,l),d=await ef(r,u),f=(await se.readdir(u,{withFileTypes:!0})).sort((h,m)=>Ct(h.name,m.name));await mi(d);for(let h of f){if(s.length>=Rr.maxDocuments)throw new Error(`Native evidence store exceeds ${Rr.maxDocuments} documents`);let m=ua.exec(h.name);if(!m||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let p=_R(l,m[1]),v=Ee.join(u,h.name);await T(j(e,v),v);let g=await Nn({changeRoot:r,file:v,ref:p,kind:l,hash:m[1],name:t,directoryChain:d});if(c+=g.size,c>Rr.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Rr.maxScannedBytes} scanned bytes`);s.push(g)}await mi(d)}return s}function RR(e,t){let i=new Set,r=[...e].sort(Ct).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Ct).reverse())i.has(o)||r.push(o)}return i}function nq(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ct),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Ct))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function aq(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=RR(t,r),a=new Set(n);for(let c of e)i-c.mtimeMsu.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ct(u.ref,d.ref)).slice(0,Rr.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=RR(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Rr.minimumAgeMs).sort((c,l)=>Ct(c.ref,l.ref));return{candidates:nq(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function tf(e){let t=e.slice(0,Rr.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Co(e){let t=Rr.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Yv(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Ct);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Co(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${tf(n)}`),path:r}}async function CR(e,t){try{await se.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await se.rename(e,t)}catch{}}async function oq(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await mi(e.directoryChain);let i=await Nn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:ua.exec(Ee.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await se.lstat(e.file),n=await se.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!rr(e.identity,r)||!rr(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=Ee.join(Ee.dirname(e.file),`.${Ee.basename(e.file)}.${YL()}.gc`);await se.rename(e.file,a);try{let[o,s]=await Promise.all([se.lstat(a),se.realpath(a)]);if(await mi(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!xR(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await CR(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await se.rm(a),await mi(e.directoryChain)}catch(o){throw await CR(a,e.file),o}}async function sq(e){if((await Y(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await se.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await Ot(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function cq(e,t){if(t)return[t];let i;try{i=await se.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Ct)}async function lq(e,t){let i=await li(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Sr(e,t),Dc(e,t),pn(e,t)]);return r!==null||n!==null||a!==null}async function uq(e){if(await lq(e.paths,e.name))return[];let t=await li(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await iq({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await rq(e.paths,e.name),a=aq(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Zd(e.paths,e.name);if(!e.repair)return[...i.findings,Yv(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await oq(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Yv(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Co(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Yv(e.name,a,!0,o)]}async function TR(e){if(e.deferAll||await sq(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await cq(e.paths,e.name))try{a.push(...await uq({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Co(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Zd(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await F(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Co(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as dq,randomUUID as fq}from"crypto";import{promises as bn}from"fs";import le from"path";var Zv=64*1024*1024,hq=256*1024,OR=16*1024*1024;async function Ue(e){try{return await bn.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pq(e){let t;try{t=await bn.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let r;try{r=await Ot(e,i.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:n}):n}if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${r.id} is unfinished; recover it before moving`)}}async function mq(e,t){for(let i of await bn.readdir(e.locksDir,{withFileTypes:!0})){let r=le.join(e.locksDir,i.name);if(le.resolve(r)!==le.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${r}`)}}async function vq(e){let t;try{t=await bn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await lt(e,i.name);if(r){await Yu({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function gq(e){let t;try{t=await bn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let r=await lt(e,i.name);if(r?.schema==="comet.native.workspace.v3"){let n=await Gi({paths:e,identity:r});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(r){let n=await Zr({paths:e,identity:r});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(r){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:r})}}async function Mc(e,t){let i=[];async function r(n){let a=await $t({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=le.join(n,s.name);if(t.excludedFiles?.has(le.resolve(c))){await a.verify();continue}let l=await bn.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:le.relative(e,c).split(le.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ge({root:e,file:c,maxBytes:Zv,label:`Native root file ${le.relative(e,c)}`});i.push({ref:le.relative(e,c).split(le.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function wq(e,t,i,r){await Wi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await $t({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=le.join(a,l.name);if(le.resolve(u)===le.resolve(i)){await s.verify();continue}let d=await bn.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=le.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Wi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Jr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Zv,label:`Native root move file ${le.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function xo(e,t,i,r){let n=await Mc(e,{rejectSymlinks:!0,excludedFiles:i?new Set([le.resolve(i)]):void 0}),a=await Mc(t,{rejectSymlinks:!0,excludedFiles:r?new Set([le.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function HR(e,t){return le.join(e.artifactRoot,`.comet-native-move-${t}`)}function yq(e,t){return le.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function Nq(e){return`${e}.removing`}function IR(e,t){return le.join(le.dirname(e),`.${le.basename(e)}.${t}.rollback-removing`)}function DR(e,t,i){return le.join(_u(e,t).directory,`root-move-cleanup-${i}.json`)}function bq(e){return JSON.stringify(e,null,2)+` -`}function kq(e){return dq("sha256").update(e).digest("hex")}function Sq(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||le.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function Eq(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(Sq);for(let a=0;a0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=le.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function Pq(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=bq(t);if(Buffer.byteLength(i,"utf8")>OR)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await Ne(DR(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),kq(i)}async function Rq(e){let t=await ge({root:e.paths.runtimeDir,file:DR(e.paths,e.id,e.cleanup.kind),maxBytes:OR,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return Eq(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Qv(e){let t=await Mc(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function jR(e){return e.ref.split("/").length}async function Cq(e){let i=[...await Qv({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>jR(a)-jR(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=le.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Pu({root:e.projectRoot,file:a,maxBytes:Zv,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Sp({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Qv({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Sp({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function rf(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function FR(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function xq(e,t,i,r){for(let a of[e,t])try{let o=await Ot(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=le.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ge({root:i,file:n,maxBytes:hq,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function $R(e){let t=rf(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Vt(e.projectRoot,t),t}async function Fc(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=rf(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Vt(e.projectRoot,i),i}async function nf(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await Ue(e.target),a=await Ue(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await Pq({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Mc(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await Rq({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await Ue(e.target),a=await Ue(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await eb({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Fc({projectRoot:e.projectRoot,config:t,id:e.id})}return await Qv({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await Cq({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Fc({projectRoot:e.projectRoot,config:t,id:e.id})}async function MR(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Ue(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=Nq(e.staging);t=await nf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Mc(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([le.resolve(e.lockFile)])}),await wq(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await xo(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await $R({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Ue(e.destinationPaths.nativeRoot)){if(await Ue(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await xo(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Ue(e.staging))throw new Error("Native move staging tree is missing");await xo(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await bn.rename(e.staging,e.destinationPaths.nativeRoot)}t=await $R({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Ue(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=yq(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Ue(e.sourcePaths.nativeRoot)&&await xo(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await nf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await vq(e.destinationPaths);let n=await Ot(e.destinationPaths,e.pending.id);await La(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Vt(e.projectRoot,o),o}async function BR(e){let t=await Y(e.projectRoot)??Hn("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=Br(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let r=await re(e.projectRoot,t.native.artifact_root),n=await re(e.projectRoot,i);if($(r.nativeRoot,n.nativeRoot)||$(n.nativeRoot,r.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Ue(r.nativeRoot))throw new Error(`Native source root does not exist: ${r.nativeRoot}`);if(await pq(r),await Ue(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await cr(r,"root-move",`move root to ${i}`),o=fq(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=FR({id:o,paths:r,now:e.now??new Date}),l=HR(n,o);try{if(await mq(r,a.file),await gq(r),await Ue(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Vt(e.projectRoot,rf(t,s)),await _p(r,c),await e.hooks?.afterRootMoveStage?.("copying",c),await MR({projectRoot:e.projectRoot,config:rf(t,s),pending:s,sourcePaths:r,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:r.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await lr(a)}}async function LR(e){let t=await Y(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await re(e.projectRoot,i.fromArtifactRoot),n=await re(e.projectRoot,i.toArtifactRoot),a=HR(n,i.id),o=await Ue(r.nativeRoot)?r:n,s=await cr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await xq(r,n,a,i.id)}catch(m){if(i.stage!=="copying"||!await Ue(r.nativeRoot))throw m;let p=FR({id:i.id,paths:r,now:new Date});await _p(r,p),c={journal:p,paths:r}}if(e.strategy==="continue"){let m=await MR({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:m}}if(!await Ue(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=IR(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Ue(n.nativeRoot)&&await xo(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await nf({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=IR(a,i.id);!t.native.pending_root_move?.cleanup&&await Ue(a)&&await xo(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await nf({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await Ot(r,i.id);await Tu(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Vt(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await lr(s)}}var Ao=4096,Aq=4096,_q=1024;async function kn(e,t,i){try{let r=await $t({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function of(e,t){let i=new Map(e.map(r=>[Ke.resolve(r.file),{...r,file:Ke.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await bs(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await fp(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function Tq(e,t){let i=cc(e),r;try{await T(e.projectRoot,i);let n=await sc(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await ke(e,r.change)?[]:(await je(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await af.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function Iq(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function jq(e,t){let i=[],r=[];for(let n of await kn(e,e.transactionsDir,Aq)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await Ot(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ke.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Dn([e],`doctor archive recovery ${a.id}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,"archive.lock")}],i)?(await XP({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function $q(e,t,i){let r=[];for(let n of await kn(e,e.locksDir,_q)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ke.join(e.locksDir,n.name);try{let o=await bs(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await fp(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function Oq(e,t,i=5){let r=[],n=t?await Wv(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Wv(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Ke.join(e.changesDir,a.name,Ve)});continue}let o=await yn(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Ke.join(e.projectRoot,s.path)}:{}})}return r}async function Hq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await Ka(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Zb(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Ke.join(M(e,n),"trajectory.jsonl")})}return i}async function Dq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await Ns(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=On(e,n),s=ze(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Dn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Wt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await af.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Wt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await af.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await af.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function Fq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Yp(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:Xa(e,n),repair:"migrate"});continue}let a=await je(e,n);await lk({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:Xa(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Xa(e,n)})}return i}async function Mq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Hc(e,n);try{let o=await Dc(e,n),s=await li(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Ke.join(e.changesDir,n,Ve)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:Ke.join(e.changesDir,n,Ve),repair:"migrate"});continue}await SR({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Ke.join(e.changesDir,n,Ve)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function Bq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Sr(e,n)}catch(o){if(o instanceof Cc)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:ht(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Dn([e],`doctor transition recovery ${n}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await fP(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:ht(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:ht(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:ht(e,n),repair:"continue"})}}return i}async function Lq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=hn(e,n),o;try{o=await pn(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Dn([e],`doctor checkpoint recovery ${n}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await EP(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Bc(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Y(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([re(r.projectRoot,c.fromArtifactRoot),re(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await of([{paths:l,file:Ke.join(l.locksDir,"root-move.lock")},{paths:u,file:Ke.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await LR({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await re(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await Iq(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await jq(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await Dq(r,{name:e.name,repair:t})),i.push(...await Mq(r,{name:e.name,repair:t})),i.push(...await Fq(r,{name:e.name,repair:t})),i.push(...await Hq(r,{name:e.name,repair:t})),i.push(...await Bq(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await Lq(r,{name:e.name,repair:t})),i.push(...await TR({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await $q(r,t,s.unfinished)),i.push(...await Tq(r,t)),e.projectOnly||i.push(...await Oq(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{promises as qR}from"node:fs";function qq(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Vq(e,t){let i=me(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function ji(e){let t=await vS(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=Vq(e.paths,t.state),n=await Gt({paths:e.paths,state:t.state}),a=de(t.state,n),o=r.bindingState==="mismatch"?{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...a.runnerAction,kind:"none"}}:a;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:qq(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{children:n.children,readyChildren:n.readyChildren}:{},continuation:o,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function VR(e){let t;try{t=await qR.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await qR.readFile(`${we(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}async function Lc(e,t){let i=await Gt({paths:e,state:t});return de(t,i)}async function Wq(e){let t;try{t=await JR.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function zq(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function WR(e,t){let i;try{i=await JR.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${zq(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:cf.join(e.archiveDir,n.name)}:null}function Jq(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function sf(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function zR(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:cf.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function Gq(e,t){let i=[],r=[];for(let n of await YN(e)){let a=Vn(n);if(t&&a.change!==t)continue;let o=cf.join(e.transactionsDir,n);try{let s=await Cs(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function eg(e,t){let i=Bt(e,"--repair"),r=Ae(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new O("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();Se(e);let a=await oR(t),o=await Gq(a,n);if(n&&o.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let d=await ke(a,n)?await ji({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let m=await dc({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:m.transactionId},state:m.state,continuation:await Lc(a,m.state)})}let h=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Lc(a,h)})}return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await ke(a,n)){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([WR(a,n),_m(a,n)]);if(u){let h=await ji({paths:a,name:n,details:!0});return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await ji({paths:a,name:n,details:!0});return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[zR(a,n)],continuation:h.continuation})}if(i){if(d){let m=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:m.schema,stateVersion:m.state_version},state:m,continuation:await Lc(a,m)})}let h=await ta({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:await Lc(a,h.state)})}let f=await ji({paths:a,name:n,details:!0});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Lc(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await VR(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");if(i){let k=await Bc({paths:a,repair:!0,projectOnly:!0}),b=[];for(let w of c.transactions)w.kind==="archive"?await dc({paths:a,name:w.change}):await xi({paths:a,name:w.change}),b.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await eg([],t),N=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...N,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await Wq(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[m,p,v,g,y]=await Promise.all([Promise.all(s.map(k=>ji({paths:a,name:k}))),Promise.all(s.map(k=>WR(a,k))),Promise.all(s.map(k=>_m(a,k))),Promise.all(h.map(k=>Bc({paths:a,name:k}))),Bc({paths:a,projectOnly:!0})]),E=Jq([...p.filter(k=>k!==null),...s.flatMap((k,b)=>v[b]&&!f.has(k)?[zR(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:cf.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...g.flatMap(({findings:k})=>k),...y.findings]),S={healthy:E.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:m,legacyChanges:h,findings:E};return S.healthy?W("doctor",S):sf(S)}let l=await Bc({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?W("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}import{promises as r1}from"fs";import $i from"path";import{readFileSync as Uq}from"fs";import GR from"path";var Kq=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),Yq=new Set(["glob","grep","listfiles","read","readfile","search","view"]),KR=["file_path","filePath","path","target_file","targetFile"],YR=["file_paths","filePaths","paths","files","targets"],XR=["operations","edits"],Xq=["patch","diff","patchText","patch_text","changes"];function ig(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function UR(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Qq(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function Zq(e){for(let t of["cwd","working_directory","workspaceRoot"]){let i=e[t];if(!(typeof i!="string"||!i.trim()||!GR.isAbsolute(i.trim())))return GR.resolve(i.trim())}}function e1(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function t1(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return e1(e[t]);return e}function tg(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let r of i)for(let n of e.matchAll(r)){let a=n[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function da(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)da(e,i);return}if(ig(t)){for(let i of KR)da(e,t[i]);for(let i of YR)da(e,t[i]);for(let i of XR)da(e,t[i])}}function i1(e,t){let i=[],r=[t,e].filter(ig);for(let n of r){for(let a of KR)da(i,n[a]);for(let a of YR)da(i,n[a]);for(let a of XR)da(i,n[a]);for(let a of Xq){let o=n[a];typeof o=="string"&&i.push(...tg(o))}}return typeof t=="string"&&i.push(...tg(t)),[...new Set(i)]}function qc(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{let o=tg(e);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!ig(i))return{intent:"unknown",targets:[],toolName:null};let r=Qq(i),n=i1(i,t1(i)),a=Zq(i);return r&&Kq.has(UR(r))?{intent:n.length>0?"write":"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:r&&Yq.has(UR(r))?{intent:"non-write",targets:[],toolName:r,...a?{cwd:a}:{}}:r?{intent:"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{}}}function QR(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return qc("",e);try{return qc(Uq(0,"utf8"),e)}catch{return qc("",e)}}async function n1(e){let{projectRoot:t,paths:i,state:r,request:n}=e,a=we(i,r.name),o=[],s=[],c=!1,l=!1,u=!1;for(let d of n.targets){let f=$i.resolve(t,d);if(!fa(t,f)){u=!0;continue}let h=$i.relative(t,f).replaceAll("\\","/");if(h===".comet/config.yaml"){l=!0;continue}if(!fa(i.nativeRoot,f)){if(await Lu(t,f,[$i.join(t,".comet"),i.nativeRoot])){c=!0;continue}s.push(h);continue}if(!fa(a,f))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:r.phase,change:r.name};let m=$i.relative(a,f).replaceAll("\\","/");if(m==="brief.md"||m==="children.yaml"||m.startsWith("specs/")){o.push(m);continue}return{allowed:!1,reason:`${m||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:r.phase,change:r.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:r.phase,change:r.name}:o.length>0?r.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await nc({paths:i,name:r.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:r.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:r.phase,change:r.name}:s.length>0?r.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:r.phase,change:r.name}:r.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name}:r.phase==="verify"||r.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await no({paths:i,name:r.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:r.name}:{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in Build`,workflow:"native",phase:r.phase,change:r.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:r.phase,change:r.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}function fa(e,t){let i=$i.relative(e,t);return i===""||!i.startsWith("..")&&!$i.isAbsolute(i)}function a1(e,t,i){return i.targets.length>0&&i.targets.every(r=>{let n=$i.resolve(e,r);return fa(e,n)?$i.relative(e,n).replaceAll("\\","/")===".comet/config.yaml"||fa(t,n):!0})}async function o1(e){let t=await Y(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await re(e,t.native.artifact_root),r;try{r=await r1.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let n=[];for(let a of r.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await ke(i,a.name)){let o=await K(i,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await je(i,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:i,changes:n}}var s1=Bu("nativeActiveContext",e=>o1(e));async function ZR(){let{intent:e,targets:t}=await QR();return{intent:e,targets:t}}async function eC(e,t,i){let r=await s1(e);if(!r)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.changes.length===0)return{allowed:!0,reason:a1(e,r.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let n;if(i){if(n=r.changes.find(l=>l.state.name===i),!n)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(r.changes.length===1)n=r.changes[0];else{let l=await SS(r.paths);if(n=r.changes.find(u=>u.state.name===l),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return n1({projectRoot:e,paths:r.paths,state:n.state,request:t});let o=!1,s=!1,c=!1;for(let l of t.targets){let u=$i.resolve(e,l);if(!fa(e,u)){s=!0;continue}if($i.relative(e,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(fa(r.paths.nativeRoot,u)){o=!0;continue}if(await Lu(e,u,[$i.join(e,".comet"),r.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:`Native change ${a.name} is in ${a.phase}; implementation writes are only allowed in build. If this belongs to the current change, confirm the scope and run comet native next ${a.name} --summary "" --return-to-build; otherwise create or select a separate Native change`,workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}async function tC(e,t){let i=Ae(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new O("--hook-output must be copilot");Se(e);let r=await eC(t,await ZR());return i==="copilot"?{command:"hook-guard",exitCode:0,data:r,text:r.allowed?`{} +`);if(c)p=await vS({paths:l.paths,name:i,finish:c});else if(p.workspace.isolation!=="current"&&p.workspace.finish===null)throw new O("Native branch and worktree isolation require --finish with --dry-run");let E=await Am({paths:l.paths,name:i}),S=fe(p),k=E.capabilityPeers.length>0?{...S,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...S.runnerAction,kind:"none"}}:S;return W("archive --dry-run",{...E,workspaceFinish:p.workspace.finish,continuation:k},`Native Archive preview: ${E.ready?"ready":"blocked"} +`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new O("archive requires --confirmed when native.archive_confirmation is required");if(p&&p.workspace.isolation!=="current"&&p.workspace.finish===null)throw new O("Native branch and worktree isolation require a persisted --finish preview");let v=p?await Dm({paths:l.paths,state:p}):null,g;try{g=await dc({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(E){if(!(E instanceof uc)||!p)throw E;let S=await Am({paths:l.paths,name:i}),k=E.peers.length>0?["comet","native","archive",i,"--confirmed","--serial-first",i]:["comet","native","archive",i,"--confirmed"];return{command:"archive",exitCode:73,data:{...S,workspaceFinish:p.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:E.message,commandArgs:k,inputOptions:E.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:E.message}}}p=g.state,!v&&p.workspace.isolation!=="current"&&(v=await Dm({paths:l.paths,state:p,archiveDir:g.archiveDir}));let y=null;if(v)try{y=await zS({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:v})}catch(E){if(!(E instanceof hc))throw E;return{command:"archive",exitCode:73,data:{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:E.result,continuation:{disposition:"blocked",reason:E.message,commandArgs:E.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:E.message}}}return W("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:y,continuation:fe(g.state)},`Archived Native change ${i} to ${g.archiveDir} +`)}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(Se(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 h=await xi({paths:l.paths,name:i});return W("archive",{migration:{from:"legacy",to:h.schema,completed:!0},state:h,continuation:fe(h)},`Migrated Native change ${i}; follow the returned portable continuation before Archive +`)}import{promises as GR}from"node:fs";import cf from"node:path";import{promises as af}from"fs";import Ke from"path";import{promises as xL}from"fs";async function uR(e,t){let i=[],r=M(e,t.name),n=Lr(r,zt.stateRef),a;try{a=await Je(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Lr(r,a.trajectoryRef),s=await Ka(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await kt(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Lr(r,a.checkpointRef);try{let u=await Ua(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var pL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function mL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function vL(e){return e?e.map(mL).join(" "):null}function gL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function pi(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function wL(e){return e.map(t=>pi(t,[],null))}function yL(e){let t=["comet","native","next",e.name,"--summary",""],i=[pi("summary",["--summary"],"")];if(e.phase==="shape")return t.push("--confirmed"),i.push(pi("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact",""),i.push(pi("artifact-or-no-code-reason",["--artifact"],"",{repeatable:!0,alternativeGroup:"build-evidence"}),pi("artifact-or-no-code-reason",["--no-code-reason"],"",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(pi("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","","--report",""),i.push(pi("verification-result",["--result"],"",{choices:["pass","fail"]}),pi("verification-report",["--report"],"")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function mt(e,t){let i=t.commandArgs===void 0?gL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?vL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??wL(t.requiredInputs??[])}}function Jd(e){let i=(e.findings??[]).filter(d=>!Ya(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||pL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return mt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return mt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[pi("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return mt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return mt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return mt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary",""],requiredInputs:["summary"],inputOptions:[pi("summary",["--summary"],"")]});if(n)return mt(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary",""];return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[pi("summary",["--summary"],"")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?mt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),mt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[pi("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):mt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return mt(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=yL(e.state);return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Oc from"path";var dR=8,NL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function bL(e){let t=NL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Ya(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function kL(e,t,i){if(!i.path)return null;let r;if(Oc.isAbsolute(i.path)?r=Oc.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Oc.resolve(te(e,t.name),...i.path.split(/[\\/]/u)):r=Oc.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=Oc.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function SL(e,t,i){return e==="next"?`comet native next ${t.name} --summary ""${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Lv(e){return e.findings.map(t=>{let i=bL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:kL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:SL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function qv(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,dR),truncated:t.length>dR}}var fR=240,hR=8,Gd=50;function pR(e){let t=Array.from(e);return t.length<=fR?e:`${t.slice(0,fR-1).join("")}…`}function EL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function PL(e){let t=[...new Set(e.map(EL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,hR),reasonCount:e.length,codesTruncated:t.length>hR};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Gd),reasonsTruncated:e.length>Gd}}}async function mR(e){let t=null;try{let s=await pn(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:hn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:hn(e.paths,e.state.name)}}let i=await SP({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=PL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fn.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:pR(i.checkpoint.summary),nextAction:pR(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fn.maxArtifacts}}async function RL(e,t){let i=M(e,t.name),r=await Je(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Ua(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await kt(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function CL(e,t){let i=await RL(e,t);return{committed:i,latest:ZE(i),history:QE(i)}}async function vR(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await CL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var AL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Qt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Vv(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function _L(e){return(await sc(e))?.change??null}function TL(e,t,i=!1,r){return Jd({state:e,archiveReady:t,evidenceRetreat:i}).command}async function IL(e,t){let i=te(e,t.name),r=[...(await Om(i,t.brief)).findings,...(await qS(e,t)).findings,...await uR(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ga(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Fu(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await yo({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Sr(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Hm(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function yn(e,t,i){let r=await _L(e)===t,n=await Ns(e,t),a=await Ku(e,t),o;try{let w=await li(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Lv({paths:e,state:o,findings:[w]}),L=Jd({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:L.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:qv(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:L,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await mR({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await vR(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await yo({changeDir:te(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let nt=await go(e,o.name,o.verification_evidence);for(let Pe of nt.acceptanceTrace.entries)P.set(Pe.acceptanceId,Pe.status==="failed"?"failed":Pe.status==="missing"?"missing":"satisfied")}let L=HN({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),H=L.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",L.nextCursor,"--project-root",e.projectRoot]:null;u={...L,...H?{nextPageCommand:Vv(H),nextPageArgs:H}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await Cd(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await lt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await Gi({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Zr({paths:e,identity:w});f.push(...P.findingCodes.map(L=>({code:L,message:`Native workspace advisory changed: ${L} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],m=!1;if(o.phase==="verify"){let w=await jP({paths:e,state:o});m=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let p=null,v=[];if(o.phase==="archive")try{p=await Fd({paths:e,name:o.name}),v.push(...p.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await IL(e,o),...s.findings,...d,...f,...h,...l,...v].filter((w,P,L)=>L.findIndex(H=>H.code===w.code&&H.path===w.path)===P),y=Lv({paths:e,state:o,findings:g}),E=y.filter(w=>!Ya(w.code)),S=o.phase==="archive"&&p?.ready===!0&&E.length===0,k=m||o.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||R?null:TL(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:qv(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Jd({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Gd,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function Wv(e){let t;try{t=await Wt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await xL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Qt.maxChanges))throw new Error(`Native status exceeds ${Qt.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Ud(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function jL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=AL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function $L(e,t){let i=await Wv(e),r=D("comet.native.status-names.v1",i),n=jL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Qt.maxItems).map(u=>yn(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:fQt.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function wR(e){return JSON.stringify(e,null,2)+` +`}function Kv(e){return e.schema===Oe?Qu(e):Gn(e)}function Jv(e,t){return{...e,schema:Oe,minimum_runtime_version:2,revision:t}}function BL(e){return{...e,schema:dr,minimum_runtime_version:2,revision:1,previousState:Jv(e.previousState,1),nextState:Jv(e.nextState,2)}}function Yd(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:$e,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function LL(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?B(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:qr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Yd(e.previousState),nextState:{...Yd(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Qi.definition.metadata.version,skillHash:Rc}:e.nextRun}}function yR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Po(e,t){return JSON.stringify(Qu(e))===JSON.stringify(Qu(t))}function NR(e,t){return JSON.stringify(Gn(e))===JSON.stringify(Gn(t))}function Pr(e,t){return Uv(e,t)}function qL(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Kd(n,FL,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!la.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!la.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Qr(n.previousRun),o=Qr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Pr(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==gR.size||u.some(f=>!gR.has(f))||l.fromSchema!==Oe||l.toSchema!==$e||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=B(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function Hc(e,t){return Gv.join(M(e,t),"schema-migration.json")}function VL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Kd(e,HL,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===yt&&i.toSchema===Oe,n=i.fromSchema===Oe&&i.toSchema===$e;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!la.test(i.sourceHash)||typeof i.targetHash!="string"||!la.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?Vi(i.nextState):jt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(B((0,Xd.stringify)(Kv(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Kd(i.transition,DL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!la.test(l.sourceHash)||typeof l.targetHash!="string"||!la.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?wv(l.nextJournal,t):gv(l.nextJournal,t);if(B(JSON.stringify(l.nextJournal,null,2)+` +`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===Oe?Po(a,u.previousState)||Po(a,u.nextState):a.schema===$e&&(NR(a,u.previousState)||NR(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==$e)throw new Error("Schema migration transition supersede target schema is invalid");s=qL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Kd(i.runRetreat,ML,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Qr(l.previousRun),d=Qr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!la.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==$e||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Dc(e,t){let i=Hc(e,t),r=j(e,i);await T(r,i);try{let n=await Eu({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return VL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function WL(e,t,i){let r=await Ga(e,t),n=r?await Fu(e,r):await Mu(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Bp(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new Za(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Vp(e,t,n)}async function kR(e){try{return await oi(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function zL(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function SR(e,t){let i=t.transitionSupersede,r=M(e,t.change),n=await kt(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Uv(o.event,zL(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function JL(e,t,i){if(!t.transitionSupersede)return;let r=ht(e,t.change),n=await kR(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=M(e,t.change),o=await Je(a),s=await SR(e,t),c=await Ua(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Pr(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==B(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function GL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=M(e,t.change),a=await Je(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Pr(a,r.nextRun)){if(!Pr(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Jn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Pr(await Je(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await SR(e,t);if(o.sequence===null){let l=await ln({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await sa({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=ht(e,t.change),c=await kR(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await bR.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function UL(e,t,i){if(!t.runRetreat)return;let r=M(e,t.change),n=await Je(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Pr(n,t.runRetreat.nextRun)){if(!Pr(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Jn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await kt(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await ln({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await sa({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function KL(e,t,i){let r=await Dc(e,t);if(!r)return null;if(await to(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Gv.join(te(e,t),Ve),a=await oi(n);if(await JL(e,r,a===r.targetHash),await WL(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await Ne(n,(0,Xd.stringify)(Kv(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=ht(e,t),s=await oi(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ve(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await GL(e,r,i),await UL(e,r,i),await bR.rm(Hc(e,t),{force:!0}),r.nextState}async function YL(e){let t=M(e.paths,e.state.name),i=await Je(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=B(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function XL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Po(i,t.previousState),a=Po(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=M(e.paths,i.name),s=await Je(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Pr(s,t.previousRun),l=Pr(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await kt(o,t.nextRun.trajectoryRef)).map((g,y)=>({event:g,index:y})).filter(({event:g})=>g.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let g={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Uv(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...Yd(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=B(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await oi(ht(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function QL(e){let t,i,r,n;if(e.state.schema===yt){if(t=Jv(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Ln)throw new Error("Native v1 change has a transition from another schema generation");let s=BL(e.pendingTransition.journal);if(yR(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(yR(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=ht(e.paths,e.name);i={sourceHash:await oi(c),targetHash:B(wR(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==dr)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await XL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=LL(s);if(Po(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Po(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=ht(e.paths,e.name);i={sourceHash:await oi(u),targetHash:B(wR(l)),nextJournal:l}}}else t=Yd(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await YL({paths:e.paths,state:e.state,migrationId:e.id}));let a=Gv.join(te(e.paths,e.name),Ve),o=(0,Xd.stringify)(Kv(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===yt?Oe:$e,sourceHash:await oi(a),targetHash:B(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function ER(e){return F(e.paths,`migrate schema for ${e.name}`,()=>un(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await KL(e.paths,e.name,e.hooks);if(i?.schema===$e)return i;let r=await li(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await to(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==yt&&n.schema!==Oe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await yv(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await QL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??OL()}),s=Hc(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ve(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Rr=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),tq=512*1024,ua=/^([a-f0-9]{64})\.json$/u,iq=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,rq=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Qd=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Qv(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function rr(e,t){return Qv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function AR(e,t){return Qv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ro(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ct(e,t){return et?1:0}function nq(e,t){let i=Ee.relative(e.projectRoot,t);if(i.length===0||Ee.isAbsolute(i)||i===".."||i.startsWith(`..${Ee.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(Ee.sep).join("/")}function _R(e,t){return Ee.join(M(e,t),"evidence")}function Zd(e,t){return nq(e,_R(e,t))}async function ef(e,t){let i=Ee.resolve(e),r=Ee.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=Ee.relative(i,r).split(Ee.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=Ee.join(o,s));let c=await se.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await se.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ro(c)})}return a}async function mi(e){for(let t of e){let i=await se.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Qv(t,i)||await se.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function TR(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:vo(e,t)}function PR(e){return e!==null&&rq.test(e)?[e]:[]}function aq(e,t,i,r){if(e==="snapshots")return{canonical:lo(i,t),dependencies:[]};if(e==="scopes"){let a=uo(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=kd(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[vo("scopes",a.scopeHash)]}}if(e==="verifications"){let a=bc(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(PR));return{canonical:a,dependencies:[a.implementationScopeRef,qE(a.reportHash),...PR(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||ZL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Ed(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=Sd(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Nn(e){let t=await se.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?tq:cn;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await se.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Yv.O_RDONLY|Yv.O_NOFOLLOW|Yv.O_NONBLOCK,a=await se.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await mi(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!rr(Ro(t),o)||!rr(Ro(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,E=await a.read(u,0,Math.min(u.length,y),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await mi(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==r||!rr(Ro(o),f)||!rr(Ro(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let g=aq(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(g.canonical,null,2)+` +`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ro(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(Ct)}}finally{await a.close()}}async function RR(e){try{return await se.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function oq(e){let t=M(e.paths,e.name),i=t,r=_R(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await ef(t,r);n=await se.readdir(r,{withFileTypes:!0}),await mi(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Qd){if(!n.some(f=>f.name===s))continue;let c=Ee.join(r,s),l=await ef(t,c),u=(await se.readdir(c,{withFileTypes:!0})).sort((f,h)=>Ct(f.name,h.name)),d=new Map;for(let f of u){let h=iq.exec(f.name);if(!h)continue;let m=d.get(h[1])??[];m.push(f),d.set(h[1],m)}for(let[f,h]of[...d.entries()].sort(([m],[p])=>Ct(m,p))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let m=h[0];if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${m.name}`);let p=Ee.join(c,f),v=ua.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${m.name}`);let g=TR(s,v),y=Ee.join(c,m.name),E=await Nn({changeRoot:i,file:y,ref:g,kind:s,hash:v,name:e.name,directoryChain:l}),S=await RR(p),k=S?null:await Nn({changeRoot:i,file:p,ref:g,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:g,original:p,quarantine:y,document:E,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Ct);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Co(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${tf(o)}`),path:Zd(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Ct(c.ref,l.ref))){if(await mi(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Nn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Nn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!rr(s.originalDocument.identity,d.identity)||!rr(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await se.rm(s.quarantine),await mi(s.document.directoryChain);continue}if(!await RR(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await se.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!rr(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await se.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Nn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Nn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!AR(s.document.identity,l.identity)||!rr(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await se.rm(s.quarantine),await mi(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Co(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${tf(o)}`),path:Zd(e.paths,e.name)}]}}async function sq(e,t){let i=M(e,t),r=i,n=Ee.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await ef(i,n);a=await se.readdir(n,{withFileTypes:!0}),await mi(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Qd.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Ct);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${tf(o)}`);let s=[],c=0;for(let l of Qd){if(!a.some(h=>h.name===l))continue;let u=Ee.join(n,l),d=await ef(r,u),f=(await se.readdir(u,{withFileTypes:!0})).sort((h,m)=>Ct(h.name,m.name));await mi(d);for(let h of f){if(s.length>=Rr.maxDocuments)throw new Error(`Native evidence store exceeds ${Rr.maxDocuments} documents`);let m=ua.exec(h.name);if(!m||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let p=TR(l,m[1]),v=Ee.join(u,h.name);await T(j(e,v),v);let g=await Nn({changeRoot:r,file:v,ref:p,kind:l,hash:m[1],name:t,directoryChain:d});if(c+=g.size,c>Rr.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Rr.maxScannedBytes} scanned bytes`);s.push(g)}await mi(d)}return s}function CR(e,t){let i=new Set,r=[...e].sort(Ct).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Ct).reverse())i.has(o)||r.push(o)}return i}function cq(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ct),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Ct))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function lq(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=CR(t,r),a=new Set(n);for(let c of e)i-c.mtimeMsu.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ct(u.ref,d.ref)).slice(0,Rr.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=CR(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Rr.minimumAgeMs).sort((c,l)=>Ct(c.ref,l.ref));return{candidates:cq(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function tf(e){let t=e.slice(0,Rr.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Co(e){let t=Rr.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Xv(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Ct);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Co(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${tf(n)}`),path:r}}async function xR(e,t){try{await se.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await se.rename(e,t)}catch{}}async function uq(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await mi(e.directoryChain);let i=await Nn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:ua.exec(Ee.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await se.lstat(e.file),n=await se.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!rr(e.identity,r)||!rr(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=Ee.join(Ee.dirname(e.file),`.${Ee.basename(e.file)}.${eq()}.gc`);await se.rename(e.file,a);try{let[o,s]=await Promise.all([se.lstat(a),se.realpath(a)]);if(await mi(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!AR(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await xR(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await se.rm(a),await mi(e.directoryChain)}catch(o){throw await xR(a,e.file),o}}async function dq(e){if((await Y(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await se.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await Ot(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function fq(e,t){if(t)return[t];let i;try{i=await se.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Ct)}async function hq(e,t){let i=await li(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Sr(e,t),Dc(e,t),pn(e,t)]);return r!==null||n!==null||a!==null}async function pq(e){if(await hq(e.paths,e.name))return[];let t=await li(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await oq({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await sq(e.paths,e.name),a=lq(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Zd(e.paths,e.name);if(!e.repair)return[...i.findings,Xv(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await uq(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Xv(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Co(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Xv(e.name,a,!0,o)]}async function IR(e){if(e.deferAll||await dq(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await fq(e.paths,e.name))try{a.push(...await pq({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Co(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Zd(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await F(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Co(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as mq,randomUUID as vq}from"crypto";import{promises as bn}from"fs";import ue from"path";var eg=64*1024*1024,gq=256*1024,HR=16*1024*1024;async function Ue(e){try{return await bn.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wq(e){let t;try{t=await bn.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let r;try{r=await Ot(e,i.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:n}):n}if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${r.id} is unfinished; recover it before moving`)}}async function yq(e,t){for(let i of await bn.readdir(e.locksDir,{withFileTypes:!0})){let r=ue.join(e.locksDir,i.name);if(ue.resolve(r)!==ue.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${r}`)}}async function Nq(e){let t;try{t=await bn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await lt(e,i.name);if(r){await Yu({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function bq(e){let t;try{t=await bn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let r=await lt(e,i.name);if(r?.schema==="comet.native.workspace.v3"){let n=await Gi({paths:e,identity:r});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(r){let n=await Zr({paths:e,identity:r});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(r){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:r})}}async function Mc(e,t){let i=[];async function r(n){let a=await $t({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ue.join(n,s.name);if(t.excludedFiles?.has(ue.resolve(c))){await a.verify();continue}let l=await bn.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ue.relative(e,c).split(ue.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ge({root:e,file:c,maxBytes:eg,label:`Native root file ${ue.relative(e,c)}`});i.push({ref:ue.relative(e,c).split(ue.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function kq(e,t,i,r){await Wi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await $t({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ue.join(a,l.name);if(ue.resolve(u)===ue.resolve(i)){await s.verify();continue}let d=await bn.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ue.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Wi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Jr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:eg,label:`Native root move file ${ue.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function xo(e,t,i,r){let n=await Mc(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ue.resolve(i)]):void 0}),a=await Mc(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ue.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function DR(e,t){return ue.join(e.artifactRoot,`.comet-native-move-${t}`)}function Sq(e,t){return ue.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function Eq(e){return`${e}.removing`}function jR(e,t){return ue.join(ue.dirname(e),`.${ue.basename(e)}.${t}.rollback-removing`)}function FR(e,t,i){return ue.join(_u(e,t).directory,`root-move-cleanup-${i}.json`)}function Pq(e){return JSON.stringify(e,null,2)+` +`}function Rq(e){return mq("sha256").update(e).digest("hex")}function Cq(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ue.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function xq(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(Cq);for(let a=0;a0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ue.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function Aq(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=Pq(t);if(Buffer.byteLength(i,"utf8")>HR)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await Ne(FR(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),Rq(i)}async function _q(e){let t=await ge({root:e.paths.runtimeDir,file:FR(e.paths,e.id,e.cleanup.kind),maxBytes:HR,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return xq(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Zv(e){let t=await Mc(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function $R(e){return e.ref.split("/").length}async function Tq(e){let i=[...await Zv({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>$R(a)-$R(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ue.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Pu({root:e.projectRoot,file:a,maxBytes:eg,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Sp({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Zv({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Sp({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function rf(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function MR(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function Iq(e,t,i,r){for(let a of[e,t])try{let o=await Ot(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ue.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ge({root:i,file:n,maxBytes:gq,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function OR(e){let t=rf(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Vt(e.projectRoot,t),t}async function Fc(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=rf(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Vt(e.projectRoot,i),i}async function nf(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await Ue(e.target),a=await Ue(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await Aq({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Mc(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await _q({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await Ue(e.target),a=await Ue(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await tb({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Fc({projectRoot:e.projectRoot,config:t,id:e.id})}return await Zv({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await Tq({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Fc({projectRoot:e.projectRoot,config:t,id:e.id})}async function BR(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Ue(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=Eq(e.staging);t=await nf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Mc(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ue.resolve(e.lockFile)])}),await kq(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await xo(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await OR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Ue(e.destinationPaths.nativeRoot)){if(await Ue(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await xo(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Ue(e.staging))throw new Error("Native move staging tree is missing");await xo(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await bn.rename(e.staging,e.destinationPaths.nativeRoot)}t=await OR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Ue(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=Sq(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Ue(e.sourcePaths.nativeRoot)&&await xo(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await nf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await Nq(e.destinationPaths);let n=await Ot(e.destinationPaths,e.pending.id);await La(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Vt(e.projectRoot,o),o}async function LR(e){let t=await Y(e.projectRoot)??Hn("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=Br(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let r=await re(e.projectRoot,t.native.artifact_root),n=await re(e.projectRoot,i);if($(r.nativeRoot,n.nativeRoot)||$(n.nativeRoot,r.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Ue(r.nativeRoot))throw new Error(`Native source root does not exist: ${r.nativeRoot}`);if(await wq(r),await Ue(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await cr(r,"root-move",`move root to ${i}`),o=vq(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=MR({id:o,paths:r,now:e.now??new Date}),l=DR(n,o);try{if(await yq(r,a.file),await bq(r),await Ue(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Vt(e.projectRoot,rf(t,s)),await _p(r,c),await e.hooks?.afterRootMoveStage?.("copying",c),await BR({projectRoot:e.projectRoot,config:rf(t,s),pending:s,sourcePaths:r,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:r.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await lr(a)}}async function qR(e){let t=await Y(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await re(e.projectRoot,i.fromArtifactRoot),n=await re(e.projectRoot,i.toArtifactRoot),a=DR(n,i.id),o=await Ue(r.nativeRoot)?r:n,s=await cr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await Iq(r,n,a,i.id)}catch(m){if(i.stage!=="copying"||!await Ue(r.nativeRoot))throw m;let p=MR({id:i.id,paths:r,now:new Date});await _p(r,p),c={journal:p,paths:r}}if(e.strategy==="continue"){let m=await BR({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:m}}if(!await Ue(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=jR(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Ue(n.nativeRoot)&&await xo(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await nf({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=jR(a,i.id);!t.native.pending_root_move?.cleanup&&await Ue(a)&&await xo(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await nf({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await Ot(r,i.id);await Tu(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Vt(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await lr(s)}}var Ao=4096,jq=4096,$q=1024;async function kn(e,t,i){try{let r=await $t({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function of(e,t){let i=new Map(e.map(r=>[Ke.resolve(r.file),{...r,file:Ke.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await bs(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await fp(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function Oq(e,t){let i=cc(e),r;try{await T(e.projectRoot,i);let n=await sc(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await ke(e,r.change)?[]:(await je(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await af.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function Hq(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function Dq(e,t){let i=[],r=[];for(let n of await kn(e,e.transactionsDir,jq)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await Ot(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ke.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Dn([e],`doctor archive recovery ${a.id}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,"archive.lock")}],i)?(await QP({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function Fq(e,t,i){let r=[];for(let n of await kn(e,e.locksDir,$q)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ke.join(e.locksDir,n.name);try{let o=await bs(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await fp(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function Mq(e,t,i=5){let r=[],n=t?await zv(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await zv(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Ke.join(e.changesDir,a.name,Ve)});continue}let o=await yn(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Ke.join(e.projectRoot,s.path)}:{}})}return r}async function Bq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await Ka(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await ek(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Ke.join(M(e,n),"trajectory.jsonl")})}return i}async function Lq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await Ns(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=On(e,n),s=ze(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Dn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Wt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await af.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Wt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await af.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await af.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function qq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Yp(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:Xa(e,n),repair:"migrate"});continue}let a=await je(e,n);await uk({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:Xa(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Xa(e,n)})}return i}async function Vq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Hc(e,n);try{let o=await Dc(e,n),s=await li(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Ke.join(e.changesDir,n,Ve)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:Ke.join(e.changesDir,n,Ve),repair:"migrate"});continue}await ER({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Ke.join(e.changesDir,n,Ve)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function Wq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Sr(e,n)}catch(o){if(o instanceof Cc)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:ht(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Dn([e],`doctor transition recovery ${n}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await hP(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:ht(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:ht(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:ht(e,n),repair:"continue"})}}return i}async function zq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=hn(e,n),o;try{o=await pn(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Dn([e],`doctor checkpoint recovery ${n}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await PP(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Bc(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Y(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([re(r.projectRoot,c.fromArtifactRoot),re(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await of([{paths:l,file:Ke.join(l.locksDir,"root-move.lock")},{paths:u,file:Ke.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await qR({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await re(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await Hq(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await Dq(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await Lq(r,{name:e.name,repair:t})),i.push(...await Vq(r,{name:e.name,repair:t})),i.push(...await qq(r,{name:e.name,repair:t})),i.push(...await Bq(r,{name:e.name,repair:t})),i.push(...await Wq(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await zq(r,{name:e.name,repair:t})),i.push(...await IR({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await Fq(r,t,s.unfinished)),i.push(...await Oq(r,t)),e.projectOnly||i.push(...await Mq(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{promises as VR}from"node:fs";function Jq(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Gq(e,t){let i=me(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function ji(e){let t=await gS(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=Gq(e.paths,t.state),n=await Gt({paths:e.paths,state:t.state}),a=fe(t.state,n),o=r.bindingState==="mismatch"?{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...a.runnerAction,kind:"none"}}:a;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:Jq(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{children:n.children,readyChildren:n.readyChildren}:{},continuation:o,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function WR(e){let t;try{t=await VR.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await VR.readFile(`${we(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}async function Lc(e,t){let i=await Gt({paths:e,state:t});return fe(t,i)}async function Uq(e){let t;try{t=await GR.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function Kq(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function zR(e,t){let i;try{i=await GR.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${Kq(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:cf.join(e.archiveDir,n.name)}:null}function Yq(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function sf(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function JR(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:cf.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function Xq(e,t){let i=[],r=[];for(let n of await XN(e)){let a=Vn(n);if(t&&a.change!==t)continue;let o=cf.join(e.transactionsDir,n);try{let s=await Cs(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function tg(e,t){let i=Bt(e,"--repair"),r=Ae(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new O("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();Se(e);let a=await sR(t),o=await Xq(a,n);if(n&&o.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let d=await ke(a,n)?await ji({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let m=await dc({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:m.transactionId},state:m.state,continuation:await Lc(a,m.state)})}let h=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Lc(a,h)})}return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await ke(a,n)){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([zR(a,n),Tm(a,n)]);if(u){let h=await ji({paths:a,name:n,details:!0});return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await ji({paths:a,name:n,details:!0});return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[JR(a,n)],continuation:h.continuation})}if(i){if(d){let m=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:m.schema,stateVersion:m.state_version},state:m,continuation:await Lc(a,m)})}let h=await ta({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:await Lc(a,h.state)})}let f=await ji({paths:a,name:n,details:!0});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Lc(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await WR(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");if(i){let k=await Bc({paths:a,repair:!0,projectOnly:!0}),b=[];for(let w of c.transactions)w.kind==="archive"?await dc({paths:a,name:w.change}):await xi({paths:a,name:w.change}),b.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await tg([],t),N=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...N,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await Uq(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[m,p,v,g,y]=await Promise.all([Promise.all(s.map(k=>ji({paths:a,name:k}))),Promise.all(s.map(k=>zR(a,k))),Promise.all(s.map(k=>Tm(a,k))),Promise.all(h.map(k=>Bc({paths:a,name:k}))),Bc({paths:a,projectOnly:!0})]),E=Yq([...p.filter(k=>k!==null),...s.flatMap((k,b)=>v[b]&&!f.has(k)?[JR(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:cf.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...g.flatMap(({findings:k})=>k),...y.findings]),S={healthy:E.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:m,legacyChanges:h,findings:E};return S.healthy?W("doctor",S):sf(S)}let l=await Bc({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?W("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}import{promises as s1}from"fs";import $i from"path";import{readFileSync as Qq}from"fs";import UR from"path";var Zq=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),e1=new Set(["glob","grep","listfiles","read","readfile","search","view"]),YR=["file_path","filePath","path","target_file","targetFile"],XR=["file_paths","filePaths","paths","files","targets"],QR=["operations","edits"],t1=["patch","diff","patchText","patch_text","changes"];function rg(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function KR(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function i1(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function r1(e){for(let t of["cwd","working_directory","workspaceRoot"]){let i=e[t];if(!(typeof i!="string"||!i.trim()||!UR.isAbsolute(i.trim())))return UR.resolve(i.trim())}}function n1(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function a1(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return n1(e[t]);return e}function ig(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let r of i)for(let n of e.matchAll(r)){let a=n[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function da(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)da(e,i);return}if(rg(t)){for(let i of YR)da(e,t[i]);for(let i of XR)da(e,t[i]);for(let i of QR)da(e,t[i])}}function o1(e,t){let i=[],r=[t,e].filter(rg);for(let n of r){for(let a of YR)da(i,n[a]);for(let a of XR)da(i,n[a]);for(let a of QR)da(i,n[a]);for(let a of t1){let o=n[a];typeof o=="string"&&i.push(...ig(o))}}return typeof t=="string"&&i.push(...ig(t)),[...new Set(i)]}function qc(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{let o=ig(e);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!rg(i))return{intent:"unknown",targets:[],toolName:null};let r=i1(i),n=o1(i,a1(i)),a=r1(i);return r&&Zq.has(KR(r))?{intent:n.length>0?"write":"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:r&&e1.has(KR(r))?{intent:"non-write",targets:[],toolName:r,...a?{cwd:a}:{}}:r?{intent:"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{}}}function ZR(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return qc("",e);try{return qc(Qq(0,"utf8"),e)}catch{return qc("",e)}}async function c1(e){let{projectRoot:t,paths:i,state:r,request:n}=e,a=we(i,r.name),o=[],s=[],c=!1,l=!1,u=!1;for(let d of n.targets){let f=$i.resolve(t,d);if(!fa(t,f)){u=!0;continue}let h=$i.relative(t,f).replaceAll("\\","/");if(h===".comet/config.yaml"){l=!0;continue}if(!fa(i.nativeRoot,f)){if(await Lu(t,f,[$i.join(t,".comet"),i.nativeRoot])){c=!0;continue}s.push(h);continue}if(!fa(a,f))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:r.phase,change:r.name};let m=$i.relative(a,f).replaceAll("\\","/");if(m==="brief.md"||m==="children.yaml"||m.startsWith("specs/")){o.push(m);continue}return{allowed:!1,reason:`${m||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:r.phase,change:r.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:r.phase,change:r.name}:o.length>0?r.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await nc({paths:i,name:r.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:r.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:r.phase,change:r.name}:s.length>0?r.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:r.phase,change:r.name}:r.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name}:r.phase==="verify"||r.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await no({paths:i,name:r.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:r.name}:{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in Build`,workflow:"native",phase:r.phase,change:r.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:r.phase,change:r.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}function fa(e,t){let i=$i.relative(e,t);return i===""||!i.startsWith("..")&&!$i.isAbsolute(i)}function l1(e,t,i){return i.targets.length>0&&i.targets.every(r=>{let n=$i.resolve(e,r);return fa(e,n)?$i.relative(e,n).replaceAll("\\","/")===".comet/config.yaml"||fa(t,n):!0})}async function u1(e){let t=await Y(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await re(e,t.native.artifact_root),r;try{r=await s1.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let n=[];for(let a of r.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await ke(i,a.name)){let o=await K(i,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await je(i,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:i,changes:n}}var d1=Bu("nativeActiveContext",e=>u1(e));async function eC(){let{intent:e,targets:t}=await ZR();return{intent:e,targets:t}}async function tC(e,t,i){let r=await d1(e);if(!r)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.changes.length===0)return{allowed:!0,reason:l1(e,r.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let n;if(i){if(n=r.changes.find(l=>l.state.name===i),!n)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(r.changes.length===1)n=r.changes[0];else{let l=await ES(r.paths);if(n=r.changes.find(u=>u.state.name===l),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return c1({projectRoot:e,paths:r.paths,state:n.state,request:t});let o=!1,s=!1,c=!1;for(let l of t.targets){let u=$i.resolve(e,l);if(!fa(e,u)){s=!0;continue}if($i.relative(e,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(fa(r.paths.nativeRoot,u)){o=!0;continue}if(await Lu(e,u,[$i.join(e,".comet"),r.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:`Native change ${a.name} is in ${a.phase}; implementation writes are only allowed in build. If this belongs to the current change, confirm the scope and run comet native next ${a.name} --summary "" --return-to-build; otherwise create or select a separate Native change`,workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}async function iC(e,t){let i=Ae(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new O("--hook-output must be copilot");Se(e);let r=await tC(t,await eC());return i==="copilot"?{command:"hook-guard",exitCode:0,data:r,text:r.allowed?`{} `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:r.reason})} -`}:r.allowed?{command:"hook-guard",exitCode:0,data:r}:{command:"hook-guard",exitCode:2,data:r,error:{code:"blocked",message:r.reason}}}async function iC(e,t){let i=Ae(e,"--root"),r=await Y(t),n=zd(e,r?.native.language??"en");if(Se(e),r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let a=Br(i??r?.native.artifact_root??"docs");if(r&&i&&r.native.artifact_root!==a)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${a}`);let o=r?{...r,native:{...r.native,language:n,snapshot:{...r.native.snapshot,exclude:yN(r.native.snapshot.exclude)}}}:Hn(a,n),s=await re(t,o.native.artifact_root);return await ou(s),await Wp(t),await Vt(t,o),W("init",{projectRoot:t,artifactRoot:o.native.artifact_root,nativeRoot:s.nativeRoot,language:n},`Initialized Comet Native at ${s.nativeRoot} -`)}async function rC(e,t){let i=rt(e,"change name"),r=await Y(t),n=zd(e,r?.native.language??"en"),a=Ae(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new O("--isolation must be current, branch, or worktree");let o=Ae(e,"--change-branch"),s=Ae(e,"--target-branch"),c=Ae(e,"--worktree-path");Se(e);let l=r;if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let u=await tR({projectRoot:t,name:i,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});t=u.projectRoot,r=await Y(t);let d=r===null?Hn("docs",n):void 0;if(r||(r=d),r.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let f=await re(t,r.native.artifact_root);await ou(f);let h=await Yk({paths:f,name:i,language:n,workspaceBinding:u.binding,...d?{initialProjectConfig:d}:{}});return await gd(f,h.name),W("new",{...h,preparation:u.preparation,continuation:de(h)},`Created Native change ${h.name} -`)}import{randomUUID as c1}from"node:crypto";import{promises as nC}from"node:fs";import l1 from"node:path";function ng(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ha(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function nr(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function aC(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,r)=>nr(i,`${t}[${r}]`))}function u1(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,i)=>{let r=ng(t,`Native Builder check ${i}`);if(ha(r,["name","result","note"],`Native Builder check ${i}`),!["passed","failed","not-run"].includes(String(r.result)))throw new Error(`Native Builder check ${i} result is invalid`);if(r.note!==null&&typeof r.note!="string")throw new Error(`Native Builder check ${i} note is invalid`);return{name:nr(r.name,`Native Builder check ${i} name`),result:r.result,note:r.note}})}function d1(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,i)=>{let r=ng(t,`Native Runtime check ${i}`);if(ha(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${i}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${i} argv is invalid`);if(!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1)throw new Error(`Native Runtime check ${i} timeoutMs is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Runtime check ${i} repeatable is invalid`);return{id:nr(r.id,`Native Runtime check ${i} id`),name:nr(r.name,`Native Runtime check ${i} name`),executable:nr(r.executable,`Native Runtime check ${i} executable`),argv:[...r.argv],cwdRef:nr(r.cwdRef,`Native Runtime check ${i} cwdRef`),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function oC(e,t){let i=e.stateVersion,r=e.iteration,n=e.attempt;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:i,iteration:r,attempt:n,verifierExecutionRef:nr(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function f1(e){let t=ng(e,"Native Runner input");if(t.kind==="builder-handoff")return ha(t,["kind","summary","addressed_acceptance_ids","checks","known_limits"],"Native Runner Builder input"),{kind:"builder-handoff",summary:nr(t.summary,"Native Builder summary"),addressed_acceptance_ids:aC(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:u1(t.checks),known_limits:aC(t.known_limits,"Native Builder known limits")};if(t.kind==="dispatch-verifier")return ha(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:d1(t.checks)};if(t.kind==="verifier-response")return ha(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return ha(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:nr(t.summary,"Native Verifier execution error summary"),...oC(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ha(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:nr(t.summary,"Native unavailable Verifier summary"),...oC(t,"Native Runner unavailable Verifier input")};throw new Error("Native Runner input kind is invalid")}async function lC(e,t){let i=l1.resolve(t,e),r=await nC.lstat(i);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await nC.readFile(i,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return f1(n)}function sC(e){return`${Ge}:${e}:${c1()}`}function Vc(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Ge)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function h1(e){return{iteration:e.iteration,summary:e.summary,addressedAcceptanceIds:[...e.addressed_acceptance_ids],checks:e.checks.map(t=>({name:t.name,result:t.result,note:t.note})),checksTruncated:e.checks_truncated,knownLimits:e.known_limits.map(t=>({...t})),knownLimitsTruncated:e.known_limits_truncated,submittedAt:e.submitted_at}}function cC(e,t,i){let r=Vc(e);return{coordination:Ge,change:e.name,candidateId:r.candidate_id,stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:i,briefRef:e.brief,specRefs:e.spec_changes.map(({capability:n,operation:a,source:o})=>({capability:n,operation:a,ref:o})),acceptance:e.acceptance.map(({id:n,source:a,text:o})=>({id:n,source:a,text:o})),builderHandoff:h1(r),runtimeChecks:t.map(n=>({...n}))}}async function rg(e){Vc(e.state);let t=await Ci(ae(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function uC(e){if(e.input.kind==="builder-handoff"){let c=Ys().captureExecutionIdentity({identityProvider:Ge,executionRef:sC("builder")}),l=await eS({paths:e.paths,name:e.name,input:{identity:c,summary:e.input.summary,addressedAcceptanceIds:e.input.addressed_acceptance_ids,checks:e.input.checks,knownLimits:e.input.known_limits}});return{state:l,checks:[],requestChecks:null,verifierDispatch:null,continuation:de(l)}}if(e.input.kind==="dispatch-verifier"){let s=await K(e.paths,e.name);if(s.builder_handoff!==null&&s.builder_handoff.identity_provider!==Ge){let d=await no({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:d,checks:[],requestChecks:null,verifierDispatch:null,continuation:de(d)}}Vc(s);let c=await aS({paths:e.paths,name:e.name,plans:e.input.checks}),l=sC("verifier"),u=await oS({paths:e.paths,name:e.name,checks:c.checks,verifierExecutionId:l});return{state:u,checks:c.checks,requestChecks:null,verifierDispatch:cC(u,c.checks,l),continuation:de(u)}}if(e.input.kind==="verifier-execution-error"){let s=await K(e.paths,e.name);Vc(s),await rg({paths:e.paths,state:s});let c=await cS({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:c,checks:[],requestChecks:null,verifierDispatch:null,continuation:de(c)}}if(e.input.kind==="verifier-unavailable"){let s=await lS({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:s,checks:s.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:de(s)}}let t=await K(e.paths,e.name),i=Vc(t),r=await rg({paths:e.paths,state:t}),n=Ys(),a=n.captureExecutionIdentity({identityProvider:Ge,executionRef:r}),o=await sS({paths:e.paths,name:e.name,envelope:n.envelopeVerifierResponse({candidateId:i.candidate_id,identity:a,payload:e.input.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures});return{...o,verifierDispatch:o.requestChecks===null?null:cC(o.state,o.checks,await rg({paths:e.paths,state:o.state})),continuation:de(o.state)}}async function _o(e,t){let i=await Gt({paths:e,state:t});return{...i?{children:i.children,readyChildren:i.readyChildren}:{},continuation:de(t,i)}}async function dC(e,t){let i=rt(e,"change name"),r=Ae(e,"--summary"),n=Ae(e,"--runner-input"),a=Bt(e,"--confirmed"),o=Bt(e,"--return-to-build"),s=Bt(e,"--retry-verifier"),c=Bt(e,"--resolve-verifier-blocker");if([a,o,s,c].filter(Boolean).length>1)throw new O("--confirmed, --return-to-build, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");Se(e);let l=await ir(t);if(!await ke(l.paths,i)){if(n)throw new O("--runner-input is only valid for portable Native changes");if(!r)throw new O("--summary is required");let h=await xi({paths:l.paths,name:i});return W("next",{state:h,migration:{completed:!0,summary:r},continuation:de(h)})}if(n){if(r||a||o||s||c)throw new O("--runner-input cannot be combined with --summary or Agent transition flags");let h=await ta({paths:l.paths,name:i,preserveRunningExecution:!0}),m=h.state;if(h.action==="await-user"||h.action==="done"||h.reason!=="available")return W("next",{state:m,recovery:h,...await _o(l.paths,m)});if(m.phase==="build"){let g=await Zn({paths:l.paths,state:m});if(g.drifted){let y=await nc({paths:l.paths,name:i,reason:g.reason??"Native confirmed requirements changed"});return W("next",{state:y,...await _o(l.paths,y)})}if(await Gt({paths:l.paths,state:m}))throw new O("Native parent Build advances child changes and does not accept a Builder handoff")}let p=await lC(n,t),v=await uC({paths:l.paths,name:i,input:p,maxVerifyFailures:l.config.native.max_verify_failures});return W("next",{...v,...await _o(l.paths,v.state),coordination:Ge})}let u=await ta({paths:l.paths,name:i}),d=u.state;if(!r)throw new O("--summary is required");let f;if(a)if(d.phase==="shape")f=await Zk({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-skill-coordinated-pass")f=await uS({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-verifier-unavailable")f=await dS({paths:l.paths,name:i,summary:r});else throw new O("--confirmed is only valid in Shape, for an accepted Skill-coordinated pass, or for a user-accepted degraded verification fallback");else if(o)f=await no({paths:l.paths,name:i,reason:r});else if(s)f=await hS({paths:l.paths,name:i});else if(c)f=await fS({paths:l.paths,name:i});else{if(u.reason!=="available")return W("next",{state:d,recovery:u,...await _o(l.paths,d)});if(d.phase==="build"){let h=await Zn({paths:l.paths,state:d});if(h.drifted)f=await nc({paths:l.paths,name:i,reason:h.reason??"Native confirmed requirements changed"});else{let m=await Gt({paths:l.paths,state:d});if(m)if(m.allDone&&!(d.loop.stage==="repairing"&&d.verification_result==="fail"))f=await tS({paths:l.paths,name:i,summary:r});else return W("next",{state:d,children:m.children,readyChildren:m.readyChildren,continuation:de(d,m)})}}return f?W("next",{state:f,...await _o(l.paths,f)}):{command:"next",exitCode:65,data:{state:d,continuation:de(d)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return W("next",{state:f,...await _o(l.paths,f)})}async function fC(e,t){let i=rt(e,"root subcommand");if(i==="show"){Se(e);let r=await Y(t);if(!r)throw new Error(".comet/config.yaml was not found");let n=await re(t,r.native.artifact_root);return W("root show",{projectRoot:t,artifactRoot:r.native.artifact_root,language:r.native.language,nativeRoot:n.nativeRoot,pendingRootMove:r.native.pending_root_move??null})}if(i==="move"){let r=rt(e,"artifact root");Se(e);let n=await BR({projectRoot:t,toArtifactRoot:r});return W("root move",n,`Moved Comet Native to ${n.toNativeRoot} -`)}throw new O(`Unknown root command: ${i}`)}async function hC(e,t){let i=rt(e,"change name");Se(e);let{config:r,paths:n}=await ir(t);await gd(n,i);let a=await ke(n,i)?await ji({paths:n,name:i}):await yn(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return W("select",{selected:i,continuation:a.continuation},`Selected Native change ${i} -`)}import{promises as pC}from"fs";import mC from"path";var vC=Ti.maxSpecs*4;async function p1(e,t){let i=mC.join(te(e,t),"specs"),r;try{r=await Wt({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await pC.opendir(i);try{for await(let s of o){if(a+=1,a>vC)throw new Error(`Native proposed specs directory exceeds ${vC} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Un(s.name);let c=mC.join(i,s.name,"spec.md");await T(e.nativeRoot,c);let l;try{l=await pC.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>Ti.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await r.verify(),n.sort()}async function gC(e,t){let i=te(e,t),r={},n=0;for(let a of await p1(e,t)){let o=await ee({root:i,ref:`specs/${a}/spec.md`,maxBytes:Ti.maxFileBytes});if(n+=o.size,n>Ti.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");r[a]=o.text}return r}async function wC(e,t){let i=rt(e,"change name");Se(e);let{paths:r}=await ir(t);if(await ke(r,i)){let u=await K(r,i),d=we(r,i),f=await ee({root:d,ref:u.brief,maxBytes:null,includeHash:!1}),h=[];for(let p of u.spec_changes){if(p.source===null)continue;let v=await ee({root:d,ref:p.source,maxBytes:null,includeHash:!1});h.push({capability:p.capability,operation:p.operation,source:p.source,content:v.text})}let m={state:u,brief:f.text,proposedSpecs:h,continuation:de(u,await Gt({paths:r,state:u}))};return W("show",m)}let n=await li(r,i);if(n.status==="migration-required")return W("show",{name:i,schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,migrationRequired:!0,message:n.message});if(n.status!=="current"||!n.state)throw new pr(n.schema,n.minimumRuntimeVersion);let a=n.state,o=te(r,i),s=await gC(r,i),c=await ee({root:o,ref:a.brief,maxBytes:Ti.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>nR)throw new Error("Native show output exceeds its serialized byte budget");return W("show",l)}async function yC(e,t){let i=rt(e,"spec subcommand");if(i!=="remove")throw new O(`Unknown spec command: ${i}`);let r=rt(e,"change name"),n=rt(e,"capability");Se(e);let{paths:a}=await ir(t);await ke(a,r)||await xi({paths:a,name:r});let o=await pS({paths:a,name:r,capability:n});return W("spec remove",{...o,continuation:de(o)},`Marked Native capability ${n} for removal in ${r} -`)}import Sn from"node:path";var m1=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function ag(e,t){let i=Sn.normalize(e),r=Sn.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function v1(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function NC(e){let t=[];for(let i of await Vv(e))t.push({name:i,kind:await ke(e,i)?"portable":"legacy"});return t}async function EC(e){let t=Zt(e),i=t.length>0?t:[Sn.resolve(e)];i.some(n=>ag(n,e))||i.push(Sn.resolve(e));let r=[];for(let n of[...new Set(i.map(a=>Sn.resolve(a)))].sort()){let a=await Y(n);if(!a)continue;let o=await re(n,a.native.artifact_root);r.push({projectRoot:n,config:a,paths:o,changes:await NC(o)})}if(r.length===0){let n=await Y(e);if(!n)throw new Error(".comet/config.yaml was not found in any registered worktree");let a=await re(e,n.native.artifact_root);r.push({projectRoot:Sn.resolve(e),config:n,paths:a,changes:await NC(a)})}return r}function bC(e,t){return e.workspace.bindingState==="aligned"?0:ag(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function PC(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable"){let u=await ji({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u}}return{source:c,name:n,kind:l,workspace:await Ku(c.paths,n),portableStatus:null}}));o.sort((c,l)=>bC(c,e)-bC(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>Qt.maxChanges)throw new Error(`Native status discovery exceeds ${Qt.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function kC(e,t){let i=t.toString(36),r=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function g1(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=m1.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function SC(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?v1(i):null,nextPageArgs:i}}async function w1(e,t,i){let r=null;try{r=await Kn(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:yn(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function RC(e,t,i){if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:ji({paths:e.source.paths,name:e.name,details:t})}return w1(e,t,i)}async function CC(e){let t=await EC(e.projectRoot),i=(await PC(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>ag(n.projectRoot,e.projectRoot))??t[0];return yn(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return RC(i[0],e.details??!1,e.acceptanceCursor)}async function xC(e){let t=await EC(e.projectRoot),i=await PC(e.projectRoot,t),r=D("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=g1({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Qt.maxItems).map(u=>RC(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,h=fQt.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c=0||e[0]==="help"){let o=e[0]==="help"?e.slice(1):i>=0?e.slice(0,i):[],s;try{s=Dv(o)}catch(c){throw new O(c.message)}return{command:s.topic?`${s.topic} --help`:"help",exitCode:0,data:s,text:s.usage}}let r=e.shift(),n=await aR(t),a=y1[r];if(!a)throw new O(`Unknown Native command: ${r}`);return a(e,n)}async function _C(e){let t=[...e],i=t.indexOf("--"),r=i<0?t:t.slice(0,i),n=i<0?[]:t.slice(i),a=r.includes("--json"),o,s=r[0]??null;try{Bt(r,"--json"),o=Ae(r,"--project-root");let c=[...r,...n];return s=c[0]??null,Mv(await N1(c,o),a)}catch(c){return Mv(sR(s,c),a)}}async function k1(e=process.argv.slice(2)){let t=await _C(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(` +`}:r.allowed?{command:"hook-guard",exitCode:0,data:r}:{command:"hook-guard",exitCode:2,data:r,error:{code:"blocked",message:r.reason}}}async function rC(e,t){let i=Ae(e,"--root"),r=await Y(t),n=zd(e,r?.native.language??"en");if(Se(e),r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let a=Br(i??r?.native.artifact_root??"docs");if(r&&i&&r.native.artifact_root!==a)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${a}`);let o=r?{...r,native:{...r.native,language:n,snapshot:{...r.native.snapshot,exclude:NN(r.native.snapshot.exclude)}}}:Hn(a,n),s=await re(t,o.native.artifact_root);return await ou(s),await Wp(t),await Vt(t,o),W("init",{projectRoot:t,artifactRoot:o.native.artifact_root,nativeRoot:s.nativeRoot,language:n},`Initialized Comet Native at ${s.nativeRoot} +`)}async function nC(e,t){let i=rt(e,"change name"),r=await Y(t),n=zd(e,r?.native.language??"en"),a=Ae(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new O("--isolation must be current, branch, or worktree");let o=Ae(e,"--change-branch"),s=Ae(e,"--target-branch"),c=Ae(e,"--worktree-path");Se(e);let l=r;if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let u=await iR({projectRoot:t,name:i,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});t=u.projectRoot,r=await Y(t);let d=r===null?Hn("docs",n):void 0;if(r||(r=d),r.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let f=await re(t,r.native.artifact_root);await ou(f);let h=await Xk({paths:f,name:i,language:n,workspaceBinding:u.binding,...d?{initialProjectConfig:d}:{}});return await gd(f,h.name),W("new",{...h,preparation:u.preparation,continuation:fe(h)},`Created Native change ${h.name} +`)}import{randomUUID as f1}from"node:crypto";import{promises as aC}from"node:fs";import h1 from"node:path";function ag(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ha(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function nr(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function oC(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,r)=>nr(i,`${t}[${r}]`))}function p1(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,i)=>{let r=ag(t,`Native Builder check ${i}`);if(ha(r,["name","result","note"],`Native Builder check ${i}`),!["passed","failed","not-run"].includes(String(r.result)))throw new Error(`Native Builder check ${i} result is invalid`);if(r.note!==null&&typeof r.note!="string")throw new Error(`Native Builder check ${i} note is invalid`);return{name:nr(r.name,`Native Builder check ${i} name`),result:r.result,note:r.note}})}function m1(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,i)=>{let r=ag(t,`Native Runtime check ${i}`);if(ha(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${i}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${i} argv is invalid`);if(!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1)throw new Error(`Native Runtime check ${i} timeoutMs is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Runtime check ${i} repeatable is invalid`);return{id:nr(r.id,`Native Runtime check ${i} id`),name:nr(r.name,`Native Runtime check ${i} name`),executable:nr(r.executable,`Native Runtime check ${i} executable`),argv:[...r.argv],cwdRef:nr(r.cwdRef,`Native Runtime check ${i} cwdRef`),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function sC(e,t){let i=e.stateVersion,r=e.iteration,n=e.attempt;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:i,iteration:r,attempt:n,verifierExecutionRef:nr(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function v1(e){let t=ag(e,"Native Runner input");if(t.kind==="builder-handoff")return ha(t,["kind","summary","addressed_acceptance_ids","checks","known_limits"],"Native Runner Builder input"),{kind:"builder-handoff",summary:nr(t.summary,"Native Builder summary"),addressed_acceptance_ids:oC(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:p1(t.checks),known_limits:oC(t.known_limits,"Native Builder known limits")};if(t.kind==="dispatch-verifier")return ha(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:m1(t.checks)};if(t.kind==="verifier-response")return ha(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return ha(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:nr(t.summary,"Native Verifier execution error summary"),...sC(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ha(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:nr(t.summary,"Native unavailable Verifier summary"),...sC(t,"Native Runner unavailable Verifier input")};throw new Error("Native Runner input kind is invalid")}async function uC(e,t){let i=h1.resolve(t,e),r=await aC.lstat(i);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await aC.readFile(i,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return v1(n)}function cC(e){return`${Ge}:${e}:${f1()}`}function Vc(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Ge)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function g1(e){return{iteration:e.iteration,summary:e.summary,addressedAcceptanceIds:[...e.addressed_acceptance_ids],checks:e.checks.map(t=>({name:t.name,result:t.result,note:t.note})),checksTruncated:e.checks_truncated,knownLimits:e.known_limits.map(t=>({...t})),knownLimitsTruncated:e.known_limits_truncated,submittedAt:e.submitted_at}}function lC(e,t,i){let r=Vc(e);return{coordination:Ge,change:e.name,candidateId:r.candidate_id,stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:i,briefRef:e.brief,specRefs:e.spec_changes.map(({capability:n,operation:a,source:o})=>({capability:n,operation:a,ref:o})),acceptance:e.acceptance.map(({id:n,source:a,text:o})=>({id:n,source:a,text:o})),builderHandoff:g1(r),runtimeChecks:t.map(n=>({...n}))}}async function ng(e){Vc(e.state);let t=await Ci(ae(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function dC(e){if(e.input.kind==="builder-handoff"){let c=Ys().captureExecutionIdentity({identityProvider:Ge,executionRef:cC("builder")}),l=await tS({paths:e.paths,name:e.name,input:{identity:c,summary:e.input.summary,addressedAcceptanceIds:e.input.addressed_acceptance_ids,checks:e.input.checks,knownLimits:e.input.known_limits}});return{state:l,checks:[],requestChecks:null,verifierDispatch:null,continuation:fe(l)}}if(e.input.kind==="dispatch-verifier"){let s=await K(e.paths,e.name);if(s.builder_handoff!==null&&s.builder_handoff.identity_provider!==Ge){let d=await no({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:d,checks:[],requestChecks:null,verifierDispatch:null,continuation:fe(d)}}Vc(s);let c=await oS({paths:e.paths,name:e.name,plans:e.input.checks}),l=cC("verifier"),u=await sS({paths:e.paths,name:e.name,checks:c.checks,verifierExecutionId:l});return{state:u,checks:c.checks,requestChecks:null,verifierDispatch:lC(u,c.checks,l),continuation:fe(u)}}if(e.input.kind==="verifier-execution-error"){let s=await K(e.paths,e.name);Vc(s),await ng({paths:e.paths,state:s});let c=await lS({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:c,checks:[],requestChecks:null,verifierDispatch:null,continuation:fe(c)}}if(e.input.kind==="verifier-unavailable"){let s=await uS({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:s,checks:s.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:fe(s)}}let t=await K(e.paths,e.name),i=Vc(t),r=await ng({paths:e.paths,state:t}),n=Ys(),a=n.captureExecutionIdentity({identityProvider:Ge,executionRef:r}),o=await cS({paths:e.paths,name:e.name,envelope:n.envelopeVerifierResponse({candidateId:i.candidate_id,identity:a,payload:e.input.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures});return{...o,verifierDispatch:o.requestChecks===null?null:lC(o.state,o.checks,await ng({paths:e.paths,state:o.state})),continuation:fe(o.state)}}async function _o(e,t){let i=await Gt({paths:e,state:t});return{...i?{children:i.children,readyChildren:i.readyChildren}:{},continuation:fe(t,i)}}async function fC(e,t){let i=rt(e,"change name"),r=Ae(e,"--summary"),n=Ae(e,"--runner-input"),a=Bt(e,"--confirmed"),o=Bt(e,"--return-to-build"),s=Bt(e,"--retry-verifier"),c=Bt(e,"--resolve-verifier-blocker");if([a,o,s,c].filter(Boolean).length>1)throw new O("--confirmed, --return-to-build, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");Se(e);let l=await ir(t);if(!await ke(l.paths,i)){if(n)throw new O("--runner-input is only valid for portable Native changes");if(!r)throw new O("--summary is required");let h=await xi({paths:l.paths,name:i});return W("next",{state:h,migration:{completed:!0,summary:r},continuation:fe(h)})}if(n){if(r||a||o||s||c)throw new O("--runner-input cannot be combined with --summary or Agent transition flags");let h=await ta({paths:l.paths,name:i,preserveRunningExecution:!0}),m=h.state;if(h.action==="await-user"||h.action==="done"||h.reason!=="available")return W("next",{state:m,recovery:h,...await _o(l.paths,m)});if(m.phase==="build"){let g=await Zn({paths:l.paths,state:m});if(g.drifted){let y=await nc({paths:l.paths,name:i,reason:g.reason??"Native confirmed requirements changed"});return W("next",{state:y,...await _o(l.paths,y)})}if(await Gt({paths:l.paths,state:m}))throw new O("Native parent Build advances child changes and does not accept a Builder handoff")}let p=await uC(n,t),v=await dC({paths:l.paths,name:i,input:p,maxVerifyFailures:l.config.native.max_verify_failures});return W("next",{...v,...await _o(l.paths,v.state),coordination:Ge})}let u=await ta({paths:l.paths,name:i}),d=u.state;if(!r)throw new O("--summary is required");let f;if(a)if(d.phase==="shape")f=await eS({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-skill-coordinated-pass")f=await dS({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-verifier-unavailable")f=await fS({paths:l.paths,name:i,summary:r});else throw new O("--confirmed is only valid in Shape, for an accepted Skill-coordinated pass, or for a user-accepted degraded verification fallback");else if(o)f=await no({paths:l.paths,name:i,reason:r});else if(s)f=await pS({paths:l.paths,name:i});else if(c)f=await hS({paths:l.paths,name:i});else{if(u.reason!=="available")return W("next",{state:d,recovery:u,...await _o(l.paths,d)});if(d.phase==="build"){let h=await Zn({paths:l.paths,state:d});if(h.drifted)f=await nc({paths:l.paths,name:i,reason:h.reason??"Native confirmed requirements changed"});else{let m=await Gt({paths:l.paths,state:d});if(m)if(m.allDone&&!(d.loop.stage==="repairing"&&d.verification_result==="fail"))f=await iS({paths:l.paths,name:i,summary:r});else return W("next",{state:d,children:m.children,readyChildren:m.readyChildren,continuation:fe(d,m)})}}return f?W("next",{state:f,...await _o(l.paths,f)}):{command:"next",exitCode:65,data:{state:d,continuation:fe(d)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return W("next",{state:f,...await _o(l.paths,f)})}async function hC(e,t){let i=rt(e,"root subcommand");if(i==="show"){Se(e);let r=await Y(t);if(!r)throw new Error(".comet/config.yaml was not found");let n=await re(t,r.native.artifact_root);return W("root show",{projectRoot:t,artifactRoot:r.native.artifact_root,language:r.native.language,nativeRoot:n.nativeRoot,pendingRootMove:r.native.pending_root_move??null})}if(i==="move"){let r=rt(e,"artifact root");Se(e);let n=await LR({projectRoot:t,toArtifactRoot:r});return W("root move",n,`Moved Comet Native to ${n.toNativeRoot} +`)}throw new O(`Unknown root command: ${i}`)}async function pC(e,t){let i=rt(e,"change name");Se(e);let{config:r,paths:n}=await ir(t);await gd(n,i);let a=await ke(n,i)?await ji({paths:n,name:i}):await yn(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return W("select",{selected:i,continuation:a.continuation},`Selected Native change ${i} +`)}import{promises as mC}from"fs";import vC from"path";var gC=Ti.maxSpecs*4;async function w1(e,t){let i=vC.join(te(e,t),"specs"),r;try{r=await Wt({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await mC.opendir(i);try{for await(let s of o){if(a+=1,a>gC)throw new Error(`Native proposed specs directory exceeds ${gC} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Un(s.name);let c=vC.join(i,s.name,"spec.md");await T(e.nativeRoot,c);let l;try{l=await mC.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>Ti.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await r.verify(),n.sort()}async function wC(e,t){let i=te(e,t),r={},n=0;for(let a of await w1(e,t)){let o=await ee({root:i,ref:`specs/${a}/spec.md`,maxBytes:Ti.maxFileBytes});if(n+=o.size,n>Ti.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");r[a]=o.text}return r}async function yC(e,t){let i=rt(e,"change name");Se(e);let{paths:r}=await ir(t);if(await ke(r,i)){let u=await K(r,i),d=we(r,i),f=await ee({root:d,ref:u.brief,maxBytes:null,includeHash:!1}),h=[];for(let p of u.spec_changes){if(p.source===null)continue;let v=await ee({root:d,ref:p.source,maxBytes:null,includeHash:!1});h.push({capability:p.capability,operation:p.operation,source:p.source,content:v.text})}let m={state:u,brief:f.text,proposedSpecs:h,continuation:fe(u,await Gt({paths:r,state:u}))};return W("show",m)}let n=await li(r,i);if(n.status==="migration-required")return W("show",{name:i,schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,migrationRequired:!0,message:n.message});if(n.status!=="current"||!n.state)throw new pr(n.schema,n.minimumRuntimeVersion);let a=n.state,o=te(r,i),s=await wC(r,i),c=await ee({root:o,ref:a.brief,maxBytes:Ti.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>aR)throw new Error("Native show output exceeds its serialized byte budget");return W("show",l)}async function NC(e,t){let i=rt(e,"spec subcommand");if(i!=="remove")throw new O(`Unknown spec command: ${i}`);let r=rt(e,"change name"),n=rt(e,"capability");Se(e);let{paths:a}=await ir(t);await ke(a,r)||await xi({paths:a,name:r});let o=await mS({paths:a,name:r,capability:n});return W("spec remove",{...o,continuation:fe(o)},`Marked Native capability ${n} for removal in ${r} +`)}import Sn from"node:path";var y1=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function og(e,t){let i=Sn.normalize(e),r=Sn.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function N1(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function bC(e){let t=[];for(let i of await Wv(e))t.push({name:i,kind:await ke(e,i)?"portable":"legacy"});return t}async function PC(e){let t=Zt(e),i=t.length>0?t:[Sn.resolve(e)];i.some(n=>og(n,e))||i.push(Sn.resolve(e));let r=[];for(let n of[...new Set(i.map(a=>Sn.resolve(a)))].sort()){let a=await Y(n);if(!a)continue;let o=await re(n,a.native.artifact_root);r.push({projectRoot:n,config:a,paths:o,changes:await bC(o)})}if(r.length===0){let n=await Y(e);if(!n)throw new Error(".comet/config.yaml was not found in any registered worktree");let a=await re(e,n.native.artifact_root);r.push({projectRoot:Sn.resolve(e),config:n,paths:a,changes:await bC(a)})}return r}function kC(e,t){return e.workspace.bindingState==="aligned"?0:og(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function RC(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable"){let u=await ji({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u}}return{source:c,name:n,kind:l,workspace:await Ku(c.paths,n),portableStatus:null}}));o.sort((c,l)=>kC(c,e)-kC(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>Qt.maxChanges)throw new Error(`Native status discovery exceeds ${Qt.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function SC(e,t){let i=t.toString(36),r=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function b1(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=y1.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function EC(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?N1(i):null,nextPageArgs:i}}async function k1(e,t,i){let r=null;try{r=await Kn(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:yn(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function CC(e,t,i){if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:ji({paths:e.source.paths,name:e.name,details:t})}return k1(e,t,i)}async function xC(e){let t=await PC(e.projectRoot),i=(await RC(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>og(n.projectRoot,e.projectRoot))??t[0];return yn(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return CC(i[0],e.details??!1,e.acceptanceCursor)}async function AC(e){let t=await PC(e.projectRoot),i=await RC(e.projectRoot,t),r=D("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=b1({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Qt.maxItems).map(u=>CC(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,h=fQt.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c=0||e[0]==="help"){let o=e[0]==="help"?e.slice(1):i>=0?e.slice(0,i):[],s;try{s=Fv(o)}catch(c){throw new O(c.message)}return{command:s.topic?`${s.topic} --help`:"help",exitCode:0,data:s,text:s.usage}}let r=e.shift(),n=await oR(t),a=S1[r];if(!a)throw new O(`Unknown Native command: ${r}`);return a(e,n)}async function TC(e){let t=[...e],i=t.indexOf("--"),r=i<0?t:t.slice(0,i),n=i<0?[]:t.slice(i),a=r.includes("--json"),o,s=r[0]??null;try{Bt(r,"--json"),o=Ae(r,"--project-root");let c=[...r,...n];return s=c[0]??null,Bv(await E1(c,o),a)}catch(c){return Bv(cR(s,c),a)}}async function R1(e=process.argv.slice(2)){let t=await TC(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(` `)?"":` -`)),t.exitCode}var TC=process.argv[1];TC&&import.meta.url===b1(TC).href&&k1().then(e=>{process.exitCode=e});export{k1 as main}; +`)),t.exitCode}var IC=process.argv[1];IC&&import.meta.url===P1(IC).href&&R1().then(e=>{process.exitCode=e});export{R1 as main}; diff --git a/assets/skills/comet-native/scripts/comet-native-spec.mjs b/assets/skills/comet-native/scripts/comet-native-spec.mjs index 32d23daad..cbccb410d 100644 --- a/assets/skills/comet-native/scripts/comet-native-spec.mjs +++ b/assets/skills/comet-native/scripts/comet-native-spec.mjs @@ -1,17 +1,17 @@ #!/usr/bin/env node import { createRequire as __cometCreateRequire } from 'module'; const require = __cometCreateRequire(import.meta.url); -var Ld=Object.create;var us=Object.defineProperty;var Md=Object.getOwnPropertyDescriptor;var Fd=Object.getOwnPropertyNames;var Vd=Object.getPrototypeOf,qd=Object.prototype.hasOwnProperty;var $i=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var Wd=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fd(e))!qd.call(t,n)&&n!==i&&us(t,n,{get:()=>e[n],enumerable:!(r=Md(e,n))||r.enumerable});return t};var jt=(t,e,i)=>(i=t!=null?Ld(Vd(t)):{},Wd(e||!t||!t.__esModule?us(i,"default",{value:t,enumerable:!0}):i,t));var P=g(H=>{"use strict";var jn=Symbol.for("yaml.alias"),ms=Symbol.for("yaml.document"),Bi=Symbol.for("yaml.map"),vs=Symbol.for("yaml.pair"),$n=Symbol.for("yaml.scalar"),Li=Symbol.for("yaml.seq"),Se=Symbol.for("yaml.node.type"),cf=t=>!!t&&typeof t=="object"&&t[Se]===jn,lf=t=>!!t&&typeof t=="object"&&t[Se]===ms,uf=t=>!!t&&typeof t=="object"&&t[Se]===Bi,df=t=>!!t&&typeof t=="object"&&t[Se]===vs,gs=t=>!!t&&typeof t=="object"&&t[Se]===$n,ff=t=>!!t&&typeof t=="object"&&t[Se]===Li;function ws(t){if(t&&typeof t=="object")switch(t[Se]){case Bi:case Li:return!0}return!1}function hf(t){if(t&&typeof t=="object")switch(t[Se]){case jn:case Bi:case $n:case Li:return!0}return!1}var pf=t=>(gs(t)||ws(t))&&!!t.anchor;H.ALIAS=jn;H.DOC=ms;H.MAP=Bi;H.NODE_TYPE=Se;H.PAIR=vs;H.SCALAR=$n;H.SEQ=Li;H.hasAnchor=pf;H.isAlias=cf;H.isCollection=ws;H.isDocument=lf;H.isMap=uf;H.isNode=hf;H.isPair=df;H.isScalar=gs;H.isSeq=ff});var Ht=g(On=>{"use strict";var O=P(),q=Symbol("break visit"),ys=Symbol("skip children"),fe=Symbol("remove node");function Mi(t,e){let i=Ns(e);O.isDocument(t)?st(null,t.contents,i,Object.freeze([t]))===fe&&(t.contents=null):st(null,t,i,Object.freeze([]))}Mi.BREAK=q;Mi.SKIP=ys;Mi.REMOVE=fe;function st(t,e,i,r){let n=bs(t,e,i,r);if(O.isNode(n)||O.isPair(n))return ks(t,r,n),st(t,n,i,r);if(typeof n!="symbol"){if(O.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a{"use strict";var Ss=P(),mf=Ht(),vf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},gf=t=>t.replace(/[!,[\]{}]/g,e=>vf[e]),Dt=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||i(`The ${e} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,r]of Object.entries(this.tags))if(e.startsWith(r))return i+gf(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(e&&r.length>0&&Ss.isNode(e.contents)){let a={};mf.visit(e.contents,(o,s)=>{Ss.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(` -`)}};Dt.defaultYaml={explicit:!1,version:"1.2"};Dt.defaultTags={"!!":"tag:yaml.org,2002:"};Es.Directives=Dt});var Vi=g(Bt=>{"use strict";var Ps=P(),wf=Ht();function yf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function xs(t){let e=new Set;return wf.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function Cs(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function Nf(t,e){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=xs(t));let o=Cs(e,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Ps.isScalar(o.node)||Ps.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}}Bt.anchorIsValid=yf;Bt.anchorNames=xs;Bt.createNodeAnchors=Nf;Bt.findNewAnchor=Cs});var Dn=g(Rs=>{"use strict";function Lt(t,e,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var bf=P();function As(t,e,i){if(Array.isArray(t))return t.map((r,n)=>As(r,String(n),i));if(t&&typeof t.toJSON=="function"){if(!i||!bf.hasAnchor(t))return t.toJSON(e,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(t,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=t.toJSON(e,i);return i.onCreate&&i.onCreate(n),n}return typeof t=="bigint"&&!i?.keep?Number(t):t}_s.toJS=As});var qi=g(Is=>{"use strict";var kf=Dn(),Ts=P(),Sf=Ie(),Bn=class{constructor(e){Object.defineProperty(this,Ts.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Ts.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=Sf.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?kf.applyReviver(a,{"":s},"",s):s}};Is.NodeBase=Bn});var Mt=g(js=>{"use strict";var Ef=Vi(),Pf=Ht(),lt=P(),xf=qi(),Cf=Ie(),Ln=class extends xf.NodeBase{constructor(e){super(lt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],Pf.visit(e,{Node:(a,o)=>{(lt.isAlias(o)||lt.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(e,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Cf.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=Wi(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,r){let n=`*${this.source}`;if(e){if(Ef.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Wi(t,e,i){if(lt.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(lt.isCollection(e)){let r=0;for(let n of e.items){let a=Wi(t,n,i);a>r&&(r=a)}return r}else if(lt.isPair(e)){let r=Wi(t,e.key,i),n=Wi(t,e.value,i);return Math.max(r,n)}return 1}js.Alias=Ln});var I=g(Mn=>{"use strict";var Rf=P(),Af=qi(),_f=Ie(),Tf=t=>!t||typeof t!="function"&&typeof t!="object",je=class extends Af.NodeBase{constructor(e){super(Rf.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:_f.toJS(this.value,e,i)}toString(){return String(this.value)}};je.BLOCK_FOLDED="BLOCK_FOLDED";je.BLOCK_LITERAL="BLOCK_LITERAL";je.PLAIN="PLAIN";je.QUOTE_DOUBLE="QUOTE_DOUBLE";je.QUOTE_SINGLE="QUOTE_SINGLE";Mn.Scalar=je;Mn.isScalarValue=Tf});var Ft=g(Os=>{"use strict";var If=Mt(),Je=P(),$s=I(),jf="tag:yaml.org,2002:";function $f(t,e,i){if(e){let r=i.filter(a=>a.tag===e),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return i.find(r=>r.identify?.(t)&&!r.format)}function Of(t,e,i){if(Je.isDocument(t)&&(t=t.contents),Je.isNode(t))return t;if(Je.isPair(t)){let d=i.schema[Je.MAP].createNode?.(i.schema,null,i);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new If.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=jf+e.slice(2));let l=$f(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new $s.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[Je.MAP]:Symbol.iterator in Object(t)?o[Je.SEQ]:o[Je.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new $s.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Os.createNode=Of});var Ji=g(zi=>{"use strict";var Hf=Ft(),he=P(),Df=qi();function Fn(t,e,i){let r=i;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Hf.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Hs=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Vn=class extends Df.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(r=>he.isNode(r)||he.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(Hs(e))this.add(i);else{let[r,...n]=e,a=this.get(r,!0);if(he.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){let[i,...r]=e;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(he.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(e,i){let[r,...n]=e,a=this.get(r,!0);return n.length===0?!i&&he.isScalar(a)?a.value:a:he.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!he.isPair(i))return!1;let r=i.value;return r==null||e&&he.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[i,...r]=e;if(r.length===0)return this.has(i);let n=this.get(i,!0);return he.isCollection(n)?n.hasIn(r):!1}setIn(e,i){let[r,...n]=e;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(he.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};zi.Collection=Vn;zi.collectionFromPath=Fn;zi.isEmptyPath=Hs});var Vt=g(Gi=>{"use strict";var Bf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function qn(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Lf=(t,e,i)=>t.endsWith(` +var Md=Object.create;var us=Object.defineProperty;var Fd=Object.getOwnPropertyDescriptor;var Vd=Object.getOwnPropertyNames;var qd=Object.getPrototypeOf,Wd=Object.prototype.hasOwnProperty;var $i=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var zd=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vd(e))!Wd.call(t,n)&&n!==i&&us(t,n,{get:()=>e[n],enumerable:!(r=Fd(e,n))||r.enumerable});return t};var jt=(t,e,i)=>(i=t!=null?Md(qd(t)):{},zd(e||!t||!t.__esModule?us(i,"default",{value:t,enumerable:!0}):i,t));var P=g(H=>{"use strict";var jn=Symbol.for("yaml.alias"),ms=Symbol.for("yaml.document"),Bi=Symbol.for("yaml.map"),vs=Symbol.for("yaml.pair"),$n=Symbol.for("yaml.scalar"),Li=Symbol.for("yaml.seq"),Se=Symbol.for("yaml.node.type"),lf=t=>!!t&&typeof t=="object"&&t[Se]===jn,uf=t=>!!t&&typeof t=="object"&&t[Se]===ms,df=t=>!!t&&typeof t=="object"&&t[Se]===Bi,ff=t=>!!t&&typeof t=="object"&&t[Se]===vs,gs=t=>!!t&&typeof t=="object"&&t[Se]===$n,hf=t=>!!t&&typeof t=="object"&&t[Se]===Li;function ws(t){if(t&&typeof t=="object")switch(t[Se]){case Bi:case Li:return!0}return!1}function pf(t){if(t&&typeof t=="object")switch(t[Se]){case jn:case Bi:case $n:case Li:return!0}return!1}var mf=t=>(gs(t)||ws(t))&&!!t.anchor;H.ALIAS=jn;H.DOC=ms;H.MAP=Bi;H.NODE_TYPE=Se;H.PAIR=vs;H.SCALAR=$n;H.SEQ=Li;H.hasAnchor=mf;H.isAlias=lf;H.isCollection=ws;H.isDocument=uf;H.isMap=df;H.isNode=pf;H.isPair=ff;H.isScalar=gs;H.isSeq=hf});var Ht=g(On=>{"use strict";var O=P(),q=Symbol("break visit"),ys=Symbol("skip children"),fe=Symbol("remove node");function Mi(t,e){let i=Ns(e);O.isDocument(t)?st(null,t.contents,i,Object.freeze([t]))===fe&&(t.contents=null):st(null,t,i,Object.freeze([]))}Mi.BREAK=q;Mi.SKIP=ys;Mi.REMOVE=fe;function st(t,e,i,r){let n=bs(t,e,i,r);if(O.isNode(n)||O.isPair(n))return ks(t,r,n),st(t,n,i,r);if(typeof n!="symbol"){if(O.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a{"use strict";var Ss=P(),vf=Ht(),gf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},wf=t=>t.replace(/[!,[\]{}]/g,e=>gf[e]),Dt=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||i(`The ${e} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,r]of Object.entries(this.tags))if(e.startsWith(r))return i+wf(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(e&&r.length>0&&Ss.isNode(e.contents)){let a={};vf.visit(e.contents,(o,s)=>{Ss.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(` +`)}};Dt.defaultYaml={explicit:!1,version:"1.2"};Dt.defaultTags={"!!":"tag:yaml.org,2002:"};Es.Directives=Dt});var Vi=g(Bt=>{"use strict";var Ps=P(),yf=Ht();function Nf(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function xs(t){let e=new Set;return yf.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function Rs(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function bf(t,e){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=xs(t));let o=Rs(e,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Ps.isScalar(o.node)||Ps.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}}Bt.anchorIsValid=Nf;Bt.anchorNames=xs;Bt.createNodeAnchors=bf;Bt.findNewAnchor=Rs});var Dn=g(Cs=>{"use strict";function Lt(t,e,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n{"use strict";var kf=P();function As(t,e,i){if(Array.isArray(t))return t.map((r,n)=>As(r,String(n),i));if(t&&typeof t.toJSON=="function"){if(!i||!kf.hasAnchor(t))return t.toJSON(e,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(t,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=t.toJSON(e,i);return i.onCreate&&i.onCreate(n),n}return typeof t=="bigint"&&!i?.keep?Number(t):t}_s.toJS=As});var qi=g(Is=>{"use strict";var Sf=Dn(),Ts=P(),Ef=Ie(),Bn=class{constructor(e){Object.defineProperty(this,Ts.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Ts.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=Ef.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Sf.applyReviver(a,{"":s},"",s):s}};Is.NodeBase=Bn});var Mt=g(js=>{"use strict";var Pf=Vi(),xf=Ht(),lt=P(),Rf=qi(),Cf=Ie(),Ln=class extends Rf.NodeBase{constructor(e){super(lt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],xf.visit(e,{Node:(a,o)=>{(lt.isAlias(o)||lt.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(e,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Cf.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=Wi(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,i,r){let n=`*${this.source}`;if(e){if(Pf.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Wi(t,e,i){if(lt.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(lt.isCollection(e)){let r=0;for(let n of e.items){let a=Wi(t,n,i);a>r&&(r=a)}return r}else if(lt.isPair(e)){let r=Wi(t,e.key,i),n=Wi(t,e.value,i);return Math.max(r,n)}return 1}js.Alias=Ln});var I=g(Mn=>{"use strict";var Af=P(),_f=qi(),Tf=Ie(),If=t=>!t||typeof t!="function"&&typeof t!="object",je=class extends _f.NodeBase{constructor(e){super(Af.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:Tf.toJS(this.value,e,i)}toString(){return String(this.value)}};je.BLOCK_FOLDED="BLOCK_FOLDED";je.BLOCK_LITERAL="BLOCK_LITERAL";je.PLAIN="PLAIN";je.QUOTE_DOUBLE="QUOTE_DOUBLE";je.QUOTE_SINGLE="QUOTE_SINGLE";Mn.Scalar=je;Mn.isScalarValue=If});var Ft=g(Os=>{"use strict";var jf=Mt(),Je=P(),$s=I(),$f="tag:yaml.org,2002:";function Of(t,e,i){if(e){let r=i.filter(a=>a.tag===e),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return i.find(r=>r.identify?.(t)&&!r.format)}function Hf(t,e,i){if(Je.isDocument(t)&&(t=t.contents),Je.isNode(t))return t;if(Je.isPair(t)){let d=i.schema[Je.MAP].createNode?.(i.schema,null,i);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new jf.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=$f+e.slice(2));let l=Of(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new $s.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[Je.MAP]:Symbol.iterator in Object(t)?o[Je.SEQ]:o[Je.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new $s.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Os.createNode=Hf});var Ji=g(zi=>{"use strict";var Df=Ft(),he=P(),Bf=qi();function Fn(t,e,i){let r=i;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Df.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Hs=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Vn=class extends Bf.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(r=>he.isNode(r)||he.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(Hs(e))this.add(i);else{let[r,...n]=e,a=this.get(r,!0);if(he.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){let[i,...r]=e;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(he.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(e,i){let[r,...n]=e,a=this.get(r,!0);return n.length===0?!i&&he.isScalar(a)?a.value:a:he.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!he.isPair(i))return!1;let r=i.value;return r==null||e&&he.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[i,...r]=e;if(r.length===0)return this.has(i);let n=this.get(i,!0);return he.isCollection(n)?n.hasIn(r):!1}setIn(e,i){let[r,...n]=e;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(he.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};zi.Collection=Vn;zi.collectionFromPath=Fn;zi.isEmptyPath=Hs});var Vt=g(Gi=>{"use strict";var Lf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function qn(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Mf=(t,e,i)=>t.endsWith(` `)?qn(i,e):i.includes(` `)?` -`+qn(i,e):(t.endsWith(" ")?"":" ")+i;Gi.indentComment=qn;Gi.lineComment=Lf;Gi.stringifyComment=Bf});var Bs=g(qt=>{"use strict";var Mf="flow",Wn="block",Ui="quoted";function Ff(t,e,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;nn-Math.max(2,a)?l.push(0):d=n-r);let u,p,v=!1,h=-1,m=-1,w=-1;i===Wn&&(h=Ds(t,h,e.length),h!==-1&&(d=h+c));for(let b;b=t[h+=1];){if(i===Ui&&b==="\\"){switch(m=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===` +`+qn(i,e):(t.endsWith(" ")?"":" ")+i;Gi.indentComment=qn;Gi.lineComment=Mf;Gi.stringifyComment=Lf});var Bs=g(qt=>{"use strict";var Ff="flow",Wn="block",Ui="quoted";function Vf(t,e,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;nn-Math.max(2,a)?l.push(0):d=n-r);let u,p,v=!1,h=-1,m=-1,w=-1;i===Wn&&(h=Ds(t,h,e.length),h!==-1&&(d=h+c));for(let b;b=t[h+=1];){if(i===Ui&&b==="\\"){switch(m=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===` `)i===Wn&&(h=Ds(t,h,e.length)),d=h+e.length+c,u=void 0;else{if(b===" "&&p&&p!==" "&&p!==` `&&p!==" "){let k=t[h+1];k&&k!==" "&&k!==` `&&k!==" "&&(u=h)}if(h>=d)if(u)l.push(u),d=u+c,u=void 0;else if(i===Ui){for(;p===" "||p===" ";)p=b,b=t[h+=1],v=!0;let k=h>w+1?h-2:m-1;if(f[k])return t;l.push(k),f[k]=!0,d=k+c,u=void 0}else v=!0}p=b}if(v&&s&&s(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let b=0;b{"use strict";var ne=I(),$e=Bs(),Yi=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Xi=t=>/^(%|---|\.\.\.)/m.test(t);function Vf(t,e,i){if(!e||e<0)return!1;let r=e-i,n=t.length;if(n<=r)return!1;for(let a=0,o=0;a{"use strict";var ne=I(),$e=Bs(),Yi=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Xi=t=>/^(%|---|\.\.\.)/m.test(t);function qf(t,e,i){if(!e||e<0)return!1;let r=e-i,n=t.length;if(n<=r)return!1;for(let a=0,o=0;ar)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Wt(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(Xi(t)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let f=i.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length `;let d,u;for(u=i.length;u>0;--u){let S=i[u-1];if(S!==` `&&S!==" "&&S!==" ")break}let p=i.substring(u),v=p.indexOf(` `);v===-1?d="-":i===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(i=i.slice(0,-p.length),p[p.length-1]===` `&&(p=p.slice(0,-1)),p=p.replace(Jn,`$&${l}`));let h=!1,m,w=-1;for(m=0;m{E=!0});let N=$e.foldFlowLines(`${y}${S}${p}`,l,$e.FOLD_BLOCK,R);if(!E)return`>${k} +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C=Yi(r,!0);o!=="folded"&&e!==ne.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{E=!0});let N=$e.foldFlowLines(`${y}${S}${p}`,l,$e.FOLD_BLOCK,C);if(!E)return`>${k} ${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k} -${l}${y}${i}${p}`}function qf(t,e,i,r){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=e;if(s&&a.includes(` +${l}${y}${i}${p}`}function Wf(t,e,i,r){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=e;if(s&&a.includes(` `)||f&&/[[\]{},]/.test(a))return ut(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(` `)?ut(a,e):Ki(t,e,i,r);if(!s&&!f&&n!==ne.Scalar.PLAIN&&a.includes(` `))return Ki(t,e,i,r);if(Xi(a)){if(c==="")return e.forceBlockIndent=!0,Ki(t,e,i,r);if(s&&c===l)return ut(a,e)}let d=a.replace(/\n+/g,`$& -${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=e.doc.schema;if(v.some(u)||p?.some(u))return ut(a,e)}return s?d:$e.foldFlowLines(d,c,$e.FOLD_FLOW,Yi(e,!1))}function Wf(t,e,i,r){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==ne.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ne.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case ne.Scalar.BLOCK_FOLDED:case ne.Scalar.BLOCK_LITERAL:return n||a?ut(o.value,e):Ki(o,e,i,r);case ne.Scalar.QUOTE_DOUBLE:return Wt(o.value,e);case ne.Scalar.QUOTE_SINGLE:return zn(o.value,e);case ne.Scalar.PLAIN:return qf(o,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=e.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Ls.stringifyString=Wf});var Jt=g(Gn=>{"use strict";var zf=Vi(),Oe=P(),Jf=Vt(),Gf=zt();function Uf(t,e){let i=Object.assign({blockQuote:!0,commentString:Jf.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function Kf(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let i,r;if(Oe.isScalar(e)){r=e.value;let n=t.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===e.format)??n.find(a=>!a.format)}else r=e,i=t.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function Yf(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Oe.isScalar(t)||Oe.isCollection(t))&&t.anchor;a&&zf.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function Xf(t,e,i,r){if(Oe.isPair(t))return t.toString(e,i,r);if(Oe.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Oe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=Kf(e.doc.schema.tags,a));let o=Yf(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,i,r):Oe.isScalar(a)?Gf.stringifyString(a,e,i,r):a.toString(e,i,r);return o?Oe.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} -${e.indent}${s}`:s}Gn.createStringifyContext=Uf;Gn.stringify=Xf});var qs=g(Vs=>{"use strict";var Ee=P(),Ms=I(),Fs=Jt(),Gt=Vt();function Qf({key:t,value:e},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=i,u=Ee.isNode(t)&&t.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(Ee.isCollection(t)||!Ee.isNode(t)&&typeof t=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!t||u&&e==null&&!i.inFlow||Ee.isCollection(t)||(Ee.isScalar(t)?t.type===Ms.Scalar.BLOCK_FOLDED||t.type===Ms.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Fs.stringify(t,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||e==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||e==null&&p)return m=`? ${m}`,u&&!v?m+=Gt.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=Gt.lineComment(m,i.indent,l(u))),m=`? ${m} +${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=e.doc.schema;if(v.some(u)||p?.some(u))return ut(a,e)}return s?d:$e.foldFlowLines(d,c,$e.FOLD_FLOW,Yi(e,!1))}function zf(t,e,i,r){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==ne.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ne.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case ne.Scalar.BLOCK_FOLDED:case ne.Scalar.BLOCK_LITERAL:return n||a?ut(o.value,e):Ki(o,e,i,r);case ne.Scalar.QUOTE_DOUBLE:return Wt(o.value,e);case ne.Scalar.QUOTE_SINGLE:return zn(o.value,e);case ne.Scalar.PLAIN:return Wf(o,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=e.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Ls.stringifyString=zf});var Jt=g(Gn=>{"use strict";var Jf=Vi(),Oe=P(),Gf=Vt(),Uf=zt();function Kf(t,e){let i=Object.assign({blockQuote:!0,commentString:Gf.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function Yf(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let i,r;if(Oe.isScalar(e)){r=e.value;let n=t.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===e.format)??n.find(a=>!a.format)}else r=e,i=t.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function Xf(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Oe.isScalar(t)||Oe.isCollection(t))&&t.anchor;a&&Jf.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function Qf(t,e,i,r){if(Oe.isPair(t))return t.toString(e,i,r);if(Oe.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Oe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=Yf(e.doc.schema.tags,a));let o=Xf(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,i,r):Oe.isScalar(a)?Uf.stringifyString(a,e,i,r):a.toString(e,i,r);return o?Oe.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o} +${e.indent}${s}`:s}Gn.createStringifyContext=Kf;Gn.stringify=Qf});var qs=g(Vs=>{"use strict";var Ee=P(),Ms=I(),Fs=Jt(),Gt=Vt();function Zf({key:t,value:e},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=i,u=Ee.isNode(t)&&t.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(Ee.isCollection(t)||!Ee.isNode(t)&&typeof t=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!d&&(!t||u&&e==null&&!i.inFlow||Ee.isCollection(t)||(Ee.isScalar(t)?t.type===Ms.Scalar.BLOCK_FOLDED||t.type===Ms.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Fs.stringify(t,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||e==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||e==null&&p)return m=`? ${m}`,u&&!v?m+=Gt.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=Gt.lineComment(m,i.indent,l(u))),m=`? ${m} ${s}:`):(m=`${m}:`,u&&(m+=Gt.lineComment(m,i.indent,l(u))));let w,y,b;Ee.isNode(e)?(w=!!e.spaceBefore,y=e.commentBefore,b=e.comment):(w=!1,y=null,b=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!p&&!u&&Ee.isScalar(e)&&(i.indentAtStart=m.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!p&&Ee.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let k=!1,S=Fs.stringify(e,i,()=>k=!0,()=>h=!0),E=" ";if(u||w||y){if(E=w?` -`:"",y){let R=l(y);E+=` -${Gt.indentComment(R,i.indent)}`}S===""&&!i.inFlow?E===` +`:"",y){let C=l(y);E+=` +${Gt.indentComment(C,i.indent)}`}S===""&&!i.inFlow?E===` `&&b&&(E=` `):E+=` -${i.indent}`}else if(!p&&Ee.isCollection(e)){let R=S[0],N=S.indexOf(` -`),j=N!==-1,_e=i.inFlow??e.flow??e.items.length===0;if(j||!_e){let ot=!1;if(j&&(R==="&"||R==="!")){let $=S.indexOf(" ");R==="&"&&$!==-1&&${"use strict";var Ws=$i("process");function Zf(t,...e){t==="debug"&&console.log(...e)}function eh(t,e){(t==="debug"||t==="warn")&&(typeof Ws.emitWarning=="function"?Ws.emitWarning(e):console.warn(e))}Un.debug=Zf;Un.warn=eh});var ir=g(tr=>{"use strict";var er=P(),zs=I(),Qi="<<",Zi={identify:t=>t===Qi||typeof t=="symbol"&&t.description===Qi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new zs.Scalar(Symbol(Qi)),{addToJSMap:Js}),stringify:()=>Qi},th=(t,e)=>(Zi.identify(e)||er.isScalar(e)&&(!e.type||e.type===zs.Scalar.PLAIN)&&Zi.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===Zi.tag&&i.default);function Js(t,e,i){let r=Gs(t,i);if(er.isSeq(r))for(let n of r.items)Yn(t,e,n);else if(Array.isArray(r))for(let n of r)Yn(t,e,n);else Yn(t,e,r)}function Yn(t,e,i){let r=Gs(t,i);if(!er.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Gs(t,e){return t&&er.isAlias(e)?e.resolve(t.doc,t):e}tr.addMergeToJSMap=Js;tr.isMergeKey=th;tr.merge=Zi});var Qn=g(Ys=>{"use strict";var ih=Kn(),Us=ir(),rh=Jt(),Ks=P(),Xn=Ie();function nh(t,e,{key:i,value:r}){if(Ks.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(Us.isMergeKey(t,i))Us.addMergeToJSMap(t,e,r);else{let n=Xn.toJS(i,"",t);if(e instanceof Map)e.set(n,Xn.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let a=ah(i,n,t),o=Xn.toJS(r,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function ah(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Ks.isNode(t)&&i?.doc){let r=rh.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=t.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),ih.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(e)}Ys.addPairToJSMap=nh});var He=g(Zn=>{"use strict";var Xs=Ft(),oh=qs(),sh=Qn(),rr=P();function ch(t,e,i){let r=Xs.createNode(t,void 0,i),n=Xs.createNode(e,void 0,i);return new nr(r,n)}var nr=class t{constructor(e,i=null){Object.defineProperty(this,rr.NODE_TYPE,{value:rr.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return rr.isNode(i)&&(i=i.clone(e)),rr.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return sh.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?oh.stringifyPair(this,e,i,r):JSON.stringify(this)}};Zn.Pair=nr;Zn.createPair=ch});var ea=g(Zs=>{"use strict";var Ge=P(),Qs=Jt(),ar=Vt();function lh(t,e,i){return(e.inFlow??t.flow?dh:uh)(t,e,i)}function uh({comment:t,items:e},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:a,type:null}),d=!1,u=[];for(let v=0;vm=null,()=>d=!0);m&&(w+=ar.lineComment(w,a,l(m))),d&&m&&(d=!1),u.push(r+w)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v{"use strict";var Ws=$i("process");function eh(t,...e){t==="debug"&&console.log(...e)}function th(t,e){(t==="debug"||t==="warn")&&(typeof Ws.emitWarning=="function"?Ws.emitWarning(e):console.warn(e))}Un.debug=eh;Un.warn=th});var ir=g(tr=>{"use strict";var er=P(),zs=I(),Qi="<<",Zi={identify:t=>t===Qi||typeof t=="symbol"&&t.description===Qi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new zs.Scalar(Symbol(Qi)),{addToJSMap:Js}),stringify:()=>Qi},ih=(t,e)=>(Zi.identify(e)||er.isScalar(e)&&(!e.type||e.type===zs.Scalar.PLAIN)&&Zi.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===Zi.tag&&i.default);function Js(t,e,i){let r=Gs(t,i);if(er.isSeq(r))for(let n of r.items)Yn(t,e,n);else if(Array.isArray(r))for(let n of r)Yn(t,e,n);else Yn(t,e,r)}function Yn(t,e,i){let r=Gs(t,i);if(!er.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Gs(t,e){return t&&er.isAlias(e)?e.resolve(t.doc,t):e}tr.addMergeToJSMap=Js;tr.isMergeKey=ih;tr.merge=Zi});var Qn=g(Ys=>{"use strict";var rh=Kn(),Us=ir(),nh=Jt(),Ks=P(),Xn=Ie();function ah(t,e,{key:i,value:r}){if(Ks.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(Us.isMergeKey(t,i))Us.addMergeToJSMap(t,e,r);else{let n=Xn.toJS(i,"",t);if(e instanceof Map)e.set(n,Xn.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let a=oh(i,n,t),o=Xn.toJS(r,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function oh(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Ks.isNode(t)&&i?.doc){let r=nh.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=t.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),rh.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(e)}Ys.addPairToJSMap=ah});var He=g(Zn=>{"use strict";var Xs=Ft(),sh=qs(),ch=Qn(),rr=P();function lh(t,e,i){let r=Xs.createNode(t,void 0,i),n=Xs.createNode(e,void 0,i);return new nr(r,n)}var nr=class t{constructor(e,i=null){Object.defineProperty(this,rr.NODE_TYPE,{value:rr.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return rr.isNode(i)&&(i=i.clone(e)),rr.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return ch.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?sh.stringifyPair(this,e,i,r):JSON.stringify(this)}};Zn.Pair=nr;Zn.createPair=lh});var ea=g(Zs=>{"use strict";var Ge=P(),Qs=Jt(),ar=Vt();function uh(t,e,i){return(e.inFlow??t.flow?fh:dh)(t,e,i)}function dh({comment:t,items:e},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:a,type:null}),d=!1,u=[];for(let v=0;vm=null,()=>d=!0);m&&(w+=ar.lineComment(w,a,l(m))),d&&m&&(d=!1),u.push(r+w)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;vm=null);l||(l=d.length>f||w.includes(` +`+ar.indentComment(l(t),c),s&&s()):d&&o&&o(),p}function fh({items:t},e,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;r+=a;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,f=0,d=[];for(let v=0;vm=null);l||(l=d.length>f||w.includes(` `)),v0&&(l||(l=d.reduce((y,b)=>y+b.length+2,2)+(w.length+2)>e.options.lineWidth)),l&&(w+=",")),m&&(w+=ar.lineComment(w,r,s(m))),d.push(w),f=d.length}let{start:u,end:p}=i;if(d.length===0)return u+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&v>e.options.lineWidth}if(l){let v=u;for(let h of d)v+=h?` ${a}${n}${h}`:` `;return`${v} -${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function or({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ar.indentComment(e(r),t);i.push(a.trimStart())}}Zs.stringifyCollection=lh});var Be=g(ia=>{"use strict";var fh=ea(),hh=Qn(),ph=Ji(),De=P(),sr=He(),mh=I();function Ut(t,e){let i=De.isScalar(e)?e.value:e;for(let r of t)if(De.isPair(r)&&(r.key===e||r.key===i||De.isScalar(r.key)&&r.key.value===i))return r}var ta=class extends ph.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(De.MAP,e),this.items=[]}static from(e,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(e),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(sr.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,i){let r;De.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new sr.Pair(e,e?.value):r=new sr.Pair(e.key,e.value);let n=Ut(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);De.isScalar(n.value)&&mh.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let i=Ut(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=Ut(this.items,e)?.value;return(!i&&De.isScalar(n)?n.value:n)??void 0}has(e){return!!Ut(this.items,e)}set(e,i){this.add(new sr.Pair(e,i),!0)}toJSON(e,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)hh.addPairToJSMap(i,n,a);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!De.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),fh.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};ia.YAMLMap=ta;ia.findPair=Ut});var dt=g(tc=>{"use strict";var vh=P(),ec=Be(),gh={collection:"map",default:!0,nodeClass:ec.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return vh.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>ec.YAMLMap.from(t,e,i)};tc.map=gh});var Le=g(ic=>{"use strict";var wh=Ft(),yh=ea(),Nh=Ji(),lr=P(),bh=I(),kh=Ie(),ra=class extends Nh.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(lr.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=cr(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=cr(e);if(typeof r!="number")return;let n=this.items[r];return!i&&lr.isScalar(n)?n.value:n}has(e){let i=cr(e);return typeof i=="number"&&i=0?e:null}ic.YAMLSeq=ra});var ft=g(nc=>{"use strict";var Sh=P(),rc=Le(),Eh={collection:"seq",default:!0,nodeClass:rc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Sh.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>rc.YAMLSeq.from(t,e,i)};nc.seq=Eh});var Kt=g(ac=>{"use strict";var Ph=zt(),xh={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,r){return e=Object.assign({actualString:!0},e),Ph.stringifyString(t,e,i,r)}};ac.string=xh});var ur=g(cc=>{"use strict";var oc=I(),sc={identify:t=>t==null,createNode:()=>new oc.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new oc.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&sc.test.test(t)?t:e.options.nullStr};cc.nullTag=sc});var na=g(uc=>{"use strict";var Ch=I(),lc={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Ch.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&lc.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};uc.boolTag=lc});var ht=g(dc=>{"use strict";function Rh({format:t,minFractionDigits:e,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}dc.stringifyNumber=Rh});var oa=g(dr=>{"use strict";var Ah=I(),aa=ht(),_h={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:aa.stringifyNumber},Th={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():aa.stringifyNumber(t)}},Ih={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Ah.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:aa.stringifyNumber};dr.float=Ih;dr.floatExp=Th;dr.floatNaN=_h});var ca=g(hr=>{"use strict";var fc=ht(),fr=t=>typeof t=="bigint"||Number.isInteger(t),sa=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function hc(t,e,i){let{value:r}=t;return fr(r)&&r>=0?i+r.toString(e):fc.stringifyNumber(t)}var jh={identify:t=>fr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>sa(t,2,8,i),stringify:t=>hc(t,8,"0o")},$h={identify:fr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>sa(t,0,10,i),stringify:fc.stringifyNumber},Oh={identify:t=>fr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>sa(t,2,16,i),stringify:t=>hc(t,16,"0x")};hr.int=$h;hr.intHex=Oh;hr.intOct=jh});var mc=g(pc=>{"use strict";var Hh=dt(),Dh=ur(),Bh=ft(),Lh=Kt(),Mh=na(),la=oa(),ua=ca(),Fh=[Hh.map,Bh.seq,Lh.string,Dh.nullTag,Mh.boolTag,ua.intOct,ua.int,ua.intHex,la.floatNaN,la.floatExp,la.float];pc.schema=Fh});var wc=g(gc=>{"use strict";var Vh=I(),qh=dt(),Wh=ft();function vc(t){return typeof t=="bigint"||Number.isInteger(t)}var pr=({value:t})=>JSON.stringify(t),zh=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:pr},{identify:t=>t==null,createNode:()=>new Vh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:pr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:pr},{identify:vc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>vc(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:pr}],Jh={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Gh=[qh.map,Wh.seq].concat(zh,Jh);gc.schema=Gh});var fa=g(yc=>{"use strict";var Yt=$i("buffer"),da=I(),Uh=zt(),Kh={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Yt.Buffer=="function")return Yt.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n{"use strict";var mr=P(),ha=He(),Yh=I(),Xh=Le();function Nc(t,e){if(mr.isSeq(t))for(let i=0;i1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new ha.Pair(new Yh.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} +${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function or({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ar.indentComment(e(r),t);i.push(a.trimStart())}}Zs.stringifyCollection=uh});var Be=g(ia=>{"use strict";var hh=ea(),ph=Qn(),mh=Ji(),De=P(),sr=He(),vh=I();function Ut(t,e){let i=De.isScalar(e)?e.value:e;for(let r of t)if(De.isPair(r)&&(r.key===e||r.key===i||De.isScalar(r.key)&&r.key.value===i))return r}var ta=class extends mh.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(De.MAP,e),this.items=[]}static from(e,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(e),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(sr.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,i){let r;De.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new sr.Pair(e,e?.value):r=new sr.Pair(e.key,e.value);let n=Ut(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);De.isScalar(n.value)&&vh.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let i=Ut(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=Ut(this.items,e)?.value;return(!i&&De.isScalar(n)?n.value:n)??void 0}has(e){return!!Ut(this.items,e)}set(e,i){this.add(new sr.Pair(e,i),!0)}toJSON(e,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)ph.addPairToJSMap(i,n,a);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!De.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),hh.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};ia.YAMLMap=ta;ia.findPair=Ut});var dt=g(tc=>{"use strict";var gh=P(),ec=Be(),wh={collection:"map",default:!0,nodeClass:ec.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return gh.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>ec.YAMLMap.from(t,e,i)};tc.map=wh});var Le=g(ic=>{"use strict";var yh=Ft(),Nh=ea(),bh=Ji(),lr=P(),kh=I(),Sh=Ie(),ra=class extends bh.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(lr.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=cr(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=cr(e);if(typeof r!="number")return;let n=this.items[r];return!i&&lr.isScalar(n)?n.value:n}has(e){let i=cr(e);return typeof i=="number"&&i=0?e:null}ic.YAMLSeq=ra});var ft=g(nc=>{"use strict";var Eh=P(),rc=Le(),Ph={collection:"seq",default:!0,nodeClass:rc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Eh.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>rc.YAMLSeq.from(t,e,i)};nc.seq=Ph});var Kt=g(ac=>{"use strict";var xh=zt(),Rh={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,r){return e=Object.assign({actualString:!0},e),xh.stringifyString(t,e,i,r)}};ac.string=Rh});var ur=g(cc=>{"use strict";var oc=I(),sc={identify:t=>t==null,createNode:()=>new oc.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new oc.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&sc.test.test(t)?t:e.options.nullStr};cc.nullTag=sc});var na=g(uc=>{"use strict";var Ch=I(),lc={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Ch.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&lc.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};uc.boolTag=lc});var ht=g(dc=>{"use strict";function Ah({format:t,minFractionDigits:e,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}dc.stringifyNumber=Ah});var oa=g(dr=>{"use strict";var _h=I(),aa=ht(),Th={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:aa.stringifyNumber},Ih={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():aa.stringifyNumber(t)}},jh={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new _h.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:aa.stringifyNumber};dr.float=jh;dr.floatExp=Ih;dr.floatNaN=Th});var ca=g(hr=>{"use strict";var fc=ht(),fr=t=>typeof t=="bigint"||Number.isInteger(t),sa=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function hc(t,e,i){let{value:r}=t;return fr(r)&&r>=0?i+r.toString(e):fc.stringifyNumber(t)}var $h={identify:t=>fr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>sa(t,2,8,i),stringify:t=>hc(t,8,"0o")},Oh={identify:fr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>sa(t,0,10,i),stringify:fc.stringifyNumber},Hh={identify:t=>fr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>sa(t,2,16,i),stringify:t=>hc(t,16,"0x")};hr.int=Oh;hr.intHex=Hh;hr.intOct=$h});var mc=g(pc=>{"use strict";var Dh=dt(),Bh=ur(),Lh=ft(),Mh=Kt(),Fh=na(),la=oa(),ua=ca(),Vh=[Dh.map,Lh.seq,Mh.string,Bh.nullTag,Fh.boolTag,ua.intOct,ua.int,ua.intHex,la.floatNaN,la.floatExp,la.float];pc.schema=Vh});var wc=g(gc=>{"use strict";var qh=I(),Wh=dt(),zh=ft();function vc(t){return typeof t=="bigint"||Number.isInteger(t)}var pr=({value:t})=>JSON.stringify(t),Jh=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:pr},{identify:t=>t==null,createNode:()=>new qh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:pr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:pr},{identify:vc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>vc(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:pr}],Gh={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Uh=[Wh.map,zh.seq].concat(Jh,Gh);gc.schema=Uh});var fa=g(yc=>{"use strict";var Yt=$i("buffer"),da=I(),Kh=zt(),Yh={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Yt.Buffer=="function")return Yt.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n{"use strict";var mr=P(),ha=He(),Xh=I(),Qh=Le();function Nc(t,e){if(mr.isSeq(t))for(let i=0;i1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new ha.Pair(new Xh.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore} ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment} -${a.comment}`:r.comment}r=n}t.items[i]=mr.isPair(r)?r:new ha.Pair(r)}}else e("Expected a sequence for this tag");return t}function bc(t,e,i){let{replacer:r}=i,n=new Xh.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ha.createPair(s,c,i))}return n}var Qh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Nc,createNode:bc};vr.createPairs=bc;vr.pairs=Qh;vr.resolvePairs=Nc});var va=g(ma=>{"use strict";var kc=P(),pa=Ie(),Xt=Be(),Zh=Le(),Sc=gr(),Ue=class t extends Zh.YAMLSeq{constructor(){super(),this.add=Xt.YAMLMap.prototype.add.bind(this),this.delete=Xt.YAMLMap.prototype.delete.bind(this),this.get=Xt.YAMLMap.prototype.get.bind(this),this.has=Xt.YAMLMap.prototype.has.bind(this),this.set=Xt.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(kc.isPair(n)?(a=pa.toJS(n.key,"",i),o=pa.toJS(n.value,a,i)):a=pa.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(e,i,r){let n=Sc.createPairs(e,i,r),a=new this;return a.items=n.items,a}};Ue.tag="tag:yaml.org,2002:omap";var ep={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ue,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Sc.resolvePairs(t,e),r=[];for(let{key:n}of i.items)kc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ue,i)},createNode:(t,e,i)=>Ue.from(t,e,i)};ma.YAMLOMap=Ue;ma.omap=ep});var Rc=g(ga=>{"use strict";var Ec=I();function Pc({value:t,source:e},i){return e&&(t?xc:Cc).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var xc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Ec.Scalar(!0),stringify:Pc},Cc={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Ec.Scalar(!1),stringify:Pc};ga.falseTag=Cc;ga.trueTag=xc});var Ac=g(wr=>{"use strict";var tp=I(),wa=ht(),ip={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:wa.stringifyNumber},rp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():wa.stringifyNumber(t)}},np={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new tp.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let r=t.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:wa.stringifyNumber};wr.float=np;wr.floatExp=rp;wr.floatNaN=ip});var Tc=g(Zt=>{"use strict";var _c=ht(),Qt=t=>typeof t=="bigint"||Number.isInteger(t);function yr(t,e,i,{intAsBigInt:r}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return n==="-"?-1*a:a}function ya(t,e,i){let{value:r}=t;if(Qt(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return _c.stringifyNumber(t)}var ap={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>yr(t,2,2,i),stringify:t=>ya(t,2,"0b")},op={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>yr(t,1,8,i),stringify:t=>ya(t,8,"0")},sp={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>yr(t,0,10,i),stringify:_c.stringifyNumber},cp={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>yr(t,2,16,i),stringify:t=>ya(t,16,"0x")};Zt.int=sp;Zt.intBin=ap;Zt.intHex=cp;Zt.intOct=op});var ba=g(Na=>{"use strict";var kr=P(),Nr=He(),br=Be(),Ke=class t extends br.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;kr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Nr.Pair(e.key,null):i=new Nr.Pair(e,null),br.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=br.findPair(this.items,e);return!i&&kr.isPair(r)?kr.isScalar(r.key)?r.key.value:r.key:r}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=br.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Nr.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(e,i,r){let{replacer:n}=r,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Nr.createPair(o,null,r));return a}};Ke.tag="tag:yaml.org,2002:set";var lp={collection:"map",identify:t=>t instanceof Set,nodeClass:Ke,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ke.from(t,e,i),resolve(t,e){if(kr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ke,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Na.YAMLSet=Ke;Na.set=lp});var Sa=g(Sr=>{"use strict";var up=ht();function ka(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=o=>e?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Ic(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return up.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var dp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>ka(t,i),stringify:Ic},fp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ka(t,!1),stringify:Ic},jc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(jc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),f=e[8];if(f&&f!=="Z"){let d=ka(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Sr.floatTime=fp;Sr.intTime=dp;Sr.timestamp=jc});var Hc=g(Oc=>{"use strict";var hp=dt(),pp=ur(),mp=ft(),vp=Kt(),gp=fa(),$c=Rc(),Ea=Ac(),Er=Tc(),wp=ir(),yp=va(),Np=gr(),bp=ba(),Pa=Sa(),kp=[hp.map,mp.seq,vp.string,pp.nullTag,$c.trueTag,$c.falseTag,Er.intBin,Er.intOct,Er.int,Er.intHex,Ea.floatNaN,Ea.floatExp,Ea.float,gp.binary,wp.merge,yp.omap,Np.pairs,bp.set,Pa.intTime,Pa.floatTime,Pa.timestamp];Oc.schema=kp});var Jc=g(Ra=>{"use strict";var Mc=dt(),Sp=ur(),Fc=ft(),Ep=Kt(),Pp=na(),xa=oa(),Ca=ca(),xp=mc(),Cp=wc(),Vc=fa(),ei=ir(),qc=va(),Wc=gr(),Dc=Hc(),zc=ba(),Pr=Sa(),Bc=new Map([["core",xp.schema],["failsafe",[Mc.map,Fc.seq,Ep.string]],["json",Cp.schema],["yaml11",Dc.schema],["yaml-1.1",Dc.schema]]),Lc={binary:Vc.binary,bool:Pp.boolTag,float:xa.float,floatExp:xa.floatExp,floatNaN:xa.floatNaN,floatTime:Pr.floatTime,int:Ca.int,intHex:Ca.intHex,intOct:Ca.intOct,intTime:Pr.intTime,map:Mc.map,merge:ei.merge,null:Sp.nullTag,omap:qc.omap,pairs:Wc.pairs,seq:Fc.seq,set:zc.set,timestamp:Pr.timestamp},Rp={"tag:yaml.org,2002:binary":Vc.binary,"tag:yaml.org,2002:merge":ei.merge,"tag:yaml.org,2002:omap":qc.omap,"tag:yaml.org,2002:pairs":Wc.pairs,"tag:yaml.org,2002:set":zc.set,"tag:yaml.org,2002:timestamp":Pr.timestamp};function Ap(t,e,i){let r=Bc.get(e);if(r&&!t)return i&&!r.includes(ei.merge)?r.concat(ei.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(Bc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat(ei.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Lc[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Lc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Ra.coreKnownTags=Rp;Ra.getTags=Ap});var Ta=g(Gc=>{"use strict";var Aa=P(),_p=dt(),Tp=ft(),Ip=Kt(),xr=Jc(),jp=(t,e)=>t.keye.key?1:0,_a=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?xr.getTags(e,"compat"):e?xr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?xr.coreKnownTags:{},this.tags=xr.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Aa.MAP,{value:_p.map}),Object.defineProperty(this,Aa.SCALAR,{value:Ip.string}),Object.defineProperty(this,Aa.SEQ,{value:Tp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?jp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Gc.Schema=_a});var Kc=g(Uc=>{"use strict";var $p=P(),Ia=Jt(),ti=Vt();function Op(t,e){let i=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&i.push("---");let n=Ia.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(ti.indentComment(c,""))}let o=!1,s=null;if(t.contents){if($p.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let f=a(t.contents.commentBefore);i.push(ti.indentComment(f,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Ia.stringify(t.contents,n,()=>s=null,c);s&&(l+=ti.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ia.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(` +${a.comment}`:r.comment}r=n}t.items[i]=mr.isPair(r)?r:new ha.Pair(r)}}else e("Expected a sequence for this tag");return t}function bc(t,e,i){let{replacer:r}=i,n=new Qh.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ha.createPair(s,c,i))}return n}var Zh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Nc,createNode:bc};vr.createPairs=bc;vr.pairs=Zh;vr.resolvePairs=Nc});var va=g(ma=>{"use strict";var kc=P(),pa=Ie(),Xt=Be(),ep=Le(),Sc=gr(),Ue=class t extends ep.YAMLSeq{constructor(){super(),this.add=Xt.YAMLMap.prototype.add.bind(this),this.delete=Xt.YAMLMap.prototype.delete.bind(this),this.get=Xt.YAMLMap.prototype.get.bind(this),this.has=Xt.YAMLMap.prototype.has.bind(this),this.set=Xt.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(kc.isPair(n)?(a=pa.toJS(n.key,"",i),o=pa.toJS(n.value,a,i)):a=pa.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(e,i,r){let n=Sc.createPairs(e,i,r),a=new this;return a.items=n.items,a}};Ue.tag="tag:yaml.org,2002:omap";var tp={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ue,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Sc.resolvePairs(t,e),r=[];for(let{key:n}of i.items)kc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ue,i)},createNode:(t,e,i)=>Ue.from(t,e,i)};ma.YAMLOMap=Ue;ma.omap=tp});var Cc=g(ga=>{"use strict";var Ec=I();function Pc({value:t,source:e},i){return e&&(t?xc:Rc).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var xc={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Ec.Scalar(!0),stringify:Pc},Rc={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Ec.Scalar(!1),stringify:Pc};ga.falseTag=Rc;ga.trueTag=xc});var Ac=g(wr=>{"use strict";var ip=I(),wa=ht(),rp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:wa.stringifyNumber},np={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():wa.stringifyNumber(t)}},ap={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new ip.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let r=t.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:wa.stringifyNumber};wr.float=ap;wr.floatExp=np;wr.floatNaN=rp});var Tc=g(Zt=>{"use strict";var _c=ht(),Qt=t=>typeof t=="bigint"||Number.isInteger(t);function yr(t,e,i,{intAsBigInt:r}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return n==="-"?-1*a:a}function ya(t,e,i){let{value:r}=t;if(Qt(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return _c.stringifyNumber(t)}var op={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>yr(t,2,2,i),stringify:t=>ya(t,2,"0b")},sp={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>yr(t,1,8,i),stringify:t=>ya(t,8,"0")},cp={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>yr(t,0,10,i),stringify:_c.stringifyNumber},lp={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>yr(t,2,16,i),stringify:t=>ya(t,16,"0x")};Zt.int=cp;Zt.intBin=op;Zt.intHex=lp;Zt.intOct=sp});var ba=g(Na=>{"use strict";var kr=P(),Nr=He(),br=Be(),Ke=class t extends br.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;kr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Nr.Pair(e.key,null):i=new Nr.Pair(e,null),br.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=br.findPair(this.items,e);return!i&&kr.isPair(r)?kr.isScalar(r.key)?r.key.value:r.key:r}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=br.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Nr.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(e,i,r){let{replacer:n}=r,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Nr.createPair(o,null,r));return a}};Ke.tag="tag:yaml.org,2002:set";var up={collection:"map",identify:t=>t instanceof Set,nodeClass:Ke,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ke.from(t,e,i),resolve(t,e){if(kr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ke,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Na.YAMLSet=Ke;Na.set=up});var Sa=g(Sr=>{"use strict";var dp=ht();function ka(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=o=>e?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Ic(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return dp.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var fp={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>ka(t,i),stringify:Ic},hp={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>ka(t,!1),stringify:Ic},jc={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(jc.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),f=e[8];if(f&&f!=="Z"){let d=ka(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Sr.floatTime=hp;Sr.intTime=fp;Sr.timestamp=jc});var Hc=g(Oc=>{"use strict";var pp=dt(),mp=ur(),vp=ft(),gp=Kt(),wp=fa(),$c=Cc(),Ea=Ac(),Er=Tc(),yp=ir(),Np=va(),bp=gr(),kp=ba(),Pa=Sa(),Sp=[pp.map,vp.seq,gp.string,mp.nullTag,$c.trueTag,$c.falseTag,Er.intBin,Er.intOct,Er.int,Er.intHex,Ea.floatNaN,Ea.floatExp,Ea.float,wp.binary,yp.merge,Np.omap,bp.pairs,kp.set,Pa.intTime,Pa.floatTime,Pa.timestamp];Oc.schema=Sp});var Jc=g(Ca=>{"use strict";var Mc=dt(),Ep=ur(),Fc=ft(),Pp=Kt(),xp=na(),xa=oa(),Ra=ca(),Rp=mc(),Cp=wc(),Vc=fa(),ei=ir(),qc=va(),Wc=gr(),Dc=Hc(),zc=ba(),Pr=Sa(),Bc=new Map([["core",Rp.schema],["failsafe",[Mc.map,Fc.seq,Pp.string]],["json",Cp.schema],["yaml11",Dc.schema],["yaml-1.1",Dc.schema]]),Lc={binary:Vc.binary,bool:xp.boolTag,float:xa.float,floatExp:xa.floatExp,floatNaN:xa.floatNaN,floatTime:Pr.floatTime,int:Ra.int,intHex:Ra.intHex,intOct:Ra.intOct,intTime:Pr.intTime,map:Mc.map,merge:ei.merge,null:Ep.nullTag,omap:qc.omap,pairs:Wc.pairs,seq:Fc.seq,set:zc.set,timestamp:Pr.timestamp},Ap={"tag:yaml.org,2002:binary":Vc.binary,"tag:yaml.org,2002:merge":ei.merge,"tag:yaml.org,2002:omap":qc.omap,"tag:yaml.org,2002:pairs":Wc.pairs,"tag:yaml.org,2002:set":zc.set,"tag:yaml.org,2002:timestamp":Pr.timestamp};function _p(t,e,i){let r=Bc.get(e);if(r&&!t)return i&&!r.includes(ei.merge)?r.concat(ei.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(Bc.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat(ei.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Lc[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Lc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Ca.coreKnownTags=Ap;Ca.getTags=_p});var Ta=g(Gc=>{"use strict";var Aa=P(),Tp=dt(),Ip=ft(),jp=Kt(),xr=Jc(),$p=(t,e)=>t.keye.key?1:0,_a=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?xr.getTags(e,"compat"):e?xr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?xr.coreKnownTags:{},this.tags=xr.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Aa.MAP,{value:Tp.map}),Object.defineProperty(this,Aa.SCALAR,{value:jp.string}),Object.defineProperty(this,Aa.SEQ,{value:Ip.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?$p:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Gc.Schema=_a});var Kc=g(Uc=>{"use strict";var Op=P(),Ia=Jt(),ti=Vt();function Hp(t,e){let i=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&i.push("---");let n=Ia.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(ti.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(Op.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let f=a(t.contents.commentBefore);i.push(ti.indentComment(f,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Ia.stringify(t.contents,n,()=>s=null,c);s&&(l+=ti.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ia.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(` `)?(i.push("..."),i.push(ti.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(ti.indentComment(a(c),"")))}return i.join(` `)+` -`}Uc.stringifyDocument=Op});var ii=g(Yc=>{"use strict";var Hp=Mt(),pt=Ji(),Q=P(),Dp=He(),Bp=Ie(),Lp=Ta(),Mp=Kc(),ja=Vi(),Fp=Dn(),Vp=Ft(),$a=Hn(),Oa=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Q.NODE_TYPE,{value:Q.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 $a.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,n,r)}clone(){let e=Object.create(t.prototype,{[Q.NODE_TYPE]:{value:Q.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Q.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){mt(this.contents)&&this.contents.add(e)}addIn(e,i){mt(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=ja.anchorNames(this);e.anchor=!i||r.has(i)?ja.findNewAnchor(i||"a",r):i}return new Hp.Alias(e.anchor)}createNode(e,i,r){let n;if(typeof i=="function")e=i.call({"":e},"",e),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=i.filter(m).map(String);w.length>0&&(i=i.concat(w)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=r??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=ja.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Vp.createNode(e,f,v);return s&&Q.isCollection(h)&&(h.flow=!0),u(),h}createPair(e,i,r={}){let n=this.createNode(e,null,r),a=this.createNode(i,null,r);return new Dp.Pair(n,a)}delete(e){return mt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return pt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):mt(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return Q.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return pt.isEmptyPath(e)?!i&&Q.isScalar(this.contents)?this.contents.value:this.contents:Q.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return Q.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return pt.isEmptyPath(e)?this.contents!==void 0:Q.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=pt.collectionFromPath(this.schema,[e],i):mt(this.contents)&&this.contents.set(e,i)}setIn(e,i){pt.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=pt.collectionFromPath(this.schema,Array.from(e),i):mt(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $a.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new $a.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Lp.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Bp.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Fp.applyReviver(o,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Mp.stringifyDocument(this,e)}};function mt(t){if(Q.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Yc.Document=Oa});var ai=g(ni=>{"use strict";var ri=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},Ha=class extends ri{constructor(e,i,r){super("YAMLParseError",e,i,r)}},Da=class extends ri{constructor(e,i,r){super("YAMLWarning",e,i,r)}},qp=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`… +`}Uc.stringifyDocument=Hp});var ii=g(Yc=>{"use strict";var Dp=Mt(),pt=Ji(),Q=P(),Bp=He(),Lp=Ie(),Mp=Ta(),Fp=Kc(),ja=Vi(),Vp=Dn(),qp=Ft(),$a=Hn(),Oa=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Q.NODE_TYPE,{value:Q.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 $a.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,n,r)}clone(){let e=Object.create(t.prototype,{[Q.NODE_TYPE]:{value:Q.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Q.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){mt(this.contents)&&this.contents.add(e)}addIn(e,i){mt(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=ja.anchorNames(this);e.anchor=!i||r.has(i)?ja.findNewAnchor(i||"a",r):i}return new Dp.Alias(e.anchor)}createNode(e,i,r){let n;if(typeof i=="function")e=i.call({"":e},"",e),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=i.filter(m).map(String);w.length>0&&(i=i.concat(w)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=r??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=ja.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=qp.createNode(e,f,v);return s&&Q.isCollection(h)&&(h.flow=!0),u(),h}createPair(e,i,r={}){let n=this.createNode(e,null,r),a=this.createNode(i,null,r);return new Bp.Pair(n,a)}delete(e){return mt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return pt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):mt(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return Q.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return pt.isEmptyPath(e)?!i&&Q.isScalar(this.contents)?this.contents.value:this.contents:Q.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return Q.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return pt.isEmptyPath(e)?this.contents!==void 0:Q.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=pt.collectionFromPath(this.schema,[e],i):mt(this.contents)&&this.contents.set(e,i)}setIn(e,i){pt.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=pt.collectionFromPath(this.schema,Array.from(e),i):mt(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $a.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new $a.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Mp.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Lp.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Vp.applyReviver(o,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Fp.stringifyDocument(this,e)}};function mt(t){if(Q.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Yc.Document=Oa});var ai=g(ni=>{"use strict";var ri=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},Ha=class extends ri{constructor(e,i,r){super("YAMLParseError",e,i,r)}},Da=class extends ri{constructor(e,i,r){super("YAMLWarning",e,i,r)}},Wp=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`… `),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+=`: ${o} ${l} -`}};ni.YAMLError=ri;ni.YAMLParseError=Ha;ni.YAMLWarning=Da;ni.prettifyError=qp});var oi=g(Xc=>{"use strict";function Wp(t,{flow:e,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,v=!1,h=null,m=null,w=null,y=null,b=null,k=null,S=null;for(let N of t)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),N.type){case"space":!e&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(h=N),f=!0;break;case"comment":{f||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let j=N.source.substring(1)||" ";d?d+=u+j:d=j,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,p=!0,(m||w)&&(y=N),f=!0;break;case"anchor":m&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),w=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case i:(m||w)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),k=N,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(e){b&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=t[t.length-1],R=E?E.offset+E.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:w,newlineAfterProp:y,end:R,start:S??R}}Xc.resolveProps=Wp});var Cr=g(Qc=>{"use strict";function Ba(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` -`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(Ba(e.key)||Ba(e.value))return!0}return!1;default:return!0}}Qc.containsNewline=Ba});var La=g(Zc=>{"use strict";var zp=Cr();function Jp(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&zp.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Zc.flowIndentCheck=Jp});var Ma=g(tl=>{"use strict";var el=P();function Gp(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||el.isScalar(a)&&el.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,i))}tl.mapIncludes=Gp});var sl=g(ol=>{"use strict";var il=He(),Up=Be(),rl=oi(),Kp=Cr(),nl=La(),Yp=Ma(),al="All mapping items must start at the same column";function Xp({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??Up.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:d,key:u,sep:p,value:v}=f,h=rl.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",al)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` -`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Kp.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",al);i.atKey=!0;let w=h.end,y=u?t(i,u,h,n):e(i,w,d,null,h,n);i.schema.compat&&nl.flowIndentCheck(r.indent,u,n),i.atKey=!1,Yp.mapIncludes(i,s.items,y)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let b=rl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=b.end,b.found){m&&(v?.type==="block-map"&&!b.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var Qp=Le(),Zp=oi(),em=La();function tm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??Qp.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:f,value:d}of r.items){let u=Zp.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?t(i,d,u,n):e(i,u.end,f,null,u,n);i.schema.compat&&em.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}cl.resolveBlockSeq=tm});var vt=g(ul=>{"use strict";function im(t,e,i,r){let n="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}ul.resolveEnd=im});var pl=g(hl=>{"use strict";var rm=P(),nm=He(),dl=Be(),am=Le(),om=vt(),fl=oi(),sm=Cr(),cm=Ma(),Fa="Block collections are not allowed within flow collections",Va=t=>t&&(t.type==="block-map"||t.type==="block-seq");function lm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?dl.YAMLMap:am.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m0){let m=om.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=` -`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}hl.resolveFlowCollection=lm});var vl=g(ml=>{"use strict";var um=P(),dm=I(),fm=Be(),hm=Le(),pm=sl(),mm=ll(),vm=pl();function qa(t,e,i,r,n,a){let o=i.type==="block-map"?pm.resolveBlockMap(t,e,i,r,a):i.type==="block-seq"?mm.resolveBlockSeq(t,e,i,r,a):vm.resolveFlowCollection(t,e,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function gm(t,e,i,r,n){let a=r.tag,o=a?e.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offsetu.tag===o&&u.collection===s);if(!c){let u=e.schema.knownTags[o];if(u?.collection===s)e.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qa(t,e,i,n,o)}let l=qa(t,e,i,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),e.options)??l,d=um.isNode(f)?f:new dm.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ml.composeCollection=gm});var za=g(gl=>{"use strict";var Wa=I();function wm(t,e,i){let r=e.offset,n=ym(e,t.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Wa.Scalar.BLOCK_FOLDED:Wa.Scalar.BLOCK_LITERAL,o=e.source?Nm(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` +`}};ni.YAMLError=ri;ni.YAMLParseError=Ha;ni.YAMLWarning=Da;ni.prettifyError=Wp});var oi=g(Xc=>{"use strict";function zp(t,{flow:e,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,v=!1,h=null,m=null,w=null,y=null,b=null,k=null,S=null;for(let N of t)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),N.type){case"space":!e&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(h=N),f=!0;break;case"comment":{f||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let j=N.source.substring(1)||" ";d?d+=u+j:d=j,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,p=!0,(m||w)&&(y=N),f=!0;break;case"anchor":m&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),w=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case i:(m||w)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),k=N,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(e){b&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=t[t.length-1],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:b,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:w,newlineAfterProp:y,end:C,start:S??C}}Xc.resolveProps=zp});var Rr=g(Qc=>{"use strict";function Ba(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(` +`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(Ba(e.key)||Ba(e.value))return!0}return!1;default:return!0}}Qc.containsNewline=Ba});var La=g(Zc=>{"use strict";var Jp=Rr();function Gp(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&Jp.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Zc.flowIndentCheck=Gp});var Ma=g(tl=>{"use strict";var el=P();function Up(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||el.isScalar(a)&&el.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,i))}tl.mapIncludes=Up});var sl=g(ol=>{"use strict";var il=He(),Kp=Be(),rl=oi(),Yp=Rr(),nl=La(),Xp=Ma(),al="All mapping items must start at the same column";function Qp({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??Kp.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:d,key:u,sep:p,value:v}=f,h=rl.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",al)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=` +`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Yp.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",al);i.atKey=!0;let w=h.end,y=u?t(i,u,h,n):e(i,w,d,null,h,n);i.schema.compat&&nl.flowIndentCheck(r.indent,u,n),i.atKey=!1,Xp.mapIncludes(i,s.items,y)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let b=rl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=b.end,b.found){m&&(v?.type==="block-map"&&!b.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start{"use strict";var Zp=Le(),em=oi(),tm=La();function im({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??Zp.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:f,value:d}of r.items){let u=em.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?t(i,d,u,n):e(i,u.end,f,null,u,n);i.schema.compat&&tm.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}cl.resolveBlockSeq=im});var vt=g(ul=>{"use strict";function rm(t,e,i,r){let n="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}ul.resolveEnd=rm});var pl=g(hl=>{"use strict";var nm=P(),am=He(),dl=Be(),om=Le(),sm=vt(),fl=oi(),cm=Rr(),lm=Ma(),Fa="Block collections are not allowed within flow collections",Va=t=>t&&(t.type==="block-map"||t.type==="block-seq");function um({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?dl.YAMLMap:om.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m0){let m=sm.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=` +`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}hl.resolveFlowCollection=um});var vl=g(ml=>{"use strict";var dm=P(),fm=I(),hm=Be(),pm=Le(),mm=sl(),vm=ll(),gm=pl();function qa(t,e,i,r,n,a){let o=i.type==="block-map"?mm.resolveBlockMap(t,e,i,r,a):i.type==="block-seq"?vm.resolveBlockSeq(t,e,i,r,a):gm.resolveFlowCollection(t,e,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function wm(t,e,i,r,n){let a=r.tag,o=a?e.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offsetu.tag===o&&u.collection===s);if(!c){let u=e.schema.knownTags[o];if(u?.collection===s)e.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qa(t,e,i,n,o)}let l=qa(t,e,i,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),e.options)??l,d=dm.isNode(f)?f:new fm.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ml.composeCollection=wm});var za=g(gl=>{"use strict";var Wa=I();function ym(t,e,i){let r=e.offset,n=Nm(e,t.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Wa.Scalar.BLOCK_FOLDED:Wa.Scalar.BLOCK_LITERAL,o=e.source?bm(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?` `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return e.source&&(m+=e.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=e.indent+n.indent,l=e.offset+n.length,f=0;for(let h=0;hc&&(c=m.length);else{m.length=s;--h)o[h][0].length>c&&(s=h+1);let d="",u="",p=!1;for(let h=0;hc||w[0]===" "?(u===" "?u=` @@ -84,41 +84,41 @@ ${l} `+o[h][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let v=r+n.length+e.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function ym({offset:t,props:e},i,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],a=n[0],o=0,s="",c=-1;for(let u=1;u{"use strict";var Ja=I(),bm=vt();function km(t,e,i){let{offset:r,type:n,source:a,end:o}=t,s,c,l=(u,p,v)=>i(r+u,p,v);switch(n){case"scalar":s=Ja.Scalar.PLAIN,c=Sm(a,l);break;case"single-quoted-scalar":s=Ja.Scalar.QUOTE_SINGLE,c=Em(a,l);break;case"double-quoted-scalar":s=Ja.Scalar.QUOTE_DOUBLE,c=Pm(a,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let f=r+a.length,d=bm.resolveEnd(o,f,e,i);return{value:c,type:s,comment:d.comment,range:[r,f,d.offset]}}function Sm(t,e){let i="";switch(t[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),wl(t)}function Em(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),wl(t.slice(1,-1)).replace(/''/g,"'")}function wl(t){let e,i;try{e=new RegExp(`(.*?)(?{"use strict";var Ja=I(),km=vt();function Sm(t,e,i){let{offset:r,type:n,source:a,end:o}=t,s,c,l=(u,p,v)=>i(r+u,p,v);switch(n){case"scalar":s=Ja.Scalar.PLAIN,c=Em(a,l);break;case"single-quoted-scalar":s=Ja.Scalar.QUOTE_SINGLE,c=Pm(a,l);break;case"double-quoted-scalar":s=Ja.Scalar.QUOTE_DOUBLE,c=xm(a,l);break;default:return i(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let f=r+a.length,d=km.resolveEnd(o,f,e,i);return{value:c,type:s,comment:d.comment,range:[r,f,d.offset]}}function Em(t,e){let i="";switch(t[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),wl(t)}function Pm(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),wl(t.slice(1,-1)).replace(/''/g,"'")}function wl(t){let e,i;try{e=new RegExp(`(.*?)(?a?t.slice(a,r+1):n)}else i+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function xm(t,e){let i="",r=t[e+1];for(;(r===" "||r===" "||r===` +`)&&(i+=r>a?t.slice(a,r+1):n)}else i+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function Rm(t,e){let i="",r=t[e+1];for(;(r===" "||r===" "||r===` `||r==="\r")&&!(r==="\r"&&t[e+2]!==` `);)r===` `&&(i+=` `),e+=1,r=t[e+1];return i||(i=" "),{fold:i,offset:e}}var Cm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Rm(t,e,i,r){let n=t.substr(e,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,i+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}yl.resolveFlowScalar=km});var kl=g(bl=>{"use strict";var Ye=P(),Nl=I(),Am=za(),_m=Ga();function Tm(t,e,i,r){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Am.resolveBlockScalar(t,e,r):_m.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Ye.SCALAR]:c?l=Im(t.schema,n,c,i,r):e.type==="scalar"?l=jm(t,n,e,r):l=t.schema[Ye.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??e,"TAG_RESOLVE_FAILED",u),t.options);f=Ye.isScalar(d)?d:new Nl.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??e,"TAG_RESOLVE_FAILED",u),f=new Nl.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Im(t,e,i,r,n){if(i==="!")return t[Ye.SCALAR];let a=[];for(let s of t.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(e))return s;let o=t.knownTags[i];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[Ye.SCALAR])}function jm({atKey:t,directives:e,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[Ye.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Ye.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}bl.composeScalar=Tm});var El=g(Sl=>{"use strict";function $m(t,e,i){if(e){i??(i=e.length);for(let r=i-1;r>=0;--r){let n=e[r];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++r];n?.type==="space";)t+=n.source.length,n=e[++r];break}}return t}Sl.emptyScalarPosition=$m});var Cl=g(Ka=>{"use strict";var Om=Mt(),Hm=P(),Dm=vl(),Pl=kl(),Bm=vt(),Lm=El(),Mm={composeNode:xl,composeEmptyNode:Ua};function xl(t,e,i,r){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(e.type){case"alias":l=Fm(t,e,r),(s||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Pl.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Dm.composeCollection(Mm,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",u)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=Ua(t,e.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!Hm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Ua(t,e,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Lm.emptyScalarPosition(e,i,r),indent:-1,source:""},d=Pl.composeScalar(t,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Fm({options:t},{offset:e,source:i,end:r},n){let a=new Om.Alias(i.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=Bm.resolveEnd(r,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Ka.composeEmptyNode=Ua;Ka.composeNode=xl});var _l=g(Al=>{"use strict";var Vm=ii(),Rl=Cl(),qm=vt(),Wm=oi();function zm(t,e,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new Vm.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Wm.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Rl.composeNode(l,n,f,o):Rl.composeEmptyNode(l,f.end,r,null,f,o);let d=c.contents.range[2],u=qm.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,d,u.offset],c}Al.composeDoc=zm});var Xa=g(jl=>{"use strict";var Jm=$i("process"),Gm=Hn(),Um=ii(),si=ai(),Tl=P(),Km=_l(),Ym=vt();function ci(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function Il(t){let e="",i=!1,r=!1;for(let n=0;n{"use strict";var Ye=P(),Nl=I(),_m=za(),Tm=Ga();function Im(t,e,i,r){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?_m.resolveBlockScalar(t,e,r):Tm.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Ye.SCALAR]:c?l=jm(t.schema,n,c,i,r):e.type==="scalar"?l=$m(t,n,e,r):l=t.schema[Ye.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??e,"TAG_RESOLVE_FAILED",u),t.options);f=Ye.isScalar(d)?d:new Nl.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??e,"TAG_RESOLVE_FAILED",u),f=new Nl.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function jm(t,e,i,r,n){if(i==="!")return t[Ye.SCALAR];let a=[];for(let s of t.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(e))return s;let o=t.knownTags[i];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),t[Ye.SCALAR])}function $m({atKey:t,directives:e,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[Ye.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Ye.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}bl.composeScalar=Im});var El=g(Sl=>{"use strict";function Om(t,e,i){if(e){i??(i=e.length);for(let r=i-1;r>=0;--r){let n=e[r];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++r];n?.type==="space";)t+=n.source.length,n=e[++r];break}}return t}Sl.emptyScalarPosition=Om});var Rl=g(Ka=>{"use strict";var Hm=Mt(),Dm=P(),Bm=vl(),Pl=kl(),Lm=vt(),Mm=El(),Fm={composeNode:xl,composeEmptyNode:Ua};function xl(t,e,i,r){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(e.type){case"alias":l=Vm(t,e,r),(s||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Pl.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Bm.composeCollection(Fm,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",u)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=Ua(t,e.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!Dm.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&f&&(l.srcToken=e),l}function Ua(t,e,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Mm.emptyScalarPosition(e,i,r),indent:-1,source:""},d=Pl.composeScalar(t,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Vm({options:t},{offset:e,source:i,end:r},n){let a=new Hm.Alias(i.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=Lm.resolveEnd(r,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Ka.composeEmptyNode=Ua;Ka.composeNode=xl});var _l=g(Al=>{"use strict";var qm=ii(),Cl=Rl(),Wm=vt(),zm=oi();function Jm(t,e,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new qm.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=zm.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Cl.composeNode(l,n,f,o):Cl.composeEmptyNode(l,f.end,r,null,f,o);let d=c.contents.range[2],u=Wm.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,d,u.offset],c}Al.composeDoc=Jm});var Xa=g(jl=>{"use strict";var Gm=$i("process"),Um=Hn(),Km=ii(),si=ai(),Tl=P(),Ym=_l(),Xm=vt();function ci(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function Il(t){let e="",i=!1,r=!1;for(let n=0;n{let o=ci(i);a?this.warnings.push(new si.YAMLWarning(o,r,n)):this.errors.push(new si.YAMLParseError(o,r,n))},this.directives=new Gm.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=Il(this.prelude);if(r){let a=e.contents;if(i)e.comment=e.comment?`${e.comment} +`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":t[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:e,afterEmptyLine:r}}var Ya=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ci(i);a?this.warnings.push(new si.YAMLWarning(o,r,n)):this.errors.push(new si.YAMLParseError(o,r,n))},this.directives=new Um.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=Il(this.prelude);if(r){let a=e.contents;if(i)e.comment=e.comment?`${e.comment} ${r}`:r;else if(n||e.directives.docStart||!a)e.commentBefore=r;else if(Tl.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Tl.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r} ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r} -${o}`:r}}if(i){for(let a=0;a{let a=ci(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=Km.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new si.YAMLParseError(ci(e),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new si.YAMLParseError(ci(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Ym.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r} -${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new si.YAMLParseError(ci(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),n=new Um.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}}};jl.Composer=Ya});var Hl=g(Rr=>{"use strict";var Xm=za(),Qm=Ga(),Zm=ai(),$l=zt();function ev(t,e=!0,i){if(t){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new Zm.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Qm.resolveFlowScalar(t,e,r);case"block-scalar":return Xm.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function tv(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=$l.stringifyString({type:o,value:t},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:r,source:` +${o}`:r}}if(i){for(let a=0;a{let a=ci(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=Ym.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new si.YAMLParseError(ci(e),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new si.YAMLParseError(ci(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Xm.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r} +${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new si.YAMLParseError(ci(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),n=new Km.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}}};jl.Composer=Ya});var Hl=g(Cr=>{"use strict";var Qm=za(),Zm=Ga(),ev=ai(),$l=zt();function tv(t,e=!0,i){if(t){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new ev.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Zm.resolveFlowScalar(t,e,r);case"block-scalar":return Qm.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function iv(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=$l.stringifyString({type:o,value:t},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:r,source:` `}];switch(s[0]){case"|":case">":{let l=s.indexOf(` `),f=s.substring(0,l),d=s.substring(l+1)+` `,u=[{type:"block-scalar-header",offset:a,indent:r,source:f}];return Ol(u,c)||u.push({type:"newline",offset:-1,indent:r,source:` -`}),{type:"block-scalar",offset:a,indent:r,props:u,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function iv(t,e,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in t?t.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=$l.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":rv(t,c);break;case'"':Qa(t,c,"double-quoted-scalar");break;case"'":Qa(t,c,"single-quoted-scalar");break;default:Qa(t,c,"scalar")}}function rv(t,e){let i=e.indexOf(` +`}),{type:"block-scalar",offset:a,indent:r,props:u,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function rv(t,e,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in t?t.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=$l.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":nv(t,c);break;case'"':Qa(t,c,"double-quoted-scalar");break;case"'":Qa(t,c,"single-quoted-scalar");break;default:Qa(t,c,"scalar")}}function nv(t,e){let i=e.indexOf(` `),r=e.substring(0,i),n=e.substring(i+1)+` `;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,t.source=n}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Ol(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:` `});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function Ol(t,e){if(e)for(let i of e)switch(i.type){case"space":case"comment":t.push(i);break;case"newline":return t.push(i),!0}return!1}function Qa(t,e,i){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=i,t.source=e;break;case"block-scalar":{let r=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let a of r)a.offset+=n;delete t.props,Object.assign(t,{type:i,source:e,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:` -`};delete t.items,Object.assign(t,{type:i,source:e,end:[n]});break}default:{let r="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:r,source:e,end:n})}}}Rr.createScalarToken=tv;Rr.resolveAsScalar=ev;Rr.setScalarValue=iv});var Bl=g(Dl=>{"use strict";var nv=t=>"type"in t?_r(t):Ar(t);function _r(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=_r(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Ar(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Ar(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Ar(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Ar({start:t,key:e,sep:i,value:r}){let n="";for(let a of t)n+=a.source;if(e&&(n+=_r(e)),i)for(let a of i)n+=a.source;return r&&(n+=_r(r)),n}Dl.stringify=nv});var Vl=g(Fl=>{"use strict";var Za=Symbol("break visit"),av=Symbol("skip children"),Ll=Symbol("remove item");function Xe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ml(Object.freeze([]),t,e)}Xe.BREAK=Za;Xe.SKIP=av;Xe.REMOVE=Ll;Xe.itemAtPath=(t,e)=>{let i=t;for(let[r,n]of e){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Xe.parentCollection=(t,e)=>{let i=Xe.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Ml(t,e,i){let r=i(e,t);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o{"use strict";var eo=Hl(),ov=Bl(),sv=Vl(),to="\uFEFF",io="",ro="",no="",cv=t=>!!t&&"items"in t,lv=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function uv(t){switch(t){case to:return"";case io:return"";case ro:return"";case no:return"";default:return JSON.stringify(t)}}function dv(t){switch(t){case to:return"byte-order-mark";case io:return"doc-mode";case ro:return"flow-error-end";case no:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`};delete t.items,Object.assign(t,{type:i,source:e,end:[n]});break}default:{let r="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:r,source:e,end:n})}}}Cr.createScalarToken=iv;Cr.resolveAsScalar=tv;Cr.setScalarValue=rv});var Bl=g(Dl=>{"use strict";var av=t=>"type"in t?_r(t):Ar(t);function _r(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=_r(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Ar(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Ar(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Ar(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Ar({start:t,key:e,sep:i,value:r}){let n="";for(let a of t)n+=a.source;if(e&&(n+=_r(e)),i)for(let a of i)n+=a.source;return r&&(n+=_r(r)),n}Dl.stringify=av});var Vl=g(Fl=>{"use strict";var Za=Symbol("break visit"),ov=Symbol("skip children"),Ll=Symbol("remove item");function Xe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ml(Object.freeze([]),t,e)}Xe.BREAK=Za;Xe.SKIP=ov;Xe.REMOVE=Ll;Xe.itemAtPath=(t,e)=>{let i=t;for(let[r,n]of e){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Xe.parentCollection=(t,e)=>{let i=Xe.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Ml(t,e,i){let r=i(e,t);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o{"use strict";var eo=Hl(),sv=Bl(),cv=Vl(),to="\uFEFF",io="",ro="",no="",lv=t=>!!t&&"items"in t,uv=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function dv(t){switch(t){case to:return"";case io:return"";case ro:return"";case no:return"";default:return JSON.stringify(t)}}function fv(t){switch(t){case to:return"byte-order-mark";case io:return"doc-mode";case ro:return"flow-error-end";case no:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` `:case`\r -`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}W.createScalarToken=eo.createScalarToken;W.resolveAsScalar=eo.resolveAsScalar;W.setScalarValue=eo.setScalarValue;W.stringify=ov.stringify;W.visit=sv.visit;W.BOM=to;W.DOCUMENT=io;W.FLOW_END=ro;W.SCALAR=no;W.isCollection=cv;W.isScalar=lv;W.prettyToken=uv;W.tokenType=dv});var so=g(Wl=>{"use strict";var li=Tr();function ae(t){switch(t){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var ql=new Set("0123456789ABCDEFabcdef"),fv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ir=new Set(",[]{}"),hv=new Set(` ,[]{} -\r `),ao=t=>!t||hv.has(t),oo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}W.createScalarToken=eo.createScalarToken;W.resolveAsScalar=eo.resolveAsScalar;W.setScalarValue=eo.setScalarValue;W.stringify=sv.stringify;W.visit=cv.visit;W.BOM=to;W.DOCUMENT=io;W.FLOW_END=ro;W.SCALAR=no;W.isCollection=lv;W.isScalar=uv;W.prettyToken=dv;W.tokenType=fv});var so=g(Wl=>{"use strict";var li=Tr();function ae(t){switch(t){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var ql=new Set("0123456789ABCDEFabcdef"),hv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ir=new Set(",[]{}"),pv=new Set(` ,[]{} +\r `),ao=t=>!t||pv.has(t),oo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===` `?!0:i==="\r"?this.buffer[e+1]===` `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let i=this.buffer[e];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+e];if(i==="\r"){let n=this.buffer[r+e+1];if(n===` `||!n&&!this.atEnd)return e+r+1}return i===` @@ -133,31 +133,31 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus `&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield li.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(ae(a)||e&&Ir.has(a))break;i=r}else if(ae(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===` `?(r+=1,n=` `,a=this.buffer[r+1]):i=r),a==="#"||e&&Ir.has(a))break;if(n===` -`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&Ir.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield li.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(ao),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ae(r)||i&&Ir.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!ae(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(fv.has(i))i=this.buffer[++e];else if(i==="%"&&ql.has(this.buffer[e+1])&&ql.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&Ir.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield li.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(ao),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ae(r)||i&&Ir.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!ae(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(hv.has(i))i=this.buffer[++e];else if(i==="%"&&ql.has(this.buffer[e+1])&&ql.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||e&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(e){let i=this.pos,r=this.buffer[i];for(;!e(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Wl.Lexer=oo});var lo=g(zl=>{"use strict";var co=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var pv=$i("process"),Jl=Tr(),mv=so();function Me(t,e){for(let i=0;i=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function $r(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Ul(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&&Gl(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(e){let i=this.pos,r=this.buffer[i];for(;!e(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Wl.Lexer=oo});var lo=g(zl=>{"use strict";var co=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i>1;this.lineStarts[a]{"use strict";var mv=$i("process"),Jl=Tr(),vv=so();function Me(t,e){for(let i=0;i=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function $r(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Ul(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&&Gl(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;se.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Me(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Kl(i.key)&&!Me(i.sep,"newline")){let o=gt(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Me(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=gt(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?e.items.push({start:a,key:null,sep:[this.sourceToken]}):Me(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(e.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Me(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){$r(n,i.start),n.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||Me(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?e.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?e.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=jr(r),a=gt(n);Ul(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let i=this.source.indexOf(` `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(` -`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=jr(e),r=gt(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=jr(e),r=gt(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Yl.Parser=uo});var tu=g(di=>{"use strict";var Xl=Xa(),vv=ii(),ui=ai(),gv=Kn(),wv=P(),yv=lo(),Ql=fo();function Zl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new yv.LineCounter||null,prettyErrors:e}}function Nv(t,e={}){let{lineCounter:i,prettyErrors:r}=Zl(e),n=new Ql.Parser(i?.addNewLine),a=new Xl.Composer(e),o=Array.from(a.compose(n.parse(t)));if(r&&i)for(let s of o)s.errors.forEach(ui.prettifyError(t,i)),s.warnings.forEach(ui.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function eu(t,e={}){let{lineCounter:i,prettyErrors:r}=Zl(e),n=new Ql.Parser(i?.addNewLine),a=new Xl.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new ui.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(ui.prettifyError(t,i)),o.warnings.forEach(ui.prettifyError(t,i))),o}function bv(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=eu(t,i);if(!n)return null;if(n.warnings.forEach(a=>gv.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 kv(t,e,i){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(t===void 0){let{keepUndefined:n}=i??e??{};if(!n)return}return wv.isDocument(t)&&!r?t.toString(i):new vv.Document(t,r,i).toString(i)}di.parse=bv;di.parseAllDocuments=Nv;di.parseDocument=eu;di.stringify=kv});var wt=g(x=>{"use strict";var Sv=Xa(),Ev=ii(),Pv=Ta(),ho=ai(),xv=Mt(),Fe=P(),Cv=He(),Rv=I(),Av=Be(),_v=Le(),Tv=Tr(),Iv=so(),jv=lo(),$v=fo(),Or=tu(),iu=Ht();x.Composer=Sv.Composer;x.Document=Ev.Document;x.Schema=Pv.Schema;x.YAMLError=ho.YAMLError;x.YAMLParseError=ho.YAMLParseError;x.YAMLWarning=ho.YAMLWarning;x.Alias=xv.Alias;x.isAlias=Fe.isAlias;x.isCollection=Fe.isCollection;x.isDocument=Fe.isDocument;x.isMap=Fe.isMap;x.isNode=Fe.isNode;x.isPair=Fe.isPair;x.isScalar=Fe.isScalar;x.isSeq=Fe.isSeq;x.Pair=Cv.Pair;x.Scalar=Rv.Scalar;x.YAMLMap=Av.YAMLMap;x.YAMLSeq=_v.YAMLSeq;x.CST=Tv;x.Lexer=Iv.Lexer;x.LineCounter=jv.LineCounter;x.Parser=$v.Parser;x.parse=Or.parse;x.parseAllDocuments=Or.parseAllDocuments;x.parseDocument=Or.parseDocument;x.stringify=Or.stringify;x.visit=iu.visit;x.visitAsync=iu.visitAsync});function ds(t,e){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",t.name,"--summary","","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",t.name,"--summary","","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",t.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",t.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(t.status==="blocked"){let n=t.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?["comet","native","next",t.name,"--retry-verifier","--summary",""]:null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(t.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",t.name,"--summary","","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary",""],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(e.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary",""],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=e.children.some(({status:o})=>o==="blocked"),a=e.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{name:"",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(t.phase==="verify"){let n=t.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input",""],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[{id:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:""}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as Ly}from"node:crypto";import{promises as Ii}from"node:fs";import My from"node:path";import{execFileSync as zd}from"child_process";import Oi from"path";function An(t,e){return zd("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Jd(t,e){let i=Oi.normalize(t),r=Oi.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ke(t){try{let e=Oi.resolve(An(t,["rev-parse","--show-toplevel"])),r=An(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Oi.resolve(r.slice(9)):e,a=null;try{a=An(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Jd(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}import{randomUUID as Gd}from"crypto";import{promises as L}from"fs";import ie from"path";function Te(t){return t!==0&&t!==0n&&t!=="0"}function G(t,e){return Te(t.dev)&&Te(e.dev)&&Te(t.ino)&&Te(e.ino)}function A(t,e){let i=Te(t.dev)&&Te(e.dev);if(i&&t.dev!==e.dev)return!1;let r=Te(t.ino)&&Te(e.ino);return r&&t.ino!==e.ino?!1:i&&r?!0:t.birthtime===e.birthtime}function Tn(t,e){let i=ie.relative(t,e);return i===""||!ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ie.sep}`)}function Ud(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function _n(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return G(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function fs(t){let e=await L.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await L.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function $t(t){for(let e of t){let i=await L.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ud(e,i)||await L.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function Kd(t,e){let i=ie.resolve(t),r=ie.resolve(e);if(!Tn(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await fs(i)],a=ie.relative(i,r).split(ie.sep).filter(Boolean),o=i;for(let s of a){await $t(n),o=ie.join(o,s);try{await L.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await fs(o);if(!Tn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await $t(n),n}async function Yd(t){let e;try{e=await L.open(t,"r"),await e.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await e?.close()}}async function Xd(t,e,i={}){let r=ie.dirname(t),n=i.containedRoot?await Kd(i.containedRoot,r):null;n||await L.mkdir(r,{recursive:!0});let a=ie.join(r,`.${ie.basename(t)}.${Gd()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await L.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([L.lstat(a),L.realpath(a)]);if(await $t(n),!c.isFile()||c.isSymbolicLink()||!_n(s,c)||!Tn(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!_n(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await $t(n);let c=await L.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!_n(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await L.link(a,t),await L.unlink(a)):await L.rename(a,t),await Yd(r)}catch(c){if(await o?.close(),!n)await L.rm(a,{force:!0});else try{await $t(n),await L.rm(a,{force:!0})}catch{}throw c}}async function de(t,e,i={}){await Xd(t,e,i)}async function Y(t,e,i={}){await de(t,JSON.stringify(e,null,2)+` -`,i)}import{createHash as tf}from"node:crypto";import{promises as re}from"node:fs";import X from"node:path";import{TextDecoder as rf}from"node:util";var Qd=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Zd=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function ef(t){return t.toLowerCase().startsWith(".env")}function Ot(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>ef(r))?"environment-file":i.some(r=>Zd.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Qd.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var Di=1024*1024;function In(t,e){let i=X.relative(t,e);return i===""||!X.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${X.sep}`)}function nf(t){let e=X.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||X.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),r=Ot(t);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${t}`);return t}function af(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function of(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hi(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return G(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function hs(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function sf(t,e){let i=X.resolve(t),r=X.resolve(e);if(!In(i,r))throw new Error("Native artifact path is outside its root");let n=[await hs(i)],a=i;for(let o of X.relative(i,r).split(X.sep).filter(Boolean)){a=X.join(a,o);let s=await hs(a);if(!In(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ps(t){for(let e of t){let i=await re.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!of(e,i)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=nf(t.ref),i=t.maxBytes===null?null:af(t.maxBytes??Di),r=X.resolve(t.root,...e.split("/")),n=await sf(t.root,X.dirname(r));await t.hooks?.afterParentChainCaptured?.();let a=await re.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await re.realpath(r);if(!In(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await re.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),re.lstat(r),re.realpath(r)]);if(await ps(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Hi(a,c)||!Hi(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let b=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),re.lstat(r),re.realpath(r)]);if(await ps(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Hi(c,v)||!Hi(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,u),y;try{y=new rf("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:b})}return{ref:e,size:u,hash:t.includeHash===!1?null:tf("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var es=jt(wt(),1);import _t from"path";var mo=jt(wt(),1);import Hr from"path";var fi=64*1024,Dr=1024,Br=64,vo=5,Ov=[".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/**",".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/**"],Hv=["**/.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"],Dv=[...Ov,...Hv].sort((t,e)=>t.localeCompare(e,"en"));var U={include:["**/*"],exclude:[...Dv],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Bv(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Hr.posix.isAbsolute(i)||Hr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function Qe(t){let e=Bv(t,"native.artifact_root");return e.length===0?".":e.join("/")}function nu(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Lr(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Hr.posix.isAbsolute(r)||Hr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function yt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function au(t,e,i){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function go(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Dr)throw new Error(`${e} exceeds ${Dr} characters`);let i=0;for(let r=0;rBr)throw new Error(`${e} contains more than ${Br} wildcard tokens`);return t}function ru(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>go(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function po(t,e,i){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Lv(t){if(t===void 0)return{...U,include:[...U.include],exclude:[...U.exclude]};let e=yt(t,"native.snapshot");return{include:ru(e.include,"native.snapshot.include",U.include),exclude:ru(e.exclude,"native.snapshot.exclude",U.exclude),max_files:po(e.max_files,U.max_files,"native.snapshot.max_files"),max_total_bytes:po(e.max_total_bytes,U.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:po(e.max_duration_ms,U.max_duration_ms,"native.snapshot.max_duration_ms")}}function Mv(t){if(t===void 0)return;let e=yt(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=yt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:Qe(r),toArtifactRoot:Qe(n),stage:a,...o?{cleanup:o}:{}}}function Fv(t,e={}){let i=yt(t,"native"),r=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??vo;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Mv(i.pending_root_move);return{artifact_root:Qe(r),language:au(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Lv(i.snapshot),...s?{pending_root_move:s}:{}}}function Vv(t){let e=yt(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:nu(e.artifact_layout),language:au(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function qv(t){let i=yt(t,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Lr(r,`hook.allow_paths[${n}]`)))]}}function Wv(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function zv(t,e,i,r,n,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!o)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:n,...e?{hook:e}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function hi(t,e={}){let i=(0,mo.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=Wv(n.ambient_resume),o=n.hook===void 0?void 0:qv(n.hook),s=n.native===void 0?void 0:Fv(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=n.classic===void 0?void 0:Vv(n.classic),l=zv(n,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function Mr(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Qe(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:vo,snapshot:{...U,include:[...U.include],exclude:[...U.exclude]}}}}import{createHash as Gv}from"crypto";import{promises as qr}from"fs";import Ve from"path";import{constants as Fr,promises as Ze}from"fs";var oe=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}};function wo(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function ou(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function pi(t){return{dev:t.dev,ino:t.ino,birthtime:wo(t)}}function Vr(t,e){let i=pi(t),r=pi(e);return G(i,r)?A(i,r):A(i,r)&&wo(t)===wo(e)&&ou(t)===ou(e)&&t.size===e.size}async function Nt(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Ze.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new oe("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new oe("too-large",`${r} exceeds ${e} bytes`);let o=await Ze.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:pi(a)});let s=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,c;try{c=await Ze.open(t,s)}catch(l){throw l.code==="ELOOP"?new oe("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Ze.lstat(t,{bigint:n}),Ze.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!Vr(a,l)||!Vr(a,f))throw new oe("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:pi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-p,{bytesRead:b}=await c.read(v,0,Math.min(v.length,y),null);if(b===0)break;if(p+=b,p>e)throw new oe("too-large",`${r} exceeds ${e} bytes`);u.push(Buffer.from(v.subarray(0,b)))}await i.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([c.stat({bigint:n}),Ze.lstat(t,{bigint:n}),Ze.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Vr(a,h)||!Vr(a,m))throw new oe("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:pi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:w}}finally{await c.close()}}function Jv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function yo(t,e){let i=Ve.relative(t,e);return i===""||!Ve.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ve.sep}`)}async function su(t,e){let i=Ve.resolve(t),r=await qr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return qr.realpath(i)}async function cu(t,e,i,r){let n=t;for(let a=0;a{if(!yo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await cu(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var mi=".comet/config.yaml";function Uv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Wr(t,e={}){return(await zr(t,e)).document}async function Kv(t){try{return(await qe(t,mi,fi,{label:mi})).bytes}catch(e){if(Uv(e))return null;throw e}}function Yv(t){return t?{exists:!0,sha256:Gv("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function zr(t,e={}){let i=await Kv(t);return{document:i?hi(i.toString("utf8"),e):null,identity:Yv(i)}}async function No(t){return(await Wr(t))?.config??null}var $k=16*1024;import{existsSync as uu,promises as et}from"fs";import C from"path";import tg from"os";var Jr=".comet/config.yaml",ig=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function So(t){try{return await et.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function rg(t){try{let e=await et.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function St(t,e){let i=C.relative(t,e);return i===""||!C.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${C.sep}`)}async function kt(t){let e=[],i=t;for(;!await So(i);){let n=C.dirname(i);if(n===i)break;e.push(C.basename(i)),i=n}let r=await et.realpath(i);return C.resolve(r,...e.reverse())}async function Eo(t){try{return(await et.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Gr(t){let e=C.resolve(t);try{(await et.stat(e)).isDirectory()||(e=C.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=C.resolve(tg.homedir());for(;;){if(!(e===r&&i!==r)){let o=C.join(e,...Jr.split("/")),s=e===i||await rg(o);if(await So(o)&&s)return e}if(await So(C.join(e,".git")))return e;let a=C.dirname(e);if(a===e)return i;e=a}}function Ur(t){return Qe(t)}async function ng(t,e){let i=Ur(e),r=C.resolve(t,...i.split("/")),n=await et.realpath(t),a=await kt(r);if(!St(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Et(t,e){let i=Ur(e),r=await ng(t,i),n=C.join(r,"comet");if(await Eo(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([kt(r),kt(n)]);if(!St(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=C.resolve(t),c=C.join(s,".comet","runtime","native");if(await Eo(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([et.realpath(s),kt(c)]);if(!St(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:C.join(t,...Jr.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:C.join(n,"specs"),changesDir:C.join(n,"changes"),archiveDir:C.join(n,"archive"),runtimeDir:c,changesRuntimeDir:C.join(c,"changes"),locksDir:C.join(c,"locks"),transactionsDir:C.join(c,"transactions")}}function du(t){if(!ig.test(t))throw new Error(`Invalid Native change name: ${t}`)}function tt(t,e){du(e);let i=C.join(t.changesRuntimeDir,e);if(!F(t.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Po(t,e){du(e);let i=C.join(t.changesDir,e,"runtime");if(!F(t.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function pe(t,e){let i=tt(t,e);if(uu(i))return i;let r=Po(t,e);return uu(r)?r:i}function me(t,e){let i=C.resolve(e);if(F(t.runtimeDir,i))return t.runtimeDir;if(F(t.nativeRoot,i))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function F(t,e){return St(C.resolve(t),C.resolve(e))}async function T(t,e){let i=C.resolve(t),r=C.resolve(e);if(!St(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await Eo(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([kt(i),kt(r)]);if(!St(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return r}function og(t="docs",e="en"){return Mr(t,e)}async function Pe(t){let e=(await Wr(t))?.config??null;return e?.native?e:null}async function Kr(t){let e=await Pe(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function fu(t){let e=await Gr(t.startPath),i=await Pe(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Jr} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=t.explicitArtifactRoot?Ur(t.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??og(r??"docs"),a=await Et(e,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Dw}from"fs";import Bw from"path";import{AsyncLocalStorage as sg}from"async_hooks";import{randomUUID as mu}from"crypto";import{promises as Z}from"fs";import vu from"os";import V from"path";var hu=16*1024,gu=".coordinator",cg=5e3,pu=new sg,Yr=new Map;function lg(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function ug(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${e}`);return i}function wu(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function xo(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return G(i,r)?A(i,r):A(i,r)&&t.size===e.size}function Co(t,e){return xo(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function xe(t){let e,i;try{let r=await Nt(t,hu,{bigint:!0,label:"Native lock"});e=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof oe?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${hu} bytes: ${t}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:r}):new Error(`Native lock changed while reading: ${t}`,{cause:r}):r}return{file:t,owner:ug(JSON.parse(e.toString("utf8")),t),identity:wu(i)}}async function dg(t){return(await xe(t))?.owner??null}function yu(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==vu.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=gg(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function fg(t,e){try{await Z.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Z.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function Ro(t,e){let i=await xe(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Co(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Z.mkdir(e,{recursive:!0});let r=V.join(e,`${V.basename(t.file)}.${t.owner.id}.${mu()}.removed`);try{await Z.rename(t.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await xe(r);if(!n||n.owner.id!==t.owner.id||!xo(n.identity,t.identity))throw await fg(r,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Z.rm(r,{force:!0}),"removed"}function Nu(t){return{id:mu(),pid:process.pid,hostname:vu.hostname(),createdAt:new Date().toISOString(),operation:t}}async function bu(t,e){let i;try{i=await Z.open(t,"wx")}catch(r){if(r.code==="EEXIST"){let n=await dg(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(e,null,2)+` -`,"utf8"),await i.sync(),wu(await i.stat({bigint:!0}))}finally{await i.close()}}async function hg(t,e){let i=await T(t.runtimeDir,t.locksDir);await Z.mkdir(i,{recursive:!0});let r=await T(t.runtimeDir,V.join(i,gu));await Z.mkdir(r,{recursive:!0});let n=Nu(e),a=V.join(r,`.${n.id}.tmp`),o=V.join(r,`${n.id}.claim`);try{let s=await bu(a,n);await Z.rename(a,o);let c=await xe(o);if(!c||!xo(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await Z.rm(a,{force:!0})}}async function pg(t){let e=V.dirname(t.file),i=!1,r=V.basename(t.file);for(let n of await Z.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=V.join(e,n.name);if(V.resolve(a)!==V.resolve(t.file))try{let o=await xe(a),s=yu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ro(o,e);continue}n.name=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function vg(t){let e=Yr.get(t)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=e.then(()=>r);return Yr.set(t,n),await e,()=>{i(),Yr.get(t)===n&&Yr.delete(t)}}async function Su(t,e,i){let r=V.resolve(t.locksDir),n=pu.getStore();if(n?.has(r))return i();let a=await vg(r);try{let o=await mg(t,e),s=new Map(n??[]);return s.set(r,o),await pu.run(s,async()=>{try{return await i()}finally{await ku(o)}})}finally{a()}}async function Xr(t,e,i){return Su(t,`acquire ${e}`,async()=>{let r=await T(t.runtimeDir,t.locksDir);await Z.mkdir(r,{recursive:!0});let n=await T(t.runtimeDir,V.join(r,lg(e))),a=Nu(i),o=await bu(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Qr(t){await xe(t.file)&&await Su({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${V.basename(t.file)}`,async()=>{let e=await xe(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Co(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=V.join(t.locksDir,gu);await Ro(e,i)})}function gg(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Eu(t){return yu(await xe(t))}import qo from"node:path";import Yg from"node:path";import xu from"node:path";import{createHash as wg}from"crypto";function se(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function yg(t,e){e.has(t)&&se("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let r=0;rr!==String(n)))&&se("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&se("symbol properties are not supported"),`[${t.map(r=>Ao(r,e)).join(",")}]`}finally{e.delete(t)}}function Ng(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&se("only plain objects are supported"),e.has(t)&&se("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&se("symbol properties are not supported"),e.add(t);try{let r=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&se("accessor properties are not supported"),`${JSON.stringify(o)}:${Ao(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Ao(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||se("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?yg(t,e):Ng(t,e);case"bigint":case"function":case"symbol":case"undefined":return se(`${typeof t} values are not supported`)}return se("unsupported value type")}function _o(t){return Ao(t,new Set)}function K(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return wg("sha256").update(`${t} -${_o(e)}`).digest("hex")}var bg="comet.native.acceptance.v1";var hS=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),yi=Object.freeze({maxCriteria:1024});function Io(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function To(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let r=i[1][0];return e===null?{marker:r,length:i[1].length}:r===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function Pu(t){return t.includes("-->")||t.includes("--!>")}function*gi(t){let e=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,` +`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=jr(e),r=gt(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=jr(e),r=gt(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Yl.Parser=uo});var tu=g(di=>{"use strict";var Xl=Xa(),gv=ii(),ui=ai(),wv=Kn(),yv=P(),Nv=lo(),Ql=fo();function Zl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Nv.LineCounter||null,prettyErrors:e}}function bv(t,e={}){let{lineCounter:i,prettyErrors:r}=Zl(e),n=new Ql.Parser(i?.addNewLine),a=new Xl.Composer(e),o=Array.from(a.compose(n.parse(t)));if(r&&i)for(let s of o)s.errors.forEach(ui.prettifyError(t,i)),s.warnings.forEach(ui.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function eu(t,e={}){let{lineCounter:i,prettyErrors:r}=Zl(e),n=new Ql.Parser(i?.addNewLine),a=new Xl.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new ui.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(ui.prettifyError(t,i)),o.warnings.forEach(ui.prettifyError(t,i))),o}function kv(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=eu(t,i);if(!n)return null;if(n.warnings.forEach(a=>wv.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 Sv(t,e,i){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(t===void 0){let{keepUndefined:n}=i??e??{};if(!n)return}return yv.isDocument(t)&&!r?t.toString(i):new gv.Document(t,r,i).toString(i)}di.parse=kv;di.parseAllDocuments=bv;di.parseDocument=eu;di.stringify=Sv});var wt=g(x=>{"use strict";var Ev=Xa(),Pv=ii(),xv=Ta(),ho=ai(),Rv=Mt(),Fe=P(),Cv=He(),Av=I(),_v=Be(),Tv=Le(),Iv=Tr(),jv=so(),$v=lo(),Ov=fo(),Or=tu(),iu=Ht();x.Composer=Ev.Composer;x.Document=Pv.Document;x.Schema=xv.Schema;x.YAMLError=ho.YAMLError;x.YAMLParseError=ho.YAMLParseError;x.YAMLWarning=ho.YAMLWarning;x.Alias=Rv.Alias;x.isAlias=Fe.isAlias;x.isCollection=Fe.isCollection;x.isDocument=Fe.isDocument;x.isMap=Fe.isMap;x.isNode=Fe.isNode;x.isPair=Fe.isPair;x.isScalar=Fe.isScalar;x.isSeq=Fe.isSeq;x.Pair=Cv.Pair;x.Scalar=Av.Scalar;x.YAMLMap=_v.YAMLMap;x.YAMLSeq=Tv.YAMLSeq;x.CST=Iv;x.Lexer=jv.Lexer;x.LineCounter=$v.LineCounter;x.Parser=Ov.Parser;x.parse=Or.parse;x.parseAllDocuments=Or.parseAllDocuments;x.parseDocument=Or.parseDocument;x.stringify=Or.stringify;x.visit=iu.visit;x.visitAsync=iu.visitAsync});function ds(t,e){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",t.name,"--summary","","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",t.name,"--summary","","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",t.name,"--summary","","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",t.name,"--return-to-build","--summary",""],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(t.status==="blocked"){let n=t.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?["comet","native","next",t.name,"--retry-verifier","--summary",""]:null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(t.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",t.name,"--summary","","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary",""],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(e.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary",""],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=e.children.some(({status:o})=>o==="blocked"),a=e.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input",""],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"",addressed_acceptance_ids:[""],checks:[{name:"",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(t.phase==="verify"){let n=t.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input",""],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[{id:"",name:"",executable:"",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"",acceptance:[{id:"",result:"",reason:""}],risks:[],summary:""}}},{kind:"verifier-execution-error",summary:"",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:""},{kind:"verifier-unavailable",summary:"",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:""}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as My}from"node:crypto";import{promises as Ii}from"node:fs";import Fy from"node:path";import{execFileSync as Jd}from"child_process";import Oi from"path";function An(t,e){return Jd("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Gd(t,e){let i=Oi.normalize(t),r=Oi.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ke(t){try{let e=Oi.resolve(An(t,["rev-parse","--show-toplevel"])),r=An(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Oi.resolve(r.slice(9)):e,a=null;try{a=An(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Gd(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}import{randomUUID as Ud}from"crypto";import{promises as L}from"fs";import ie from"path";function Te(t){return t!==0&&t!==0n&&t!=="0"}function G(t,e){return Te(t.dev)&&Te(e.dev)&&Te(t.ino)&&Te(e.ino)}function A(t,e){let i=Te(t.dev)&&Te(e.dev);if(i&&t.dev!==e.dev)return!1;let r=Te(t.ino)&&Te(e.ino);return r&&t.ino!==e.ino?!1:i&&r?!0:t.birthtime===e.birthtime}function Tn(t,e){let i=ie.relative(t,e);return i===""||!ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ie.sep}`)}function Kd(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function _n(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return G(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function fs(t){let e=await L.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await L.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function $t(t){for(let e of t){let i=await L.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kd(e,i)||await L.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function Yd(t,e){let i=ie.resolve(t),r=ie.resolve(e);if(!Tn(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await fs(i)],a=ie.relative(i,r).split(ie.sep).filter(Boolean),o=i;for(let s of a){await $t(n),o=ie.join(o,s);try{await L.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await fs(o);if(!Tn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await $t(n),n}async function Xd(t){let e;try{e=await L.open(t,"r"),await e.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await e?.close()}}async function Qd(t,e,i={}){let r=ie.dirname(t),n=i.containedRoot?await Yd(i.containedRoot,r):null;n||await L.mkdir(r,{recursive:!0});let a=ie.join(r,`.${ie.basename(t)}.${Ud()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await L.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([L.lstat(a),L.realpath(a)]);if(await $t(n),!c.isFile()||c.isSymbolicLink()||!_n(s,c)||!Tn(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!_n(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await $t(n);let c=await L.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!_n(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await L.link(a,t),await L.unlink(a)):await L.rename(a,t),await Xd(r)}catch(c){if(await o?.close(),!n)await L.rm(a,{force:!0});else try{await $t(n),await L.rm(a,{force:!0})}catch{}throw c}}async function de(t,e,i={}){await Qd(t,e,i)}async function Y(t,e,i={}){await de(t,JSON.stringify(e,null,2)+` +`,i)}import{createHash as rf}from"node:crypto";import{promises as re}from"node:fs";import X from"node:path";import{TextDecoder as nf}from"node:util";var Zd=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ef=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function tf(t){return t.toLowerCase().startsWith(".env")}function Ot(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>tf(r))?"environment-file":i.some(r=>ef.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Zd.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var Di=1024*1024;function In(t,e){let i=X.relative(t,e);return i===""||!X.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${X.sep}`)}function af(t){let e=X.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||X.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),r=Ot(t);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${t}`);return t}function of(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function sf(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hi(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return G(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function hs(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function cf(t,e){let i=X.resolve(t),r=X.resolve(e);if(!In(i,r))throw new Error("Native artifact path is outside its root");let n=[await hs(i)],a=i;for(let o of X.relative(i,r).split(X.sep).filter(Boolean)){a=X.join(a,o);let s=await hs(a);if(!In(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ps(t){for(let e of t){let i=await re.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!sf(e,i)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=af(t.ref),i=t.maxBytes===null?null:of(t.maxBytes??Di),r=X.resolve(t.root,...e.split("/")),n=await cf(t.root,X.dirname(r));await t.hooks?.afterParentChainCaptured?.();let a=await re.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await re.realpath(r);if(!In(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await re.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),re.lstat(r),re.realpath(r)]);if(await ps(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Hi(a,c)||!Hi(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let b=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),re.lstat(r),re.realpath(r)]);if(await ps(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Hi(c,v)||!Hi(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,u),y;try{y=new nf("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:b})}return{ref:e,size:u,hash:t.includeHash===!1?null:rf("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var es=jt(wt(),1);import _t from"path";var mo=jt(wt(),1);import Hr from"path";var fi=64*1024,Dr=1024,Br=64,vo=5,Hv=[".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/**",".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/**"],Dv=["**/.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"],Bv=[...Hv,...Dv].sort((t,e)=>t.localeCompare(e,"en"));var U={include:["**/*"],exclude:[...Bv],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Lv(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Hr.posix.isAbsolute(i)||Hr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function Qe(t){let e=Lv(t,"native.artifact_root");return e.length===0?".":e.join("/")}function nu(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Lr(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Hr.posix.isAbsolute(r)||Hr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function yt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function au(t,e,i){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function go(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Dr)throw new Error(`${e} exceeds ${Dr} characters`);let i=0;for(let r=0;rBr)throw new Error(`${e} contains more than ${Br} wildcard tokens`);return t}function ru(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>go(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function po(t,e,i){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Mv(t){if(t===void 0)return{...U,include:[...U.include],exclude:[...U.exclude]};let e=yt(t,"native.snapshot");return{include:ru(e.include,"native.snapshot.include",U.include),exclude:ru(e.exclude,"native.snapshot.exclude",U.exclude),max_files:po(e.max_files,U.max_files,"native.snapshot.max_files"),max_total_bytes:po(e.max_total_bytes,U.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:po(e.max_duration_ms,U.max_duration_ms,"native.snapshot.max_duration_ms")}}function Fv(t){if(t===void 0)return;let e=yt(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=yt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:Qe(r),toArtifactRoot:Qe(n),stage:a,...o?{cleanup:o}:{}}}function Vv(t,e={}){let i=yt(t,"native"),r=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??vo;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Fv(i.pending_root_move);return{artifact_root:Qe(r),language:au(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Mv(i.snapshot),...s?{pending_root_move:s}:{}}}function qv(t){let e=yt(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:nu(e.artifact_layout),language:au(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function Wv(t){let i=yt(t,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Lr(r,`hook.allow_paths[${n}]`)))]}}function zv(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Jv(t,e,i,r,n,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!o)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:n,...e?{hook:e}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function hi(t,e={}){let i=(0,mo.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=zv(n.ambient_resume),o=n.hook===void 0?void 0:Wv(n.hook),s=n.native===void 0?void 0:Vv(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=n.classic===void 0?void 0:qv(n.classic),l=Jv(n,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function Mr(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Qe(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:vo,snapshot:{...U,include:[...U.include],exclude:[...U.exclude]}}}}import{createHash as Uv}from"crypto";import{promises as qr}from"fs";import Ve from"path";import{constants as Fr,promises as Ze}from"fs";var oe=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}};function wo(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function ou(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function pi(t){return{dev:t.dev,ino:t.ino,birthtime:wo(t)}}function Vr(t,e){let i=pi(t),r=pi(e);return G(i,r)?A(i,r):A(i,r)&&wo(t)===wo(e)&&ou(t)===ou(e)&&t.size===e.size}async function Nt(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Ze.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new oe("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new oe("too-large",`${r} exceeds ${e} bytes`);let o=await Ze.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:pi(a)});let s=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,c;try{c=await Ze.open(t,s)}catch(l){throw l.code==="ELOOP"?new oe("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Ze.lstat(t,{bigint:n}),Ze.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!Vr(a,l)||!Vr(a,f))throw new oe("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:pi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-p,{bytesRead:b}=await c.read(v,0,Math.min(v.length,y),null);if(b===0)break;if(p+=b,p>e)throw new oe("too-large",`${r} exceeds ${e} bytes`);u.push(Buffer.from(v.subarray(0,b)))}await i.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([c.stat({bigint:n}),Ze.lstat(t,{bigint:n}),Ze.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Vr(a,h)||!Vr(a,m))throw new oe("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:pi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:w}}finally{await c.close()}}function Gv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function yo(t,e){let i=Ve.relative(t,e);return i===""||!Ve.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ve.sep}`)}async function su(t,e){let i=Ve.resolve(t),r=await qr.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return qr.realpath(i)}async function cu(t,e,i,r){let n=t;for(let a=0;a{if(!yo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await cu(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var mi=".comet/config.yaml";function Kv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Wr(t,e={}){return(await zr(t,e)).document}async function Yv(t){try{return(await qe(t,mi,fi,{label:mi})).bytes}catch(e){if(Kv(e))return null;throw e}}function Xv(t){return t?{exists:!0,sha256:Uv("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function zr(t,e={}){let i=await Yv(t);return{document:i?hi(i.toString("utf8"),e):null,identity:Xv(i)}}async function No(t){return(await Wr(t))?.config??null}var Ok=16*1024;import{existsSync as uu,promises as et}from"fs";import R from"path";import ig from"os";var Jr=".comet/config.yaml",rg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function So(t){try{return await et.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ng(t){try{let e=await et.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function St(t,e){let i=R.relative(t,e);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function kt(t){let e=[],i=t;for(;!await So(i);){let n=R.dirname(i);if(n===i)break;e.push(R.basename(i)),i=n}let r=await et.realpath(i);return R.resolve(r,...e.reverse())}async function Eo(t){try{return(await et.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Gr(t){let e=R.resolve(t);try{(await et.stat(e)).isDirectory()||(e=R.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=R.resolve(ig.homedir());for(;;){if(!(e===r&&i!==r)){let o=R.join(e,...Jr.split("/")),s=e===i||await ng(o);if(await So(o)&&s)return e}if(await So(R.join(e,".git")))return e;let a=R.dirname(e);if(a===e)return i;e=a}}function Ur(t){return Qe(t)}async function ag(t,e){let i=Ur(e),r=R.resolve(t,...i.split("/")),n=await et.realpath(t),a=await kt(r);if(!St(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Et(t,e){let i=Ur(e),r=await ag(t,i),n=R.join(r,"comet");if(await Eo(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([kt(r),kt(n)]);if(!St(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(t),c=R.join(s,".comet","runtime","native");if(await Eo(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([et.realpath(s),kt(c)]);if(!St(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(t,...Jr.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 du(t){if(!rg.test(t))throw new Error(`Invalid Native change name: ${t}`)}function tt(t,e){du(e);let i=R.join(t.changesRuntimeDir,e);if(!F(t.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Po(t,e){du(e);let i=R.join(t.changesDir,e,"runtime");if(!F(t.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function pe(t,e){let i=tt(t,e);if(uu(i))return i;let r=Po(t,e);return uu(r)?r:i}function me(t,e){let i=R.resolve(e);if(F(t.runtimeDir,i))return t.runtimeDir;if(F(t.nativeRoot,i))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function F(t,e){return St(R.resolve(t),R.resolve(e))}async function T(t,e){let i=R.resolve(t),r=R.resolve(e);if(!St(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await Eo(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([kt(i),kt(r)]);if(!St(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return r}function sg(t="docs",e="en"){return Mr(t,e)}async function Pe(t){let e=(await Wr(t))?.config??null;return e?.native?e:null}async function Kr(t){let e=await Pe(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function fu(t){let e=await Gr(t.startPath),i=await Pe(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Jr} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=t.explicitArtifactRoot?Ur(t.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??sg(r??"docs"),a=await Et(e,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Bw}from"fs";import Lw from"path";import{AsyncLocalStorage as cg}from"async_hooks";import{randomUUID as mu}from"crypto";import{promises as Z}from"fs";import vu from"os";import V from"path";var hu=16*1024,gu=".coordinator",lg=5e3,pu=new cg,Yr=new Map;function ug(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function dg(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${e}`);return i}function wu(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function xo(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return G(i,r)?A(i,r):A(i,r)&&t.size===e.size}function Ro(t,e){return xo(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function xe(t){let e,i;try{let r=await Nt(t,hu,{bigint:!0,label:"Native lock"});e=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof oe?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${hu} bytes: ${t}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:r}):new Error(`Native lock changed while reading: ${t}`,{cause:r}):r}return{file:t,owner:dg(JSON.parse(e.toString("utf8")),t),identity:wu(i)}}async function fg(t){return(await xe(t))?.owner??null}function yu(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==vu.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=wg(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function hg(t,e){try{await Z.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Z.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function Co(t,e){let i=await xe(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Ro(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Z.mkdir(e,{recursive:!0});let r=V.join(e,`${V.basename(t.file)}.${t.owner.id}.${mu()}.removed`);try{await Z.rename(t.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await xe(r);if(!n||n.owner.id!==t.owner.id||!xo(n.identity,t.identity))throw await hg(r,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Z.rm(r,{force:!0}),"removed"}function Nu(t){return{id:mu(),pid:process.pid,hostname:vu.hostname(),createdAt:new Date().toISOString(),operation:t}}async function bu(t,e){let i;try{i=await Z.open(t,"wx")}catch(r){if(r.code==="EEXIST"){let n=await fg(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(e,null,2)+` +`,"utf8"),await i.sync(),wu(await i.stat({bigint:!0}))}finally{await i.close()}}async function pg(t,e){let i=await T(t.runtimeDir,t.locksDir);await Z.mkdir(i,{recursive:!0});let r=await T(t.runtimeDir,V.join(i,gu));await Z.mkdir(r,{recursive:!0});let n=Nu(e),a=V.join(r,`.${n.id}.tmp`),o=V.join(r,`${n.id}.claim`);try{let s=await bu(a,n);await Z.rename(a,o);let c=await xe(o);if(!c||!xo(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await Z.rm(a,{force:!0})}}async function mg(t){let e=V.dirname(t.file),i=!1,r=V.basename(t.file);for(let n of await Z.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=V.join(e,n.name);if(V.resolve(a)!==V.resolve(t.file))try{let o=await xe(a),s=yu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Co(o,e);continue}n.name=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function gg(t){let e=Yr.get(t)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=e.then(()=>r);return Yr.set(t,n),await e,()=>{i(),Yr.get(t)===n&&Yr.delete(t)}}async function Su(t,e,i){let r=V.resolve(t.locksDir),n=pu.getStore();if(n?.has(r))return i();let a=await gg(r);try{let o=await vg(t,e),s=new Map(n??[]);return s.set(r,o),await pu.run(s,async()=>{try{return await i()}finally{await ku(o)}})}finally{a()}}async function Xr(t,e,i){return Su(t,`acquire ${e}`,async()=>{let r=await T(t.runtimeDir,t.locksDir);await Z.mkdir(r,{recursive:!0});let n=await T(t.runtimeDir,V.join(r,ug(e))),a=Nu(i),o=await bu(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Qr(t){await xe(t.file)&&await Su({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${V.basename(t.file)}`,async()=>{let e=await xe(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Ro(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=V.join(t.locksDir,gu);await Co(e,i)})}function wg(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Eu(t){return yu(await xe(t))}import qo from"node:path";import Xg from"node:path";import xu from"node:path";import{createHash as yg}from"crypto";function se(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Ng(t,e){e.has(t)&&se("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let r=0;rr!==String(n)))&&se("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&se("symbol properties are not supported"),`[${t.map(r=>Ao(r,e)).join(",")}]`}finally{e.delete(t)}}function bg(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&se("only plain objects are supported"),e.has(t)&&se("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&se("symbol properties are not supported"),e.add(t);try{let r=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&se("accessor properties are not supported"),`${JSON.stringify(o)}:${Ao(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Ao(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||se("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Ng(t,e):bg(t,e);case"bigint":case"function":case"symbol":case"undefined":return se(`${typeof t} values are not supported`)}return se("unsupported value type")}function _o(t){return Ao(t,new Set)}function K(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return yg("sha256").update(`${t} +${_o(e)}`).digest("hex")}var kg="comet.native.acceptance.v1";var pS=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),yi=Object.freeze({maxCriteria:1024});function Io(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function To(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let r=i[1][0];return e===null?{marker:r,length:i[1].length}:r===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function Pu(t){return t.includes("-->")||t.includes("--!>")}function*gi(t){let e=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,` `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(` -`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&r===null,index:s},s+=1,e!==null)e=To(l,e);else if(i)Pu(l)&&(i=!1);else if(r!==null)new RegExp(``,"iu").test(l)&&(r=null);else{let d=To(l,null);if(d!==null)e=d;else{let u=l.trimStart();if(u.startsWith(""||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),$o(n,"Specification mandatory requirements",r)}var Sg=/^A[1-9]\d*$/u;function Cu(t,e){if(t.length===0||t!==t.trim()||t.includes("\\")||xu.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||xu.posix.normalize(t)!==t||t==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized change-relative ref`);return t}function Eg(t,e){return t.localeCompare(e,"en")}function Bo(t){let e=Cu(t.briefSource??"brief.md","Native brief source"),i=[...t.specs??[]].sort((a,o)=>Eg(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=Oo(t.briefMarkdown,e,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Cu(a.source,`Native spec source for ${a.capability}`);r.push(...Ho(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Do(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=wi(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 Ru(t){let e=t.map(({id:i})=>i);if(new Set(e).size!==e.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function B(t,e,i){if(typeof t!="string"||!i?.empty&&t.length===0)throw new Error(`${e} must be ${i?.empty?"a string":"a non-empty string"}`);return t}function Mo(t,e){return t===null?null:B(t,e)}function Tg(t,e){let i=B(t,e);if(!Ag.test(i))throw new Error(`${e} must be a SHA-256 hash`);return i}function xt(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function _(t,e,i=0){if(!Number.isSafeInteger(t)||ti(r,n))}function rn(t,e){return ve(t,e,(i,r)=>B(i,`${e}[${r}]`))}function it(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Ct(t,e){let i=B(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO date or timestamp`);return i}function Fo(t,e,i=!1){let r=B(t,e);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return r}function ce(t,e){let i=z(t,e);return J(i,new Set(["text","truncated"]),e),{text:B(i.text,`${e}.text`,{empty:!0}),truncated:xt(i.truncated,`${e}.truncated`)}}function jg(t,e){let i=`Native spec_changes[${e}]`,r=z(t,i);J(r,new Set(["capability","operation","source"]),i);let n=B(r.capability,`${i}.capability`);if(!Cg.test(n))throw new Error(`${i}.capability is invalid`);let a=D(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Fo(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 $g(t){let e="Native workspace",i=z(t,e);J(i,new Set(["isolation","change_branch","target_branch","finish"]),e);let r=D(i.isolation,["current","branch","worktree"],`${e}.isolation`),n=Mo(i.change_branch,`${e}.change_branch`),a=Mo(i.target_branch,`${e}.target_branch`),o=i.finish===null?null:D(i.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function Og(t){let e="Native loop",i=z(t,e);J(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let r=rn(i.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return it(r,`${e}.previous_unresolved_ids`),{stage:D(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:_(i.goal_cycle,`${e}.goal_cycle`,1),iteration:_(i.iteration,`${e}.iteration`),attempt:_(i.attempt,`${e}.attempt`),retry_epoch:_(i.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${e}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:r,next_action:Mo(i.next_action,`${e}.next_action`)}}function Hg(t,e){let i=`Native acceptance[${e}]`,r=z(t,i);J(r,new Set(["id","source","text","result","reason"]),i);let n=B(r.id,`${i}.id`);if(!Rg.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Fo(r.source,`${i}.source`),text:B(r.text,`${i}.text`),result:D(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:ce(r.reason,`${i}.reason`)}}function Dg(t,e){let i=`Native builder_handoff.checks[${e}]`,r=z(t,i);return J(r,new Set(["name","result","note"]),i),{name:ce(r.name,`${i}.name`),result:D(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:ce(r.note,`${i}.note`)}}function Bg(t){let e="Native builder_handoff",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let r=rn(i.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return it(r,`${e}.addressed_acceptance_ids`),{candidate_id:B(i.candidate_id,`${e}.candidate_id`),identity_provider:B(i.identity_provider,`${e}.identity_provider`),builder_execution_ref:B(i.builder_execution_ref,`${e}.builder_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),summary:ce(i.summary,`${e}.summary`),addressed_acceptance_ids:r,checks:ve(i.checks,`${e}.checks`,Dg),checks_truncated:xt(i.checks_truncated,`${e}.checks_truncated`),known_limits:ve(i.known_limits,`${e}.known_limits`,(n,a)=>ce(n,`${e}.known_limits[${a}]`)),known_limits_truncated:xt(i.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Ct(i.submitted_at,`${e}.submitted_at`)}}function Lg(t,e){let i=`Native blockers[${e}]`,r=z(t,i);J(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=rn(r.acceptance_ids,`${i}.acceptance_ids`);return it(n,`${i}.acceptance_ids`),{owner:D(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:ce(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:D(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Mg(t,e){let i=`Native verification.checks[${e}]`,r=z(t,i);return J(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:B(r.id,`${i}.id`),name:ce(r.name,`${i}.name`),argv_display:ve(r.argv_display,`${i}.argv_display`,(n,a)=>ce(n,`${i}.argv_display[${a}]`)),argv_truncated:xt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Fo(r.cwd_ref,`${i}.cwd_ref`,!0),status:D(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Ig(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Fg(t){let e="Native verification",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let r=ve(i.checks,`${e}.checks`,Mg);it(r.map(a=>a.id),`${e}.checks IDs`);let n=B(i.identity_provider,`${e}.identity_provider`);return{candidate_id:B(i.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:B(i.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),attempt:_(i.attempt,`${e}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":D(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:D(i.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:r,summary:ce(i.summary,`${e}.summary`),risks:ve(i.risks,`${e}.risks`,(a,o)=>ce(a,`${e}.risks[${o}]`)),risks_truncated:xt(i.risks_truncated,`${e}.risks_truncated`),completed_at:Ct(i.completed_at,`${e}.completed_at`)}}function Vg(t,e){let i=`Native history[${e}]`,r=z(t,i);J(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=rn(r.unresolved_ids,`${i}.unresolved_ids`);return it(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:D(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:ce(r.summary,`${i}.summary`),completed_at:Ct(r.completed_at,`${i}.completed_at`)}}function qg(t){let e="Native history_overflow.outcome_counts",i=z(t,e),r=["pass","fail","blocked","execution-error","recovery"];return J(i,new Set(r),e),{pass:_(i.pass,`${e}.pass`),fail:_(i.fail,`${e}.fail`),blocked:_(i.blocked,`${e}.blocked`),"execution-error":_(i["execution-error"],`${e}.execution-error`),recovery:_(i.recovery,`${e}.recovery`)}}function Wg(t){let e="Native history_overflow",i=z(t,e);J(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let r=_(i.dropped_entries,`${e}.dropped_entries`),n=i.first_dropped_at===null?null:Ct(i.first_dropped_at,`${e}.first_dropped_at`),a=i.last_dropped_at===null?null:Ct(i.last_dropped_at,`${e}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=qg(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 zg(t){let e=new Set(t.acceptance.map(i=>i.id));for(let i of t.loop.previous_unresolved_ids)if(!e.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of t.blockers)for(let r of i.acceptance_ids)if(!e.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Jg(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let i=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(i!==null&&t.loop.stage!==i)throw new Error(`Native status ${t.status} requires loop stage ${i}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function rt(t){let e=z(t,"Native portable state");if(J(e,_g,"Native portable state"),e.schema!==Pt)throw new Error(`Native portable state schema must be ${Pt}`);let i=B(e.name,"Native state name");if(!xg.test(i))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ve(e.spec_changes,"Native spec_changes",jg);it(r.map(s=>s.capability),"Native spec change capabilities");let n=ve(e.acceptance,"Native acceptance",Hg);it(n.map(s=>s.id),"Native acceptance IDs");let a=ve(e.history,"Native history",Vg);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Pt,name:i,language:D(e.language,["en","zh-CN"],"Native state language"),phase:D(e.phase,["shape","build","verify","archive"],"Native state phase"),status:D(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:Tg(e.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:$g(e.workspace),loop:Og(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:Bg(e.builder_handoff),blockers:ve(e.blockers,"Native blockers",Lg),verification:e.verification===null?null:Fg(e.verification),history:a,history_overflow:Wg(e.history_overflow),verification_result:D(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:D(e.verification_report,["verification.md"],"Native verification_report"),archived:xt(e.archived,"Native archived"),created_at:Ct(e.created_at,"Native created_at")};return zg(o),Jg(o),o}function Gg(t,e){let i=(0,tn.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${e} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ce(t){let e=await Pg.readFile(t,"utf8");return rt(Gg(e,"Native portable state"))}async function nn(t,e,i={}){let r=rt(e);await de(t,(0,tn.stringify)(r),i)}var Zr=new Map;async function Ug(t,e){let i=Zr.get(t)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Zr.set(t,a),await i;try{return await e()}finally{r(),Zr.get(t)===a&&Zr.delete(t)}}async function _u(t){return Ug(t.file,async()=>{let e=_(t.expectedStateVersion,"Native expected state version",1),i=rt(t.next);if(i.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ce(t.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==e)throw new en(e,r.state_version);return await nn(t.file,i,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Ce(t.file);if(n.state_version!==e)throw new en(e,n.state_version)}}),i})}function Kg(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function an(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(Kg(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let i="",r=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(r+a>e)break;i+=n,r+=a}return{text:i,truncated:!0}}var Re="comet.native.v3",ge="comet.native.v2",we="comet.native.v1";var on="comet.native.portable-migration.v1",Xg=new Set(["schema","id","change","fromSchema","status","createdAt"]),Qg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zg=/^[a-z0-9][a-z0-9-]{7,127}$/u,ew=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),tw=new Set([we,ge,Re]);function iw(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function rw(t,e){let i=t instanceof Date?new Date(t.valueOf()):new Date(t);if(Number.isNaN(i.valueOf()))throw new Error(`${e} must be a valid timestamp`);return i.toISOString()}function nw(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function aw(t){return t.schema===we?bi(t):t.schema===ge?ki(t):Si(t)}function ow(t){return Yg.posix.normalize(t.replaceAll("\\","/"))}function sw(t){return t.spec_changes.map(e=>e.operation==="remove"?{capability:e.capability,operation:"remove",source:null}:{capability:e.capability,operation:e.operation==="replace"?"modify":"create",source:ow(e.source)})}function cw(t){return t==="shape"?"shape":"build"}function lw(t,e){return t==="zh-CN"?e==="shape"?"继续澄清并确认验收项":"重新提交候选实现":e==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function uw(t,e,i){return t==="zh-CN"?`从旧版 ${e} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${e} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Tu(t){let e=aw(t.state);Ru(t.acceptance);let i=cw(e.phase),r=i==="shape"?0:1,n=rw(t.migratedAt??`${e.created_at}T00:00:00.000Z`,"Native portable migration time"),a=t.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return rt({schema:Pt,name:e.name,language:e.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:sw(e),workspace:t.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:lw(e.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:an(uw(e.language,e.schema,e.phase)),completed_at:n}],history_overflow:Lo(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${e.created_at}T00:00:00.000Z`})}function Vo(t){let e=iw(t,"Native portable migration transaction"),i=Object.keys(e).filter(r=>!Xg.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(e.schema!==on)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!Zg.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!Qg.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!tw.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!ew.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:on,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:nw(e.createdAt,"Native portable migration transaction createdAt")}}function Iu(t){switch(Vo(t).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var ju="comet.native.archive-transaction.v4",$u="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",dw=new RegExp(`^portable-archive-(${$u})\\.json$`,"u"),fw=new RegExp(`^portable-migration-(${$u})\\.json$`,"u"),hw=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pw=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mw=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),vw=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),gw=new Set(["capability","operation","source","content"]),Ou=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Hu(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Du(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${i} fields are invalid`)}function ww(t,e){let i=`Native portable Archive spec_changes[${e}]`,r=Hu(t,i);if(Du(r,gw,i),typeof r.capability!="string"||!Ou.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 yw(t){let e=Hu(t,"Native portable Archive transaction");if(Du(e,vw,"Native portable Archive transaction"),e.schema!==ju)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!hw.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Ou.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!pw.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!mw.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=e.spec_changes.map(ww);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(e.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:ju,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:i,created_at:e.created_at}}function sn(t){let e=dw.exec(t);if(e)return{kind:"archive",change:e[1]};let i=fw.exec(t);return i?{kind:"migration",change:i[1]}:null}function cn(t,e){let i=`${e.kind==="archive"?"portable-archive":"portable-migration"}-${e.change}.json`,r=sn(i);if(!r||r.kind!==e.kind||r.change!==e.change)throw new Error(`Invalid Native portable transaction change: ${e.change}`);return qo.join(t.transactionsDir,i)}async function Wo(t,e){let i=sn(e);if(!i)return null;let r=await M({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=qo.join(t.transactionsDir,e);if(i.kind==="archive"){let s=yw(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=Vo(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 Bu(t,e){let i=cn(t,e);try{return await Wo(t,qo.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function Lu(t){return t.kind==="archive"||t.journal.status!=="committed"}import Ae from"path";import{TextDecoder as Cw}from"util";import{createHash as Nw}from"node:crypto";import{constants as ln,promises as le}from"node:fs";import ue from"node:path";function dn(t,e){let i=ue.relative(t,e);return i===""||!ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ue.sep}`)}function bw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function kw(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Sw(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function un(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function zo(t,e){let i=await le.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await le.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ew(t,e,i){let r=ue.resolve(t),n=ue.resolve(e);if(!dn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await zo(r,i)],o=r;for(let s of ue.relative(r,n).split(ue.sep).filter(Boolean)){await nt(a,i),o=ue.join(o,s);let c=await zo(o,i);if(!dn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await nt(a,i),a}async function nt(t,e){for(let i of t){let r=await le.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!kw(i,r)||await le.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Pw(t,e,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Rt(t){let e=bw(t.maxBytes),i=ue.resolve(t.file),r=await Ew(t.root,ue.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(f=>zo(ue.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await nt(r,t.label);let a=await le.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Sw(a),s=await le.realpath(i);if(!dn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(f=>dn(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ln.O_RDONLY:ln.O_RDONLY|ln.O_NOFOLLOW|ln.O_NONBLOCK,l=await le.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[d,u]=await Promise.all([le.lstat(i),le.realpath(i)]);if(await nt(r,t.label),await nt(n,t.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!un(o,f)||!un(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await Pw(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),le.lstat(i),le.realpath(i)]);if(await nt(r,t.label),await nt(n,t.label),!h.isFile()||h.isSymbolicLink()||m!==s||!un(o,v)||!un(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:Nw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Rw=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Aw=new Set(["id","type","source","target","staged","backup"]),_w=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Tw=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Vu=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Iw=256*1024,XS=1024*1024,QS=16*1024;var ZS=64*1024*1024;var jw=new Cw("utf-8",{fatal:!0});function hn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function pn(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function qu(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Jo(t,e){if(typeof t!="string"||t.length===0||Ae.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function fn(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Mu(t,e){if(Jo(t,e),t.includes("\\")||t!==Ae.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function $w(t,e){let i=hn(t,`transaction operations[${e}]`);if(pn(i,Aw,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Jo(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Jo(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 Wu(t){let e=hn(t,"Native Archive transaction journal");if(pn(e,_w,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Vu.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!qu(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fn(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=hn(s,`Archive transaction operations[${c}]`);if(pn(l,Tw,`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`);Mu(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Mu(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&fn(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(fn(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`);fn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function Ow(t){let e=hn(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Wu(e);if(pn(e,Rw,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Vu.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Ae.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Ae.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!qu(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map($w),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function Hw(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Ae.join(t.transactionsDir,e)}function zu(t,e){let i=Hw(t,e);return{directory:i,journal:Ae.join(i,"transaction.json"),events:Ae.join(i,"events.jsonl"),staged:Ae.join(i,"staged"),backups:Ae.join(i,"backups")}}async function Uo(t,e){let i=zu(t,e);return await Promise.all(Object.values(i).map(r=>T(t.runtimeDir,r))),i}async function Ko(t,e,i={}){let r=await Uo(t,e),n=await Rt({root:t.runtimeDir,file:r.journal,maxBytes:Iw,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(jw.decode(n.bytes)),o=Ow(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Lw(t,e,i){let r;try{r=await Dw.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Ko(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(sn(n.name))try{let a=await Wo(t,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Lu(a))return!0}catch{return!0}return!1}async function Mw(t,e){let i=Date.now()+5e3,r=Bw.join(t.locksDir,"root-move.lock");for(;;)try{return await Xr(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Eu(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 ee(t,e,i,r){let n=await Mw(t,e);try{if(await Kr(t.projectRoot),await Lw(t,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Qr(n)}}import{createHash as Fw}from"crypto";function te(t){return Fw("sha256").update(t).digest("hex")}var NE={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var bE=8*1024*1024;var kE=64*1024,SE=64*1024;var EE={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},PE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var xE=(1n<<256n)-1n;var Uw=jt(wt(),1);var VE=4*1024*1024;var Kw=null;function Yw(t,e){let i=t;for(let r of e)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Ju(t,e){return(...i)=>{let r=Kw;if(r===null)return e(...i);let n=Yw(`async:${t}`,i),a=r.entries.get(n);if(a)return a.value;let o=e(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var GE=Ju("hookWritePolicy",async t=>(await No(t))?.hook??{allow_paths:[]});var VP=256*1024;var tx={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 At from"node:path";var Ei=/^[a-f0-9]{64}$/u,Uu=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Zw=16*1024,gx=process.platform;function ey(t,e){let i=At.relative(t,e);return At.isAbsolute(i)||i===".."||i.startsWith(`..${At.sep}`)?null:i.replaceAll("\\","/")||"."}function Ku(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Yu(t,e){if(t.length===0||Ku(t)||t.includes("\\")||At.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=At.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function ty(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function Yo(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Ku(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function iy(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Yo(t.changeBranch,"Native workspace change branch"),Yo(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function ry(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(e).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!Uu.test(e.baseCommit)||typeof e.targetCommit!="string"||!Uu.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Yo(e.targetBranch,"Native workspace Git target branch")}function ny(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Ei.test(String(e.projectRootId))||!Ei.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");ty(e.capturedAt),Yu(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ei.test(String(e.projectRootPathId))||a&&!Ei.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Ei.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&ry(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(iy(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function ay(t,e){return At.join(pe(t,e),"workspace.json")}function oy(t,e){let i=ay(t,e),r=me(t,i),n=ey(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Yu(n,"Native workspace file ref")}}async function sy(t,e){try{let i=oy(t,e),r=await M({root:i.root,ref:i.ref,maxBytes:Zw});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pi(t,e){let i=await sy(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ny(i),i)}var Zu=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],ly=new Set(Zu),ed=new Set([...Zu,"minimum_runtime_version","revision"]),uy=new Set([...ed,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),dy=new Set(["capability","operation","source","base_hash"]),fy=new Set(["shape","build","verify","archive"]),hy=new Set(["implicit","confirmed"]),py=new Set(["pending","pass","fail"]),at="comet-state.yaml",Qo=/^[a-f0-9]{64}$/u,td=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,my=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Zo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Tt=class extends Error{constructor(i,r){super(i!==Re||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},mn=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"},xi=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"},vn=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"},Vx=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` -`);function Ri(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function id(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ts(t){if(!td.test(t))throw new Error(`Invalid Native change name: ${t}`)}function vy(t){if(!td.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function rd(t,e){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function gy(t,e){let i=Ri(t,`spec_changes[${e}]`);if(id(i,dy,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(vy(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"&&rd(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"||!Qo.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"||!Qo.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 wy(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function is(t,e){if(id(t,e,at),typeof t.name!="string")throw new Error("Native change name is required");if(ts(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!fy.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!hy.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(gy),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof t.verification_result!="string"||!py.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&rd(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!wy(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function bi(t){let e=Ri(t,at);if(e.schema!==we)throw new Error(`Expected ${we}`);return{schema:we,...is(e,ly)}}function Ci(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Xo(t,e,i){if(t===null)return null;let r=typeof t=="string"?my.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/.json relative to the Native change`);return t}function yy(t){if(t==null)return null;if(typeof t!="string"||!Qo.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function Ny(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function ki(t){let e=Ri(t,at);if(e.schema!==ge)throw new Error(`Expected ${ge}`);if(Ci(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ge} minimum_runtime_version must be 2`);return{schema:ge,minimum_runtime_version:2,revision:Ci(e.revision,"Native v2 revision"),...is(e,ed)}}function Si(t){let e=Ri(t,at);if(e.schema!==Re){if(e.schema===we||e.schema===ge){let o=e.schema===we?bi(e):ki(e);throw new Zo(o.name,o.schema)}throw new Tt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Ci(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Tt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Ci(e.revision,"Native revision"),n=is(e,uy),a=yy(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Re,minimum_runtime_version:3,revision:r,verification_protocol:Ny(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xo(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xo(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xo(e.partial_allowance,"Native partial_allowance","allowances")}}function by(t){let e=Ri(t,at);if(e.schema===we){let n=bi(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema===ge){let n=ki(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema!==Re){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Tt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Ci(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Tt(e.schema,i).message};let r=Si(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function ye(t,e){ts(e);let i=_t.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}var ky=256*1024;async function Sy(t,e=_t.dirname(t)){let i=_t.relative(e,t).split(_t.sep).join("/"),r=await M({root:e,ref:i,maxBytes:ky}),n=(0,es.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function nd(t,e){let i=_t.join(ye(t,e),at);await T(t.nativeRoot,i);let r=by(await Sy(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return r}import{promises as sd}from"node:fs";import Sn from"node:path";var Py=jt(wt(),1);var Wx=8*1024*1024;var eC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as Ty}from"node:fs";import _i from"node:path";function gn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function wn(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ne(t,e,i=!1){if(typeof t!="string"||!i&&t.length===0)throw new Error(`${e} must be ${i?"a string":"a non-empty string"}`);return t}function ad(t,e){return t===null?null:Ne(t,e)}function Nn(t,e,i=0){if(!Number.isSafeInteger(t)||tNe(l,`${i}.argv[${f}]`,!0)),a=yn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=rs(r.startedAt,`${i}.startedAt`),s=rs(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=Nn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ne(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),operationId:Ne(r.operationId,`${i}.operationId`),status:a,repeatable:jy(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Nn(r.executionCount,`${i}.executionCount`),argv:n,cwd:ns(r.cwd,`${i}.cwd`),exitCode:Iy(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ne(r.log,`${i}.log`)}}function od(t){let e="Native local execution state",i=gn(t,e);if(wn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),i.schema!==Ni)throw new Error(`Native local execution schema must be ${Ni}`);let r=gn(i.workspace,"Native local workspace");wn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=gn(i.execution,"Native local execution");wn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=rs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ne(o.operationId,"Native local execution.operationId"),stage:yn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:yn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ad(o.executionId,"Native local execution.executionId"),status:yn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Nn(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($y);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:Ni,change:Ne(i.change,"Native local change"),basedOnStateVersion:Nn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:ns(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ns(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ad(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function bn(t){return od({schema:Ni,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:_i.resolve(t.projectRoot),worktreeRoot:_i.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function kn(t,e,i={}){let r=od(e);await Ty.mkdir(_i.dirname(t),{recursive:!0}),await Y(t,r,i)}var cd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oy="comet-state.yaml",Hy="state.json";function ld(t,e){if(!cd.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=Sn.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}function ze(t,e){return Sn.join(ld(t,e),Oy)}function as(t,e){return Sn.join(tt(t,e),Hy)}async function Ti(t,e){try{let i=await sd.readFile(ze(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function Dy(t){return ke(t).currentBranch}async function ud(t,e){return Ce(ze(t,e))}async function By(t){let e=await _u({file:ze(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let i=Sn.join(ld(t.paths,e.name),"verification.md");await T(t.paths.nativeRoot,i),await sd.rm(i,{force:!0})}return e}async function dd(t){if(!cd.test(t.capability))throw new Error(`Invalid Native capability: ${t.capability}`);return ee(t.paths,`remove portable spec ${t.capability}`,async()=>{let e=await ud(t.paths,t.name);if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i=e.spec_changes.filter(({capability:a})=>a!==t.capability),r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:[...i,{capability:t.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await By({paths:t.paths,previous:e,next:r});return await kn(as(t.paths,e.name),bn({portableState:n,projectRoot:t.paths.projectRoot,branch:Dy(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}var Fy=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function Vy(t,e){let i=await Bu(t,{kind:"migration",change:e});return i?.kind==="migration"?i.journal:null}async function fd(t,e){await Ii.mkdir(t.transactionsDir,{recursive:!0}),await Y(cn(t,{kind:"migration",change:e.change}),e,{containedRoot:t.runtimeDir})}async function hd(t,e){await Promise.all([Ii.rm(tt(t,e),{recursive:!0,force:!0}),Ii.rm(Po(t,e),{recursive:!0,force:!0}),...Fy.map(i=>Ii.rm(My.join(ye(t,e),i),{force:!0}))])}async function pd(t,e){await kn(as(t,e.name),bn({portableState:e,projectRoot:t.projectRoot}),{containedRoot:t.runtimeDir})}async function md(t,e){try{let i=await Pi(t,e);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function vd(t,e){if(e.isolation==="current"&&e.change_branch===null)return;let i=ke(t.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==e.change_branch)throw new Error(`Native legacy migration expected branch ${e.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function qy(t){let e=ye(t.paths,t.state.name),i=await M({root:e,ref:t.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of t.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await M({root:e,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Bo({briefMarkdown:i.text,specs:r})}catch(n){if(t.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function gd(t,e){let i=await nd(t,e);if(!i.state)throw new Error(`Native legacy change ${e} is unreadable`);return i.state}async function wd(t){return ee(t.paths,`migrate ${t.name} to portable Native`,async()=>{let e=await Vy(t.paths,t.name),i=await Ti(t.paths,t.name)?await Ce(ze(t.paths,t.name)):null;if(!e&&i)return await hd(t.paths,t.name),await pd(t.paths,i),i;let r=null,n=null;for(e||(r=await gd(t.paths,t.name),n=await md(t.paths,t.name),vd(t.paths,n),e={schema:on,id:Ly(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(t.now??new Date).toISOString()},await fd(t.paths,e));;){let a=Iu(e);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await gd(t.paths,t.name),n??=await md(t.paths,t.name),vd(t.paths,n),i=Tu({state:r,acceptance:await qy({paths:t.paths,state:r}),workspace:n,migratedAt:t.now}),await nn(ze(t.paths,t.name),i,{containedRoot:t.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await hd(t.paths,t.name):a.action==="commit-transaction"&&(i??=await Ce(ze(t.paths,t.name)),await pd(t.paths,i)),e={...e,status:a.nextStatus},await fd(t.paths,e)}return await Ii.rm(cn(t.paths,{kind:"migration",change:t.name}),{force:!0}),i??Ce(ze(t.paths,t.name))},{allowedPortableTransaction:{kind:"migration",change:t.name}})}import cs from"path";var zy=["Outcome","Scope","Non-goals","Acceptance examples"],QR=[...zy,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var Jy=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 yd=1024*1024;var bd="scoped-text-safety",Gy=1,Uy=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Ky="comet.native.checker-policy.v1";var pA=K(Ky,{policy:bd,version:Gy,limits:Uy,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Yy=["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"],mA=new Set(Yy);var Zy=yd,IA=3*Zy;var kd={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:[]},tN=te("comet-native-runtime:v3:scope-reopen"),a_=[{skillVersion:"3",skillHash:te("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:te("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:te("comet-native-runtime:v1")}];var Ed=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],L_=new Set(Ed),cN=new Set([...Ed,"minimum_runtime_version","revision"]),M_=new Set([...cN,"operation"]),F_=512*1024,lN=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),V_=new Set([...lN,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var J_={maxAcceptanceCriteria:yi.maxCriteria};var X_={maxSpecs:64,maxFileBytes:Di,maxTotalBytes:4*1024*1024};import{execFile as wN}from"node:child_process";import{promisify as yN}from"node:util";var sT={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var RT=512*1024;var ji=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var XT=64*1024;var QT=3600*1e3;var ZT=yN(wN);var En=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var BI={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var UI=16*1024*1024,KI=256*1024,YI=16*1024;var tj=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var nj=16*1024;var vj=16*1024;var o$=16*1024*1024,Pn=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"},xn=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 Cn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Cd=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ss=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:Cd,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] +`),o.context,r)),o=null}};for(let{line:c,body:l}of gi(t)){let f=l?Io(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=wi(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),$o(n,"Specification",r)}function Do(t,e="spec.md",i=yi.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(jo("spec-must",e,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(f=>/^(?:non-?goals?|非目标)$/iu.test(f.text.trim()));for(let{line:f,body:d}of gi(t)){let u=d?Io(f):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=f.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||To(f,null)!==null||p.startsWith(""||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),$o(n,"Specification mandatory requirements",r)}var Eg=/^A[1-9]\d*$/u;function Ru(t,e){if(t.length===0||t!==t.trim()||t.includes("\\")||xu.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||xu.posix.normalize(t)!==t||t==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized change-relative ref`);return t}function Pg(t,e){return t.localeCompare(e,"en")}function Bo(t){let e=Ru(t.briefSource??"brief.md","Native brief source"),i=[...t.specs??[]].sort((a,o)=>Pg(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=Oo(t.briefMarkdown,e,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Ru(a.source,`Native spec source for ${a.capability}`);r.push(...Ho(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Do(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=wi(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 Cu(t){let e=t.map(({id:i})=>i);if(new Set(e).size!==e.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function B(t,e,i){if(typeof t!="string"||!i?.empty&&t.length===0)throw new Error(`${e} must be ${i?.empty?"a string":"a non-empty string"}`);return t}function Mo(t,e){return t===null?null:B(t,e)}function Ig(t,e){let i=B(t,e);if(!_g.test(i))throw new Error(`${e} must be a SHA-256 hash`);return i}function xt(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function _(t,e,i=0){if(!Number.isSafeInteger(t)||ti(r,n))}function rn(t,e){return ve(t,e,(i,r)=>B(i,`${e}[${r}]`))}function it(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Rt(t,e){let i=B(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO date or timestamp`);return i}function Fo(t,e,i=!1){let r=B(t,e);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return r}function ce(t,e){let i=z(t,e);return J(i,new Set(["text","truncated"]),e),{text:B(i.text,`${e}.text`,{empty:!0}),truncated:xt(i.truncated,`${e}.truncated`)}}function $g(t,e){let i=`Native spec_changes[${e}]`,r=z(t,i);J(r,new Set(["capability","operation","source"]),i);let n=B(r.capability,`${i}.capability`);if(!Cg.test(n))throw new Error(`${i}.capability is invalid`);let a=D(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Fo(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 Og(t){let e="Native workspace",i=z(t,e);J(i,new Set(["isolation","change_branch","target_branch","finish"]),e);let r=D(i.isolation,["current","branch","worktree"],`${e}.isolation`),n=Mo(i.change_branch,`${e}.change_branch`),a=Mo(i.target_branch,`${e}.target_branch`),o=i.finish===null?null:D(i.finish,["merge","push","pull-request","keep"],`${e}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function Hg(t){let e="Native loop",i=z(t,e);J(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let r=rn(i.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return it(r,`${e}.previous_unresolved_ids`),{stage:D(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:_(i.goal_cycle,`${e}.goal_cycle`,1),iteration:_(i.iteration,`${e}.iteration`),attempt:_(i.attempt,`${e}.attempt`),retry_epoch:_(i.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${e}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:r,next_action:Mo(i.next_action,`${e}.next_action`)}}function Dg(t,e){let i=`Native acceptance[${e}]`,r=z(t,i);J(r,new Set(["id","source","text","result","reason"]),i);let n=B(r.id,`${i}.id`);if(!Ag.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Fo(r.source,`${i}.source`),text:B(r.text,`${i}.text`),result:D(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:ce(r.reason,`${i}.reason`)}}function Bg(t,e){let i=`Native builder_handoff.checks[${e}]`,r=z(t,i);return J(r,new Set(["name","result","note"]),i),{name:ce(r.name,`${i}.name`),result:D(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:ce(r.note,`${i}.note`)}}function Lg(t){let e="Native builder_handoff",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let r=rn(i.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return it(r,`${e}.addressed_acceptance_ids`),{candidate_id:B(i.candidate_id,`${e}.candidate_id`),identity_provider:B(i.identity_provider,`${e}.identity_provider`),builder_execution_ref:B(i.builder_execution_ref,`${e}.builder_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),summary:ce(i.summary,`${e}.summary`),addressed_acceptance_ids:r,checks:ve(i.checks,`${e}.checks`,Bg),checks_truncated:xt(i.checks_truncated,`${e}.checks_truncated`),known_limits:ve(i.known_limits,`${e}.known_limits`,(n,a)=>ce(n,`${e}.known_limits[${a}]`)),known_limits_truncated:xt(i.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Rt(i.submitted_at,`${e}.submitted_at`)}}function Mg(t,e){let i=`Native blockers[${e}]`,r=z(t,i);J(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=rn(r.acceptance_ids,`${i}.acceptance_ids`);return it(n,`${i}.acceptance_ids`),{owner:D(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:ce(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:D(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Fg(t,e){let i=`Native verification.checks[${e}]`,r=z(t,i);return J(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:B(r.id,`${i}.id`),name:ce(r.name,`${i}.name`),argv_display:ve(r.argv_display,`${i}.argv_display`,(n,a)=>ce(n,`${i}.argv_display[${a}]`)),argv_truncated:xt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Fo(r.cwd_ref,`${i}.cwd_ref`,!0),status:D(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:jg(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Vg(t){let e="Native verification",i=z(t,e);J(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let r=ve(i.checks,`${e}.checks`,Fg);it(r.map(a=>a.id),`${e}.checks IDs`);let n=B(i.identity_provider,`${e}.identity_provider`);return{candidate_id:B(i.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:B(i.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),attempt:_(i.attempt,`${e}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":D(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:D(i.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:r,summary:ce(i.summary,`${e}.summary`),risks:ve(i.risks,`${e}.risks`,(a,o)=>ce(a,`${e}.risks[${o}]`)),risks_truncated:xt(i.risks_truncated,`${e}.risks_truncated`),completed_at:Rt(i.completed_at,`${e}.completed_at`)}}function qg(t,e){let i=`Native history[${e}]`,r=z(t,i);J(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=rn(r.unresolved_ids,`${i}.unresolved_ids`);return it(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:D(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:ce(r.summary,`${i}.summary`),completed_at:Rt(r.completed_at,`${i}.completed_at`)}}function Wg(t){let e="Native history_overflow.outcome_counts",i=z(t,e),r=["pass","fail","blocked","execution-error","recovery"];return J(i,new Set(r),e),{pass:_(i.pass,`${e}.pass`),fail:_(i.fail,`${e}.fail`),blocked:_(i.blocked,`${e}.blocked`),"execution-error":_(i["execution-error"],`${e}.execution-error`),recovery:_(i.recovery,`${e}.recovery`)}}function zg(t){let e="Native history_overflow",i=z(t,e);J(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let r=_(i.dropped_entries,`${e}.dropped_entries`),n=i.first_dropped_at===null?null:Rt(i.first_dropped_at,`${e}.first_dropped_at`),a=i.last_dropped_at===null?null:Rt(i.last_dropped_at,`${e}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Wg(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 Jg(t){let e=new Set(t.acceptance.map(i=>i.id));for(let i of t.loop.previous_unresolved_ids)if(!e.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of t.blockers)for(let r of i.acceptance_ids)if(!e.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Gg(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let i=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(i!==null&&t.loop.stage!==i)throw new Error(`Native status ${t.status} requires loop stage ${i}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function rt(t){let e=z(t,"Native portable state");if(J(e,Tg,"Native portable state"),e.schema!==Pt)throw new Error(`Native portable state schema must be ${Pt}`);let i=B(e.name,"Native state name");if(!Rg.test(i))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ve(e.spec_changes,"Native spec_changes",$g);it(r.map(s=>s.capability),"Native spec change capabilities");let n=ve(e.acceptance,"Native acceptance",Dg);it(n.map(s=>s.id),"Native acceptance IDs");let a=ve(e.history,"Native history",qg);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Pt,name:i,language:D(e.language,["en","zh-CN"],"Native state language"),phase:D(e.phase,["shape","build","verify","archive"],"Native state phase"),status:D(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:Ig(e.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Og(e.workspace),loop:Hg(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:Lg(e.builder_handoff),blockers:ve(e.blockers,"Native blockers",Mg),verification:e.verification===null?null:Vg(e.verification),history:a,history_overflow:zg(e.history_overflow),verification_result:D(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:D(e.verification_report,["verification.md"],"Native verification_report"),archived:xt(e.archived,"Native archived"),created_at:Rt(e.created_at,"Native created_at")};return Jg(o),Gg(o),o}function Ug(t,e){let i=(0,tn.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${e} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Re(t){let e=await xg.readFile(t,"utf8");return rt(Ug(e,"Native portable state"))}async function nn(t,e,i={}){let r=rt(e);await de(t,(0,tn.stringify)(r),i)}var Zr=new Map;async function Kg(t,e){let i=Zr.get(t)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Zr.set(t,a),await i;try{return await e()}finally{r(),Zr.get(t)===a&&Zr.delete(t)}}async function _u(t){return Kg(t.file,async()=>{let e=_(t.expectedStateVersion,"Native expected state version",1),i=rt(t.next);if(i.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Re(t.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==e)throw new en(e,r.state_version);return await nn(t.file,i,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Re(t.file);if(n.state_version!==e)throw new en(e,n.state_version)}}),i})}function Yg(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function an(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(Yg(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let i="",r=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(r+a>e)break;i+=n,r+=a}return{text:i,truncated:!0}}var Ce="comet.native.v3",ge="comet.native.v2",we="comet.native.v1";var on="comet.native.portable-migration.v1",Qg=new Set(["schema","id","change","fromSchema","status","createdAt"]),Zg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ew=/^[a-z0-9][a-z0-9-]{7,127}$/u,tw=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),iw=new Set([we,ge,Ce]);function rw(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function nw(t,e){let i=t instanceof Date?new Date(t.valueOf()):new Date(t);if(Number.isNaN(i.valueOf()))throw new Error(`${e} must be a valid timestamp`);return i.toISOString()}function aw(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function ow(t){return t.schema===we?bi(t):t.schema===ge?ki(t):Si(t)}function sw(t){return Xg.posix.normalize(t.replaceAll("\\","/"))}function cw(t){return t.spec_changes.map(e=>e.operation==="remove"?{capability:e.capability,operation:"remove",source:null}:{capability:e.capability,operation:e.operation==="replace"?"modify":"create",source:sw(e.source)})}function lw(t){return t==="shape"?"shape":"build"}function uw(t,e){return t==="zh-CN"?e==="shape"?"继续澄清并确认验收项":"重新提交候选实现":e==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function dw(t,e,i){return t==="zh-CN"?`从旧版 ${e} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${e} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Tu(t){let e=ow(t.state);Cu(t.acceptance);let i=lw(e.phase),r=i==="shape"?0:1,n=nw(t.migratedAt??`${e.created_at}T00:00:00.000Z`,"Native portable migration time"),a=t.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return rt({schema:Pt,name:e.name,language:e.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:cw(e),workspace:t.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:uw(e.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:an(dw(e.language,e.schema,e.phase)),completed_at:n}],history_overflow:Lo(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${e.created_at}T00:00:00.000Z`})}function Vo(t){let e=rw(t,"Native portable migration transaction"),i=Object.keys(e).filter(r=>!Qg.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(e.schema!==on)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!ew.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!Zg.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!iw.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!tw.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:on,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:aw(e.createdAt,"Native portable migration transaction createdAt")}}function Iu(t){switch(Vo(t).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var ju="comet.native.archive-transaction.v4",$u="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",fw=new RegExp(`^portable-archive-(${$u})\\.json$`,"u"),hw=new RegExp(`^portable-migration-(${$u})\\.json$`,"u"),pw=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,mw=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vw=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),gw=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ww=new Set(["capability","operation","source","content"]),Ou=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Hu(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Du(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${i} fields are invalid`)}function yw(t,e){let i=`Native portable Archive spec_changes[${e}]`,r=Hu(t,i);if(Du(r,ww,i),typeof r.capability!="string"||!Ou.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 Nw(t){let e=Hu(t,"Native portable Archive transaction");if(Du(e,gw,"Native portable Archive transaction"),e.schema!==ju)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!pw.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Ou.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!mw.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!vw.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=e.spec_changes.map(yw);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(e.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:ju,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:i,created_at:e.created_at}}function sn(t){let e=fw.exec(t);if(e)return{kind:"archive",change:e[1]};let i=hw.exec(t);return i?{kind:"migration",change:i[1]}:null}function cn(t,e){let i=`${e.kind==="archive"?"portable-archive":"portable-migration"}-${e.change}.json`,r=sn(i);if(!r||r.kind!==e.kind||r.change!==e.change)throw new Error(`Invalid Native portable transaction change: ${e.change}`);return qo.join(t.transactionsDir,i)}async function Wo(t,e){let i=sn(e);if(!i)return null;let r=await M({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=qo.join(t.transactionsDir,e);if(i.kind==="archive"){let s=Nw(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=Vo(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 Bu(t,e){let i=cn(t,e);try{return await Wo(t,qo.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function Lu(t){return t.kind==="archive"||t.journal.status!=="committed"}import Ae from"path";import{TextDecoder as Cw}from"util";import{createHash as bw}from"node:crypto";import{constants as ln,promises as le}from"node:fs";import ue from"node:path";function dn(t,e){let i=ue.relative(t,e);return i===""||!ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ue.sep}`)}function kw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Sw(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ew(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function un(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function zo(t,e){let i=await le.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await le.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Pw(t,e,i){let r=ue.resolve(t),n=ue.resolve(e);if(!dn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await zo(r,i)],o=r;for(let s of ue.relative(r,n).split(ue.sep).filter(Boolean)){await nt(a,i),o=ue.join(o,s);let c=await zo(o,i);if(!dn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await nt(a,i),a}async function nt(t,e){for(let i of t){let r=await le.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Sw(i,r)||await le.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function xw(t,e,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Ct(t){let e=kw(t.maxBytes),i=ue.resolve(t.file),r=await Pw(t.root,ue.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(f=>zo(ue.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await nt(r,t.label);let a=await le.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Ew(a),s=await le.realpath(i);if(!dn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(f=>dn(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ln.O_RDONLY:ln.O_RDONLY|ln.O_NOFOLLOW|ln.O_NONBLOCK,l=await le.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[d,u]=await Promise.all([le.lstat(i),le.realpath(i)]);if(await nt(r,t.label),await nt(n,t.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!un(o,f)||!un(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await xw(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),le.lstat(i),le.realpath(i)]);if(await nt(r,t.label),await nt(n,t.label),!h.isFile()||h.isSymbolicLink()||m!==s||!un(o,v)||!un(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:bw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Aw=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),_w=new Set(["id","type","source","target","staged","backup"]),Tw=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Iw=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Vu=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var jw=256*1024,QS=1024*1024,ZS=16*1024;var eE=64*1024*1024;var $w=new Cw("utf-8",{fatal:!0});function hn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function pn(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function qu(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Jo(t,e){if(typeof t!="string"||t.length===0||Ae.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function fn(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Mu(t,e){if(Jo(t,e),t.includes("\\")||t!==Ae.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function Ow(t,e){let i=hn(t,`transaction operations[${e}]`);if(pn(i,_w,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Jo(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Jo(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 Wu(t){let e=hn(t,"Native Archive transaction journal");if(pn(e,Tw,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Vu.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!qu(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fn(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=hn(s,`Archive transaction operations[${c}]`);if(pn(l,Iw,`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`);Mu(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Mu(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&fn(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(fn(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`);fn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function Hw(t){let e=hn(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Wu(e);if(pn(e,Aw,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Vu.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Ae.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Ae.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!qu(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(Ow),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function Dw(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Ae.join(t.transactionsDir,e)}function zu(t,e){let i=Dw(t,e);return{directory:i,journal:Ae.join(i,"transaction.json"),events:Ae.join(i,"events.jsonl"),staged:Ae.join(i,"staged"),backups:Ae.join(i,"backups")}}async function Uo(t,e){let i=zu(t,e);return await Promise.all(Object.values(i).map(r=>T(t.runtimeDir,r))),i}async function Ko(t,e,i={}){let r=await Uo(t,e),n=await Ct({root:t.runtimeDir,file:r.journal,maxBytes:jw,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse($w.decode(n.bytes)),o=Hw(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Mw(t,e,i){let r;try{r=await Bw.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Ko(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(sn(n.name))try{let a=await Wo(t,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Lu(a))return!0}catch{return!0}return!1}async function Fw(t,e){let i=Date.now()+5e3,r=Lw.join(t.locksDir,"root-move.lock");for(;;)try{return await Xr(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Eu(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 ee(t,e,i,r){let n=await Fw(t,e);try{if(await Kr(t.projectRoot),await Mw(t,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Qr(n)}}import{createHash as Vw}from"crypto";function te(t){return Vw("sha256").update(t).digest("hex")}var bE={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var kE=8*1024*1024;var SE=64*1024,EE=64*1024;var PE={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},xE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var RE=(1n<<256n)-1n;var Kw=jt(wt(),1);var qE=4*1024*1024;var Yw=null;function Xw(t,e){let i=t;for(let r of e)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Ju(t,e){return(...i)=>{let r=Yw;if(r===null)return e(...i);let n=Xw(`async:${t}`,i),a=r.entries.get(n);if(a)return a.value;let o=e(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var UE=Ju("hookWritePolicy",async t=>(await No(t))?.hook??{allow_paths:[]});var qP=256*1024;var ix={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 At from"node:path";var Ei=/^[a-f0-9]{64}$/u,Uu=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ey=16*1024,wx=process.platform;function ty(t,e){let i=At.relative(t,e);return At.isAbsolute(i)||i===".."||i.startsWith(`..${At.sep}`)?null:i.replaceAll("\\","/")||"."}function Ku(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Yu(t,e){if(t.length===0||Ku(t)||t.includes("\\")||At.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=At.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function iy(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function Yo(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Ku(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function ry(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Yo(t.changeBranch,"Native workspace change branch"),Yo(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function ny(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(e).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!Uu.test(e.baseCommit)||typeof e.targetCommit!="string"||!Uu.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Yo(e.targetBranch,"Native workspace Git target branch")}function ay(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Ei.test(String(e.projectRootId))||!Ei.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");iy(e.capturedAt),Yu(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ei.test(String(e.projectRootPathId))||a&&!Ei.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Ei.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&ny(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(ry(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function oy(t,e){return At.join(pe(t,e),"workspace.json")}function sy(t,e){let i=oy(t,e),r=me(t,i),n=ty(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Yu(n,"Native workspace file ref")}}async function cy(t,e){try{let i=sy(t,e),r=await M({root:i.root,ref:i.ref,maxBytes:ey});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pi(t,e){let i=await cy(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ay(i),i)}var Zu=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],uy=new Set(Zu),ed=new Set([...Zu,"minimum_runtime_version","revision"]),dy=new Set([...ed,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),fy=new Set(["capability","operation","source","base_hash"]),hy=new Set(["shape","build","verify","archive"]),py=new Set(["implicit","confirmed"]),my=new Set(["pending","pass","fail"]),at="comet-state.yaml",Qo=/^[a-f0-9]{64}$/u,td=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vy=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Zo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Tt=class extends Error{constructor(i,r){super(i!==Ce||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"},mn=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"},xi=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"},vn=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"},qx=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(` +`);function Ci(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function id(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ts(t){if(!td.test(t))throw new Error(`Invalid Native change name: ${t}`)}function gy(t){if(!td.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function rd(t,e){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function wy(t,e){let i=Ci(t,`spec_changes[${e}]`);if(id(i,fy,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(gy(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"&&rd(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"||!Qo.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"||!Qo.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 yy(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function is(t,e){if(id(t,e,at),typeof t.name!="string")throw new Error("Native change name is required");if(ts(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!hy.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!py.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(wy),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof t.verification_result!="string"||!my.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&rd(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!yy(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function bi(t){let e=Ci(t,at);if(e.schema!==we)throw new Error(`Expected ${we}`);return{schema:we,...is(e,uy)}}function Ri(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Xo(t,e,i){if(t===null)return null;let r=typeof t=="string"?vy.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/.json relative to the Native change`);return t}function Ny(t){if(t==null)return null;if(typeof t!="string"||!Qo.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function by(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function ki(t){let e=Ci(t,at);if(e.schema!==ge)throw new Error(`Expected ${ge}`);if(Ri(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ge} minimum_runtime_version must be 2`);return{schema:ge,minimum_runtime_version:2,revision:Ri(e.revision,"Native v2 revision"),...is(e,ed)}}function Si(t){let e=Ci(t,at);if(e.schema!==Ce){if(e.schema===we||e.schema===ge){let o=e.schema===we?bi(e):ki(e);throw new Zo(o.name,o.schema)}throw new Tt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Ri(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Tt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Ri(e.revision,"Native revision"),n=is(e,dy),a=Ny(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ce,minimum_runtime_version:3,revision:r,verification_protocol:by(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xo(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xo(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xo(e.partial_allowance,"Native partial_allowance","allowances")}}function ky(t){let e=Ci(t,at);if(e.schema===we){let n=bi(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ce}`}}if(e.schema===ge){let n=ki(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ce}`}}if(e.schema!==Ce){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Tt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Ri(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Tt(e.schema,i).message};let r=Si(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function ye(t,e){ts(e);let i=_t.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}var Sy=256*1024;async function Ey(t,e=_t.dirname(t)){let i=_t.relative(e,t).split(_t.sep).join("/"),r=await M({root:e,ref:i,maxBytes:Sy}),n=(0,es.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function nd(t,e){let i=_t.join(ye(t,e),at);await T(t.nativeRoot,i);let r=ky(await Ey(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return r}import{promises as sd}from"node:fs";import Sn from"node:path";var xy=jt(wt(),1);var zx=8*1024*1024;var tR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as Iy}from"node:fs";import _i from"node:path";function gn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function wn(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ne(t,e,i=!1){if(typeof t!="string"||!i&&t.length===0)throw new Error(`${e} must be ${i?"a string":"a non-empty string"}`);return t}function ad(t,e){return t===null?null:Ne(t,e)}function Nn(t,e,i=0){if(!Number.isSafeInteger(t)||tNe(l,`${i}.argv[${f}]`,!0)),a=yn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=rs(r.startedAt,`${i}.startedAt`),s=rs(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=Nn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ne(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),operationId:Ne(r.operationId,`${i}.operationId`),status:a,repeatable:$y(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Nn(r.executionCount,`${i}.executionCount`),argv:n,cwd:ns(r.cwd,`${i}.cwd`),exitCode:jy(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ne(r.log,`${i}.log`)}}function od(t){let e="Native local execution state",i=gn(t,e);if(wn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),i.schema!==Ni)throw new Error(`Native local execution schema must be ${Ni}`);let r=gn(i.workspace,"Native local workspace");wn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=gn(i.execution,"Native local execution");wn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=rs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ne(o.operationId,"Native local execution.operationId"),stage:yn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:yn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ad(o.executionId,"Native local execution.executionId"),status:yn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Nn(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(Oy);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:Ni,change:Ne(i.change,"Native local change"),basedOnStateVersion:Nn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:ns(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ns(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ad(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function bn(t){return od({schema:Ni,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:_i.resolve(t.projectRoot),worktreeRoot:_i.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function kn(t,e,i={}){let r=od(e);await Iy.mkdir(_i.dirname(t),{recursive:!0}),await Y(t,r,i)}var cd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hy="comet-state.yaml",Dy="state.json";function ld(t,e){if(!cd.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=Sn.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}function ze(t,e){return Sn.join(ld(t,e),Hy)}function as(t,e){return Sn.join(tt(t,e),Dy)}async function Ti(t,e){try{let i=await sd.readFile(ze(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function By(t){return ke(t).currentBranch}async function ud(t,e){return Re(ze(t,e))}async function Ly(t){let e=await _u({file:ze(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let i=Sn.join(ld(t.paths,e.name),"verification.md");await T(t.paths.nativeRoot,i),await sd.rm(i,{force:!0})}return e}async function dd(t){if(!cd.test(t.capability))throw new Error(`Invalid Native capability: ${t.capability}`);return ee(t.paths,`remove portable spec ${t.capability}`,async()=>{let e=await ud(t.paths,t.name);if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i=e.spec_changes.filter(({capability:a})=>a!==t.capability),r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:[...i,{capability:t.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await Ly({paths:t.paths,previous:e,next:r});return await kn(as(t.paths,e.name),bn({portableState:n,projectRoot:t.paths.projectRoot,branch:By(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}var fd=["evidence.md","repair.md","archive.md","checkpoint.md"],Vy="verification.md";async function qy(t,e){let i=await Bu(t,{kind:"migration",change:e});return i?.kind==="migration"?i.journal:null}async function hd(t,e){await Ii.mkdir(t.transactionsDir,{recursive:!0}),await Y(cn(t,{kind:"migration",change:e.change}),e,{containedRoot:t.runtimeDir})}async function pd(t,e,i={}){let r=i.removeVerificationReport===!1?fd:[...fd,Vy];await Promise.all([Ii.rm(tt(t,e),{recursive:!0,force:!0}),Ii.rm(Po(t,e),{recursive:!0,force:!0}),...r.map(n=>Ii.rm(Fy.join(ye(t,e),n),{force:!0}))])}async function md(t,e){await kn(as(t,e.name),bn({portableState:e,projectRoot:t.projectRoot}),{containedRoot:t.runtimeDir})}async function vd(t,e){try{let i=await Pi(t,e);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function gd(t,e){if(e.isolation==="current"&&e.change_branch===null)return;let i=ke(t.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==e.change_branch)throw new Error(`Native legacy migration expected branch ${e.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function Wy(t){let e=ye(t.paths,t.state.name),i=await M({root:e,ref:t.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of t.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await M({root:e,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Bo({briefMarkdown:i.text,specs:r})}catch(n){if(t.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function wd(t,e){let i=await nd(t,e);if(!i.state)throw new Error(`Native legacy change ${e} is unreadable`);return i.state}async function yd(t){return ee(t.paths,`migrate ${t.name} to portable Native`,async()=>{let e=await qy(t.paths,t.name),i=await Ti(t.paths,t.name)?await Re(ze(t.paths,t.name)):null;if(!e&&i)return await pd(t.paths,t.name,{removeVerificationReport:!1}),await md(t.paths,i),i;let r=null,n=null;for(e||(r=await wd(t.paths,t.name),n=await vd(t.paths,t.name),gd(t.paths,n),e={schema:on,id:My(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(t.now??new Date).toISOString()},await hd(t.paths,e));;){let a=Iu(e);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await wd(t.paths,t.name),n??=await vd(t.paths,t.name),gd(t.paths,n),i=Tu({state:r,acceptance:await Wy({paths:t.paths,state:r}),workspace:n,migratedAt:t.now}),await nn(ze(t.paths,t.name),i,{containedRoot:t.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await pd(t.paths,t.name):a.action==="commit-transaction"&&(i??=await Re(ze(t.paths,t.name)),await md(t.paths,i)),e={...e,status:a.nextStatus},await hd(t.paths,e)}return await Ii.rm(cn(t.paths,{kind:"migration",change:t.name}),{force:!0}),i??Re(ze(t.paths,t.name))},{allowedPortableTransaction:{kind:"migration",change:t.name}})}import cs from"path";var Jy=["Outcome","Scope","Non-goals","Acceptance examples"],ZC=[...Jy,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var Gy=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 Nd=1024*1024;var kd="scoped-text-safety",Uy=1,Ky=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Yy="comet.native.checker-policy.v1";var mA=K(Yy,{policy:kd,version:Uy,limits:Ky,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Xy=["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"],vA=new Set(Xy);var eN=Nd,jA=3*eN;var Sd={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:[]},iN=te("comet-native-runtime:v3:scope-reopen"),o_=[{skillVersion:"3",skillHash:te("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:te("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:te("comet-native-runtime:v1")}];var Pd=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],M_=new Set(Pd),lN=new Set([...Pd,"minimum_runtime_version","revision"]),F_=new Set([...lN,"operation"]),V_=512*1024,uN=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),q_=new Set([...uN,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var G_={maxAcceptanceCriteria:yi.maxCriteria};var Q_={maxSpecs:64,maxFileBytes:Di,maxTotalBytes:4*1024*1024};import{execFile as yN}from"node:child_process";import{promisify as NN}from"node:util";var cT={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var AT=512*1024;var ji=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var QT=64*1024;var ZT=3600*1e3;var eI=NN(yN);var En=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var LI={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var KI=16*1024*1024,YI=256*1024,XI=16*1024;var ij=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var aj=16*1024;var gj=16*1024;var s$=16*1024*1024,Pn=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"},xn=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 Rn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Cd=["--project-root Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ss=Object.freeze({"":{usage:"comet native [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 Move the configured artifact root.","new Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show Read formal artifacts and portable state.","status [] Discover stable boundaries and Runner actions.","select Select a change in its bound workspace.","next Confirm or recover a stable workflow boundary.","archive Preview and execute Archive plus workspace finish.","doctor [] Diagnose, migrate, or rebuild local execution state."],options:Cd,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 ] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--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 [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move 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 ",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 [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch ] [--target-branch ] [--worktree-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 current, branch, or worktree; defaults to current.","--change-branch Change branch; defaults to comet/.","--target-branch Local base branch; defaults to the current branch.","--worktree-path Worktree directory; defaults to .worktrees/."],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 ",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove ",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 ",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 [] [--cursor ] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor 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 ",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next --summary [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker] comet native next --runner-input `,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 Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--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.","--runner-input 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 "Implementation changed" --return-to-build','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 "]},archive:{usage:`comet native archive --dry-run [--finish merge|push|pull-request|keep] comet native archive [--confirmed] [--serial-first ]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first During execution only, confirm that this change archives before detected capability peers; the value must equal .","--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 [] [--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 os(t,e){return`${t}: ${e.map(i=>` ${i}`).join(` -`)}`}function PN(t){let e=t.filter(r=>r!=="--help");if(e.length===0)return"";let i=e.slice(0,2).join(" ");return ss[i]||e.length>1&&ss[e[0]]?.subcommands?i:e[0]}function xN(t=[]){let e=PN(t),i=ss[e];if(!i)throw new Error(`Unknown Native help topic: ${e}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",os("Commands",i.subcommands));let n=e===""?i.options:[...i.options??[],...Cd];return n&&n.length>0&&r.push("",os("Options",n)),r.push("",`Output: +`)}`}function xN(t){let e=t.filter(r=>r!=="--help");if(e.length===0)return"";let i=e.slice(0,2).join(" ");return ss[i]||e.length>1&&ss[e[0]]?.subcommands?i:e[0]}function RN(t=[]){let e=xN(t),i=ss[e];if(!i)throw new Error(`Unknown Native help topic: ${e}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",os("Commands",i.subcommands));let n=e===""?i.options:[...i.options??[],...Cd];return n&&n.length>0&&r.push("",os("Options",n)),r.push("",`Output: ${i.output}`),i.examples&&r.push("",os("Examples",i.examples)),e===""&&r.push("","Run `comet native --help` for command-specific details."),{topic:e,usage:`${r.join(` `)} -`}}var CN=xN().usage;var A$=10*1024*1024,be=class extends Error{};function Ad(t,e){let i=t.flatMap((r,n)=>r===e?[n]:[]);if(i.length>1)throw new be(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function _d(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new be(`${e} may only be provided once`);if(i.length===0)return;let r=i[0],n=t[r+1];if(n===void 0||n.startsWith("--"))throw new be(`${e} requires a value`);return t.splice(r,2),n}function Td(t){if(t.length>0)throw new be(`Unexpected argument: ${t[0]}`)}function Rn(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new be(`${e} is required`);return i}function Rd(t,e){let i=cs.normalize(t),r=cs.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function RN(t){let e=cs.resolve(t),i=ke(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return e;let r=ke(e);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Rd(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Rd(i.currentWorktreeRoot,r.currentWorktreeRoot)?e:i.currentWorktreeRoot}async function Id(t){return t?RN(t):Gr(process.cwd())}async function jd(t){let e=await fu({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function $d(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+` -`}}function Od(t,e){if(e instanceof be)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Pn)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof xn)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof mn)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof xi)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof Cn)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof vn)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof En)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof ji)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Hd(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+` -`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Dd(t,e){let i=Rn(t,"spec subcommand");if(i!=="remove")throw new be(`Unknown spec command: ${i}`);let r=Rn(t,"change name"),n=Rn(t,"capability");Td(t);let{paths:a}=await jd(e);await Ti(a,r)||await wd({paths:a,name:r});let o=await dd({paths:a,name:r,capability:n});return $d("spec remove",{...o,continuation:ds(o)},`Marked Native capability ${n} for removal in ${r} -`)}function AN(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+` -`}}async function Bd(t,e,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{Ad(n,"--json"),s=_d(n,"--project-root");let f=[...n,...a],d=await Id(s);c=await e(f,d)}catch(f){c=Od(t,f)}let l=o?AN(c):Hd(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` +`}}var CN=RN().usage;var _$=10*1024*1024,be=class extends Error{};function _d(t,e){let i=t.flatMap((r,n)=>r===e?[n]:[]);if(i.length>1)throw new be(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Td(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new be(`${e} may only be provided once`);if(i.length===0)return;let r=i[0],n=t[r+1];if(n===void 0||n.startsWith("--"))throw new be(`${e} requires a value`);return t.splice(r,2),n}function Id(t){if(t.length>0)throw new be(`Unexpected argument: ${t[0]}`)}function Cn(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new be(`${e} is required`);return i}function Ad(t,e){let i=cs.normalize(t),r=cs.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function AN(t){let e=cs.resolve(t),i=ke(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return e;let r=ke(e);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Ad(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Ad(i.currentWorktreeRoot,r.currentWorktreeRoot)?e:i.currentWorktreeRoot}async function jd(t){return t?AN(t):Gr(process.cwd())}async function $d(t){let e=await fu({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function Od(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+` +`}}function Hd(t,e){if(e instanceof be)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Pn)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof xn)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof mn)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof xi)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof Rn)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof vn)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof En)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof ji)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Dd(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+` +`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Bd(t,e){let i=Cn(t,"spec subcommand");if(i!=="remove")throw new be(`Unknown spec command: ${i}`);let r=Cn(t,"change name"),n=Cn(t,"capability");Id(t);let{paths:a}=await $d(e);await Ti(a,r)||await yd({paths:a,name:r});let o=await dd({paths:a,name:r,capability:n});return Od("spec remove",{...o,continuation:ds(o)},`Marked Native capability ${n} for removal in ${r} +`)}function _N(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+` +`}}async function Ld(t,e,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{_d(n,"--json"),s=Td(n,"--project-root");let f=[...n,...a],d=await jd(s);c=await e(f,d)}catch(f){c=Hd(t,f)}let l=o?_N(c):Dd(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(` `)?"":` -`)),l.exitCode}process.exitCode=await Bd("spec",Dd); +`)),l.exitCode}process.exitCode=await Ld("spec",Bd); diff --git a/domains/comet-native/native-portable-migration-runtime.ts b/domains/comet-native/native-portable-migration-runtime.ts index dd08a6343..723ca43e4 100644 --- a/domains/comet-native/native-portable-migration-runtime.ts +++ b/domains/comet-native/native-portable-migration-runtime.ts @@ -39,12 +39,13 @@ import { readNativeWorkspaceIdentity } from './native-workspace.js'; const LEGACY_PROJECTION_FILES = [ 'evidence.md', - 'verification.md', 'repair.md', 'archive.md', 'checkpoint.md', ] as const; +const LEGACY_VERIFICATION_REPORT = 'verification.md'; + async function exists(file: string): Promise { try { await fs.lstat(file); @@ -94,7 +95,12 @@ async function writeTransaction( async function cleanupLegacyMigrationArtifacts( paths: NativeProjectPaths, name: string, + options: { removeVerificationReport?: boolean } = {}, ): Promise { + const projectionFiles = + options.removeVerificationReport === false + ? LEGACY_PROJECTION_FILES + : [...LEGACY_PROJECTION_FILES, LEGACY_VERIFICATION_REPORT]; await Promise.all([ fs.rm(nativePreferredChangeRuntimeDir(paths, name), { recursive: true, @@ -104,7 +110,7 @@ async function cleanupLegacyMigrationArtifacts( recursive: true, force: true, }), - ...LEGACY_PROJECTION_FILES.map((file) => + ...projectionFiles.map((file) => fs.rm(path.join(nativeChangeDir(paths, name), file), { force: true }), ), ]); @@ -225,7 +231,9 @@ export async function migrateNativeLegacyChangeToPortable(options: { // The portable YAML is the durable migration boundary. If its journal was // lost after that write, finish the deterministic cleanup and recreate the // disposable local overlay instead of mistaking the migration for complete. - await cleanupLegacyMigrationArtifacts(options.paths, options.name); + await cleanupLegacyMigrationArtifacts(options.paths, options.name, { + removeVerificationReport: false, + }); await rebuildLocalExecution(options.paths, portable); return portable; } diff --git a/domains/comet-native/native-workspace-finish.ts b/domains/comet-native/native-workspace-finish.ts index aaa6979b7..1a82c8a5d 100644 --- a/domains/comet-native/native-workspace-finish.ts +++ b/domains/comet-native/native-workspace-finish.ts @@ -77,6 +77,27 @@ function pathCovered(candidate: string, allowed: readonly string[]): boolean { return allowed.some((entry) => candidate === entry || candidate.startsWith(`${entry}/`)); } +function gitPathList(output: string): string[] { + return output.split('\0').filter(Boolean); +} + +function listTrackedPaths(projectRoot: string, candidate: string): string[] { + return gitPathList(runGitCommand(projectRoot, ['ls-files', '-z', '--', candidate])); +} + +function listUntrackedNonIgnoredPaths(projectRoot: string, candidate: string): string[] { + return gitPathList( + runGitCommand(projectRoot, [ + 'ls-files', + '--others', + '--exclude-standard', + '-z', + '--', + candidate, + ]), + ); +} + function assertGitIdentity(projectRoot: string): void { try { if ( @@ -309,14 +330,23 @@ export async function finishArchivedNativeWorkspace(options: { `Native Archive produced or encountered paths outside the authorized finish scope: ${unexpected.slice(0, 20).join(', ')}${unexpected.length > 20 ? ', ...' : ''}`, ); } - const stageable: string[] = []; + const trackedCandidates: string[] = []; + const untrackedPaths = new Set(); for (const candidate of allowedPaths) { const absolute = path.resolve(options.paths.projectRoot, ...candidate.split('/')); - const tracked = runGitCommand(options.plan.changeRoot, ['ls-files', '--', candidate]) !== ''; - if ((await pathExists(absolute)) || tracked) stageable.push(candidate); + const tracked = listTrackedPaths(options.plan.changeRoot, candidate); + if (tracked.length > 0) trackedCandidates.push(candidate); + if (await pathExists(absolute)) { + for (const file of listUntrackedNonIgnoredPaths(options.plan.changeRoot, candidate)) { + untrackedPaths.add(file); + } + } + } + if (trackedCandidates.length > 0) { + runGitCommand(options.plan.changeRoot, ['add', '-u', '--', ...trackedCandidates]); } - if (stageable.length > 0) { - runGitCommand(options.plan.changeRoot, ['add', '-A', '--', ...stageable]); + if (untrackedPaths.size > 0) { + runGitCommand(options.plan.changeRoot, ['add', '--', ...untrackedPaths]); } const staged = runGitCommand(options.plan.changeRoot, [ 'diff', diff --git a/test/domains/comet-native/native-doctor-v4.test.ts b/test/domains/comet-native/native-doctor-v4.test.ts index 622514223..7cf71a180 100644 --- a/test/domains/comet-native/native-doctor-v4.test.ts +++ b/test/domains/comet-native/native-doctor-v4.test.ts @@ -89,6 +89,27 @@ describe('Native portable Doctor', () => { }); }); + it('keeps a generated portable verification report out of migration findings', async () => { + const name = 'verified-portable'; + await createPortable(name); + const report = path.join(paths.changesDir, name, 'verification.md'); + await fs.writeFile(report, '# Verification\n\nPassed\n'); + + await expect(nativeDoctorCommand([name], projectRoot)).resolves.toMatchObject({ + exitCode: 0, + data: { healthy: true, workflow: 'native-portable', change: name }, + }); + await expect(nativeDoctorCommand([name, '--repair'], projectRoot)).resolves.toMatchObject({ + exitCode: 0, + data: { healthy: true, repaired: true }, + }); + await expect(fs.stat(report)).resolves.toBeTruthy(); + await expect(nativeDoctorCommand([], projectRoot)).resolves.toMatchObject({ + exitCode: 0, + data: { healthy: true, workflow: 'native-portable', findings: [] }, + }); + }); + it('merges portable statuses with legacy migration findings in a mixed project', async () => { await createPortable('portable-change'); await createLegacy('legacy-change'); diff --git a/test/domains/comet-native/native-portable-migration-runtime.test.ts b/test/domains/comet-native/native-portable-migration-runtime.test.ts index deedd2c7c..23b7b4891 100644 --- a/test/domains/comet-native/native-portable-migration-runtime.test.ts +++ b/test/domains/comet-native/native-portable-migration-runtime.test.ts @@ -14,7 +14,10 @@ import { nativeProjectPaths, } from '../../../domains/comet-native/native-paths.js'; import { withNativeMutationLock } from '../../../domains/comet-native/native-mutation-lock.js'; -import { migrateNativeLegacyChangeToPortable } from '../../../domains/comet-native/native-portable-migration-runtime.js'; +import { + hasIncompleteNativePortableMigration, + migrateNativeLegacyChangeToPortable, +} from '../../../domains/comet-native/native-portable-migration-runtime.js'; import { createNativePortableChange } from '../../../domains/comet-native/native-portable-runtime.js'; import type { NativeProjectPaths } from '../../../domains/comet-native/native-types.js'; import { writeNativeWorkspaceIdentity } from '../../../domains/comet-native/native-workspace.js'; @@ -70,6 +73,28 @@ describe('Native portable migration Runtime', () => { return paths; } + async function portableChange(): Promise { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-native-portable-report-')); + roots.push(root); + await writeProjectConfig(root, defaultProjectConfig('docs', 'en')); + const paths = await nativeProjectPaths(root, 'docs'); + await ensureNativeDirectories(paths); + await createNativePortableChange({ paths, name: 'portable-change', language: 'en' }); + return paths; + } + + it('does not treat a portable verification report as incomplete migration', async () => { + const paths = await portableChange(); + await fs.writeFile( + path.join(paths.changesDir, 'portable-change', 'verification.md'), + '# Verification\n\nPassed\n', + ); + + await expect(hasIncompleteNativePortableMigration(paths, 'portable-change')).resolves.toBe( + false, + ); + }); + it('commits portable YAML before cleaning legacy Runtime and is idempotent', async () => { const paths = await legacyChange(); const migrated = await migrateNativeLegacyChangeToPortable({ paths, name: 'legacy-change' }); diff --git a/test/domains/comet-native/native-workspace-finish-git-ignore.test.ts b/test/domains/comet-native/native-workspace-finish-git-ignore.test.ts new file mode 100644 index 000000000..a578acccc --- /dev/null +++ b/test/domains/comet-native/native-workspace-finish-git-ignore.test.ts @@ -0,0 +1,126 @@ +import { execFileSync } from 'node:child_process'; +import { promises as fs } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { + ensureNativeDirectories, + nativeProjectPaths, +} from '../../../domains/comet-native/native-paths.js'; +import { + finishArchivedNativeWorkspace, + type NativeWorkspaceFinishPlan, +} from '../../../domains/comet-native/native-workspace-finish.js'; +import type { NativePortableState } from '../../../domains/comet-native/native-portable-types.js'; + +describe('Native workspace finish Git ignore behavior', () => { + let projectRoot: string | undefined; + + afterEach(async () => { + if (projectRoot) await fs.rm(projectRoot, { recursive: true, force: true }); + projectRoot = undefined; + }); + + it('skips ignored untracked archive artifacts instead of blocking finish', async () => { + projectRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-native-finish-ignore-')); + execFileSync('git', ['init'], { cwd: projectRoot, stdio: 'ignore' }); + execFileSync('git', ['config', 'user.email', 'native@example.test'], { cwd: projectRoot }); + execFileSync('git', ['config', 'user.name', 'Native Test'], { cwd: projectRoot }); + await fs.writeFile(path.join(projectRoot, '.gitignore'), '/docs/\n'); + await fs.writeFile(path.join(projectRoot, 'README.md'), 'baseline\n'); + execFileSync('git', ['add', '.gitignore', 'README.md'], { + cwd: projectRoot, + stdio: 'ignore', + }); + execFileSync('git', ['commit', '-m', 'baseline'], { cwd: projectRoot, stdio: 'ignore' }); + + const paths = await nativeProjectPaths(projectRoot, 'docs'); + await ensureNativeDirectories(paths); + const archiveDir = path.join(paths.archiveDir, 'ignored-change'); + await fs.mkdir(archiveDir, { recursive: true }); + await fs.writeFile(path.join(archiveDir, 'verification.md'), '# Verification\n'); + + const plan: NativeWorkspaceFinishPlan = { + finish: 'keep', + changeRoot: projectRoot, + primaryRoot: projectRoot, + changeBranch: 'comet/ignored-change', + targetBranch: 'main', + targetRoot: projectRoot, + remote: null, + isolation: 'branch', + }; + + await expect( + finishArchivedNativeWorkspace({ + paths, + state: { name: 'ignored-change', spec_changes: [] } as NativePortableState, + name: 'ignored-change', + archiveDir, + transactionId: 'tx-ignore', + plan, + }), + ).resolves.toMatchObject({ status: 'kept', pushed: false, merged: false }); + }); + + it('stages tracked artifacts even when their directory is ignored', async () => { + projectRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'comet-native-finish-tracked-')); + execFileSync('git', ['init'], { cwd: projectRoot, stdio: 'ignore' }); + execFileSync('git', ['config', 'user.email', 'native@example.test'], { cwd: projectRoot }); + execFileSync('git', ['config', 'user.name', 'Native Test'], { cwd: projectRoot }); + await fs.writeFile(path.join(projectRoot, '.gitignore'), '/docs/\n'); + await fs.writeFile(path.join(projectRoot, 'README.md'), 'baseline\n'); + const trackedArtifact = path.join( + projectRoot, + 'docs', + 'comet', + 'archive', + 'tracked-change', + 'verification.md', + ); + await fs.mkdir(path.dirname(trackedArtifact), { recursive: true }); + await fs.writeFile(trackedArtifact, 'before\n'); + execFileSync('git', ['add', '.gitignore', 'README.md'], { + cwd: projectRoot, + stdio: 'ignore', + }); + execFileSync('git', ['add', '-f', '--', 'docs/comet/archive/tracked-change/verification.md'], { + cwd: projectRoot, + stdio: 'ignore', + }); + execFileSync('git', ['commit', '-m', 'baseline'], { cwd: projectRoot, stdio: 'ignore' }); + await fs.writeFile(trackedArtifact, 'after\n'); + + const paths = await nativeProjectPaths(projectRoot, 'docs'); + await ensureNativeDirectories(paths); + const archiveDir = path.join(paths.archiveDir, 'tracked-change'); + const plan: NativeWorkspaceFinishPlan = { + finish: 'keep', + changeRoot: projectRoot, + primaryRoot: projectRoot, + changeBranch: 'comet/tracked-change', + targetBranch: 'main', + targetRoot: projectRoot, + remote: null, + isolation: 'branch', + }; + + await expect( + finishArchivedNativeWorkspace({ + paths, + state: { name: 'tracked-change', spec_changes: [] } as NativePortableState, + name: 'tracked-change', + archiveDir, + transactionId: 'tx-tracked', + plan, + }), + ).resolves.toMatchObject({ status: 'kept', pushed: false, merged: false }); + expect( + execFileSync('git', ['show', '--format=', '--name-only', 'HEAD'], { + cwd: projectRoot, + encoding: 'utf8', + }), + ).toContain('docs/comet/archive/tracked-change/verification.md'); + }); +}); From 12be966a5171391a20c54ec6a93d3e9ebcacbdc2 Mon Sep 17 00:00:00 2001 From: benym Date: Sun, 16 Aug 2026 17:04:20 +0800 Subject: [PATCH 2/4] docs: rewrite beta19 changelog --- CHANGELOG.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cc1fb03e..3cb79c590 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,17 +2,20 @@ All notable changes to @rpamis/comet will be documented in this file. -## What's Changed [0.4.0-beta.19] - 2026-08-15 +## What's Changed [0.4.0-beta.19] - 2026-08-16 + +### Added + +- **CodeBuddy rules support**: Comet now installs and refreshes Markdown workflow rules in CodeBuddy's `.codebuddy/rules/` directory. +- **Fork pull request guidance**: First-time contributors opening pull requests from forks now receive the repository guidance comment through a trusted workflow. +- **Pull request template validation**: Pull requests now receive an actionable comment and a failing check when required template sections or items are missing, or when checklist items are incomplete. ### Changed - **Dashboard artifact previews**: Fullscreen previews now close with Escape, keep long tables horizontally scrollable, preserve readable table headers, and use a larger directory navigation scale. -- **Hook allow-path documentation**: The website now explains how to configure project-relative `hook.allow_paths` directories for guarded workflow phases. ### Fixed -- **Fork pull request greetings**: First-time contributors now receive the repository guidance comment when opening a pull request from a fork, without weakening the read-only permissions of workflows that execute contributor code. -- **Pull request template checks**: Pull requests now receive an actionable comment and a failing check when items from the repository template are missing or its checklist is incomplete. - **Native Archive**: Archive now respects Git ignore rules when staging workspace artifacts and keeps valid portable verification reports from being treated as incomplete migrations. ## What's Changed [0.4.0-beta.18] - 2026-08-13 From 827616e7b1295113022ffe7eacb17a0c47be4757 Mon Sep 17 00:00:00 2001 From: benym Date: Sun, 16 Aug 2026 17:17:36 +0800 Subject: [PATCH 3/4] ci: automate issue triage and PR scopes --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 + .github/ISSUE_TEMPLATE/feature_request.yml | 2 + .github/ISSUE_TEMPLATE/question.yml | 2 + .github/workflows/issue-triage.yml | 103 +++++++++++++++++++++ .github/workflows/pr-title-lint.yml | 15 +++ CHANGELOG.md | 2 + test/repository/ci-workflows.test.ts | 51 ++++++++++ 7 files changed, 177 insertions(+) create mode 100644 .github/workflows/issue-triage.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 8750ac6b3..832a9d13c 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -17,8 +17,10 @@ body: description: Which part of Comet is affected? options: - CLI command / user interaction (`app/`) + - Native workflow runtime (`domains/comet-native`) - Bundle authoring (`domains/bundle`) - Classic workflow runtime (`domains/comet-classic`, `assets/skills/comet/scripts/`) + - Shared Hook / Hook Router (`domains/comet-entry`) - Dashboard (`domains/dashboard`) - Engine (`domains/engine`) - Eval (`domains/eval`) diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 950e585a8..8dc6847d4 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -32,8 +32,10 @@ body: description: Where would this feature live? options: - CLI command / user interaction (`app/`) + - Native workflow runtime (`domains/comet-native`) - Bundle authoring (`domains/bundle`) - Classic workflow runtime (`domains/comet-classic`, `assets/skills/comet/scripts/`) + - Shared Hook / Hook Router (`domains/comet-entry`) - Dashboard (`domains/dashboard`) - Engine (`domains/engine`) - Eval (`domains/eval`) diff --git a/.github/ISSUE_TEMPLATE/question.yml b/.github/ISSUE_TEMPLATE/question.yml index 2921cf263..c2e4e35a8 100644 --- a/.github/ISSUE_TEMPLATE/question.yml +++ b/.github/ISSUE_TEMPLATE/question.yml @@ -17,8 +17,10 @@ body: description: Which part of Comet is your question about? options: - CLI command / user interaction (`app/`) + - Native workflow runtime (`domains/comet-native`) - Bundle authoring (`domains/bundle`) - Classic workflow runtime (`domains/comet-classic`, `assets/skills/comet/scripts/`) + - Shared Hook / Hook Router (`domains/comet-entry`) - Dashboard (`domains/dashboard`) - Engine (`domains/engine`) - Eval (`domains/eval`) diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml new file mode 100644 index 000000000..769d67374 --- /dev/null +++ b/.github/workflows/issue-triage.yml @@ -0,0 +1,103 @@ +name: Issue Triage + +on: + issues: + types: [opened, edited] + +permissions: + issues: write + +jobs: + triage: + name: Apply issue triage labels + runs-on: ubuntu-latest + steps: + - uses: actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71 # v9.0.0 + with: + script: | + const issue = context.payload.issue; + if (!issue) { + core.setFailed('Issue payload is missing.'); + return; + } + + const sections = new Map(); + let currentHeading; + for (const line of (issue.body ?? '').replace(/\r\n/g, '\n').split('\n')) { + const heading = line.match(/^###\s+(.+?)\s*$/); + if (heading) { + currentHeading = heading[1].trim().replace(/^[^A-Za-z0-9]+/, ''); + sections.set(currentHeading, []); + continue; + } + if (currentHeading) sections.get(currentHeading).push(line); + } + + const selectedArea = ['Affected area', 'Primary area', 'Topic'] + .flatMap((heading) => sections.get(heading) ?? []) + .join(' ') + .replace(/[`*_]/g, '') + .replace(/\s+/g, ' ') + .trim(); + + const areaRules = [ + { label: 'area:native', pattern: /Native workflow runtime/i }, + { label: 'area:classic', pattern: /Classic workflow runtime/i }, + { label: 'area:hook', pattern: /Shared Hook|Hook Router/i }, + { label: 'area:cli', pattern: /CLI command|user interaction/i }, + { label: 'area:dashboard', pattern: /Dashboard/i }, + { label: 'area:platform', pattern: /Platform adapter|installer/i }, + { label: 'area:skills', pattern: /Skill domain|Bundled skills|assets/i }, + { label: 'area:workflow', pattern: /Workflow contract/i }, + { label: 'area:core', pattern: /Bundle authoring|Engine|Factory|Integrations/i }, + { label: 'area:eval', pattern: /Eval/i }, + { label: 'area:docs', pattern: /Documentation/i }, + { + label: 'area:ci', + pattern: /Repository automation|CI \/ release \/ architecture checks/i, + }, + { label: 'area:repo', pattern: /Tests \/ repository architecture/i }, + ]; + const targetArea = areaRules.find(({ pattern }) => pattern.test(selectedArea))?.label; + const managedAreaLabels = new Set(areaRules.map(({ label }) => label)); + + const labelsResponse = await github.rest.issues.listLabelsOnIssue({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issue.number, + per_page: 100, + }); + const currentLabels = labelsResponse.data.map(({ name }) => name); + const currentManagedAreas = currentLabels.filter((label) => + managedAreaLabels.has(label), + ); + + for (const label of currentManagedAreas) { + if (label !== targetArea) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issue.number, + name: label, + }); + } + } + + const labelsToAdd = []; + if (targetArea && !currentLabels.includes(targetArea)) labelsToAdd.push(targetArea); + if (context.payload.action === 'opened' && !currentLabels.includes('needs-triage')) { + labelsToAdd.push('needs-triage'); + } + if (labelsToAdd.length > 0) { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issue.number, + labels: labelsToAdd, + }); + } + + core.info( + `Issue #${issue.number}: selected area=${selectedArea || 'none'}, ` + + `applied area=${targetArea || 'none'}.`, + ); diff --git a/.github/workflows/pr-title-lint.yml b/.github/workflows/pr-title-lint.yml index 0e8588cb6..e31fb6342 100644 --- a/.github/workflows/pr-title-lint.yml +++ b/.github/workflows/pr-title-lint.yml @@ -32,6 +32,7 @@ jobs: cli commands core + app skills assets scripts @@ -39,6 +40,20 @@ jobs: ci deps release + native + classic + hook + dashboard + platform + workflow + bundle + engine + factory + integrations + eval + repo + tests + website requireScope: false subjectPattern: ^.{1,72}$ subjectPatternError: | diff --git a/CHANGELOG.md b/CHANGELOG.md index a5bce216e..eca73cbc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,10 +10,12 @@ All notable changes to @rpamis/comet will be documented in this file. - **On-demand change review**: The new `/comet-review` Skill reviews the current Native or Classic change against its implementation diff and existing evidence, reports prioritized correctness, security, edge-case, and coverage findings, and remains read-only without advancing or replacing Verify. - **Fork pull request guidance**: First-time contributors opening pull requests from forks now receive the repository guidance comment through a trusted workflow. - **Pull request template validation**: Pull requests now receive an actionable comment and a failing check when required template sections or items are missing, or when checklist items are incomplete. +- **Issue triage labels**: New issues are automatically marked for triage and assigned a repository area label from their structured issue form selection. ### Changed - **Dashboard artifact previews**: Fullscreen previews now close with Escape, keep long tables horizontally scrollable, preserve readable table headers, and use a larger directory navigation scale. +- **Pull request title scopes**: Conventional PR titles now support Native, Classic, Hook, Dashboard, Platform, Workflow, Eval, and other repository areas, including titles such as `feat(native): ...`. ### Fixed diff --git a/test/repository/ci-workflows.test.ts b/test/repository/ci-workflows.test.ts index 73f2e5ea0..d0ceb2b86 100644 --- a/test/repository/ci-workflows.test.ts +++ b/test/repository/ci-workflows.test.ts @@ -101,6 +101,57 @@ describe('CI workflows', () => { expect(workflow).toContain('types: [opened, edited, reopened, ready_for_review]'); expect(workflow).toContain('requireScope: false'); expect(workflow).toContain('subjectPattern: ^.{1,72}$'); + for (const scope of [ + 'app', + 'native', + 'classic', + 'hook', + 'dashboard', + 'platform', + 'workflow', + 'bundle', + 'engine', + 'factory', + 'integrations', + 'eval', + 'repo', + 'tests', + 'website', + ]) { + expect(workflow).toMatch(new RegExp(`^ ${scope}$`, 'm')); + } + }); + + it('triages issue form areas with a trusted, least-privilege workflow', async () => { + const workflow = await readWorkflow('issue-triage.yml'); + const issueForms = await Promise.all( + ['bug_report.yml', 'feature_request.yml', 'question.yml'].map((name) => + fs.readFile(`.github/ISSUE_TEMPLATE/${name}`, 'utf8'), + ), + ); + + expect(workflow).toMatch(/^ issues:\s*$/m); + expect(workflow).toContain('types: [opened, edited]'); + expect(workflow).toContain('issues: write'); + expect(workflow).toContain('actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71'); + expect(workflow).toContain('needs-triage'); + expect(workflow).toContain("replace(/^[^A-Za-z0-9]+/, '')"); + expect(workflow).toContain('area:native'); + expect(workflow).toContain('area:hook'); + expect(workflow).toContain('area:workflow'); + expect(workflow).toContain('area:repo'); + expect(workflow).not.toContain('actions/checkout'); + + for (const form of issueForms) { + expect(form).toContain('Native workflow runtime'); + expect(form).toContain('Shared Hook / Hook Router'); + } + }); + + it('keeps the maintenance task template backed by an existing task label', async () => { + const template = await fs.readFile('.github/ISSUE_TEMPLATE/task.yml', 'utf8'); + + expect(template).toContain("labels: ['task']"); }); it('greets first-time contributors from the trusted base workflow', async () => { From 2dc983f716b576f4712476d50f442e72248c3ca1 Mon Sep 17 00:00:00 2001 From: benym Date: Sun, 16 Aug 2026 18:16:20 +0800 Subject: [PATCH 4/4] fix: stabilize Windows eval packaging tests --- .npmignore | 2 ++ CHANGELOG.md | 1 + eval/.npmignore | 24 +++++++++++++ eval/langfuse/.npmignore | 12 +++++++ eval/langsmith/.npmignore | 12 +++++++ eval/local/.npmignore | 23 ++++++++++++ package.json | 35 ++++++------------- .../eval-static-collect.integration.test.ts | 9 ++++- .../comet-classic/comet-scripts.test.ts | 3 ++ test/scripts/prepublish-check.test.ts | 27 ++++++++++++++ 10 files changed, 122 insertions(+), 26 deletions(-) create mode 100644 eval/.npmignore create mode 100644 eval/langfuse/.npmignore create mode 100644 eval/langsmith/.npmignore create mode 100644 eval/local/.npmignore diff --git a/.npmignore b/.npmignore index a56bbfd23..ba06aca75 100644 --- a/.npmignore +++ b/.npmignore @@ -44,6 +44,8 @@ __tests__/ eval/**/.pytest*/ eval/**/.pytest-*/ eval/**/.pytest_*/ +eval/.pytest-basetemp-*/ +eval/.pytest-tmp-*/ eval/**/.tmp/ eval/**/.cache/ eval/**/.ruff_cache/ diff --git a/CHANGELOG.md b/CHANGELOG.md index eca73cbc6..12742e797 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ All notable changes to @rpamis/comet will be documented in this file. ### Fixed - **Native Archive**: Archive now respects Git ignore rules when staging workspace artifacts and keeps valid portable verification reports from being treated as incomplete migrations. +- **Windows Eval packaging**: Packaging no longer traverses ignored pytest and Eval runtime artifacts before applying the package boundary, so stale Windows test directories cannot make `pnpm pack` fail with `EPERM`. ## What's Changed [0.4.0-beta.18] - 2026-08-13 diff --git a/eval/.npmignore b/eval/.npmignore new file mode 100644 index 000000000..6acfaf42a --- /dev/null +++ b/eval/.npmignore @@ -0,0 +1,24 @@ +# Ignore runtime and test artifacts when the eval package is packed. +.env* +.venv/ +.uv-cache/ +.cache/ +.tmp/ +.comet/ +.ruff_cache/ +.pytest_cache/ +.pytest_cache*/ +.pytest-basetemp-*/ +.pytest-tmp-*/ +logs/ +.pytest* +.pytest_* +_pytest*/ +_eval*/ +**/.pytest*/ +**/.pytest-basetemp-*/ +**/.pytest-tmp-*/ +**/.pytest_*/ +**/__pycache__/ +**/.comet/ +**/logs/ diff --git a/eval/langfuse/.npmignore b/eval/langfuse/.npmignore new file mode 100644 index 000000000..0aec011ed --- /dev/null +++ b/eval/langfuse/.npmignore @@ -0,0 +1,12 @@ +# Eval runs and caches are local artifacts, not package inputs. +logs/ +.cache/ +.tmp/ +.comet/ +.pytest*/ +_pytest*/ +**/.pytest*/ +**/.pytest_*/ +**/.cache/ +**/.comet/ +**/__pycache__/ diff --git a/eval/langsmith/.npmignore b/eval/langsmith/.npmignore new file mode 100644 index 000000000..0aec011ed --- /dev/null +++ b/eval/langsmith/.npmignore @@ -0,0 +1,12 @@ +# Eval runs and caches are local artifacts, not package inputs. +logs/ +.cache/ +.tmp/ +.comet/ +.pytest*/ +_pytest*/ +**/.pytest*/ +**/.pytest_*/ +**/.cache/ +**/.comet/ +**/__pycache__/ diff --git a/eval/local/.npmignore b/eval/local/.npmignore new file mode 100644 index 000000000..72d2703b1 --- /dev/null +++ b/eval/local/.npmignore @@ -0,0 +1,23 @@ +# Ignore runtime and test artifacts when the eval package is packed. +.env* +.venv/ +.uv-cache/ +.cache/ +.tmp/ +.comet/ +.ruff_cache/ +.pytest_cache/ +.pytest_cache*/ +.pytest-basetemp-*/ +.pytest-tmp-*/ +logs/ +.pytest* +.pytest_* +_pytest*/ +_eval*/ +**/.pytest*/ +**/.pytest-basetemp-*/ +**/.pytest-tmp-*/ +**/.pytest_*/ +**/__pycache__/ +**/.comet/ diff --git a/package.json b/package.json index 32cc0d787..65e7ba6b0 100644 --- a/package.json +++ b/package.json @@ -30,32 +30,17 @@ "assets", "!assets/skills-maintainer", "!assets/skills-maintainer/**", - "eval", - "!eval/.env*", - "!eval/**/.env*", "eval/.env.example", - "!eval/.venv", - "!eval/.uv-cache", - "!eval/.cache", - "!eval/.tmp", - "!eval/.ruff_cache", - "!eval/uv.lock", - "!eval/**/__pycache__", - "!eval/.pytest_cache", - "!eval/.pytest_cache*", - "!eval/.pytest-basetemp-*", - "!eval/.pytest-tmp-*", - "!eval/local/logs", - "!eval/local/.pytest_docker_build.lock", - "!eval/**/logs", - "!eval/**/.cache", - "!eval/**/.ruff_cache", - "!eval/**/.tmp", - "!eval/**/.pytest_cache", - "!eval/**/.pytest_cache*", - "!eval/**/.pytest*", - "!eval/**/.pytest-basetemp-*", - "!eval/**/.pytest-tmp-*", + "eval/CLAUDE.md", + "eval/README.md", + "eval/pyproject.toml", + "eval/report-html-config.json", + "eval/simulator-instruction.md", + "eval/langfuse", + "eval/langsmith", + "eval/local", + "eval/scaffold", + "eval/schemas", "scripts/install/postinstall.js", "!dist/**/*.test.js", "!dist/**/__tests__" diff --git a/test/app/eval-static-collect.integration.test.ts b/test/app/eval-static-collect.integration.test.ts index 3d37ad0c4..532bc15fa 100644 --- a/test/app/eval-static-collect.integration.test.ts +++ b/test/app/eval-static-collect.integration.test.ts @@ -71,7 +71,14 @@ function run(command: string, args: string[], cwd: string, env: NodeJS.ProcessEn afterEach(async () => { await Promise.all( - temporary.splice(0).map((entry) => fs.rm(entry, { recursive: true, force: true })), + temporary.splice(0).map((entry) => + fs.rm(entry, { + recursive: true, + force: true, + maxRetries: process.platform === 'win32' ? 8 : 0, + retryDelay: process.platform === 'win32' ? 100 : 0, + }), + ), ); }); diff --git a/test/domains/comet-classic/comet-scripts.test.ts b/test/domains/comet-classic/comet-scripts.test.ts index 28af16383..3cbce0fbc 100644 --- a/test/domains/comet-classic/comet-scripts.test.ts +++ b/test/domains/comet-classic/comet-scripts.test.ts @@ -22,11 +22,14 @@ function runNode( env: NodeJS.ProcessEnv = {}, timeout?: number, ) { + const isolatedHome = path.join(cwd, '.test-home'); return spawnSync(process.execPath, [script, ...args], { cwd, encoding: 'utf-8', env: { ...process.env, + HOME: isolatedHome, + USERPROFILE: isolatedHome, COMET_RUNTIME_CLASSIC_ROOT: classicRuntimeRoot, COMET_CLASSIC_SKILL_ROOT: classicRuntimeRoot, ...env, diff --git a/test/scripts/prepublish-check.test.ts b/test/scripts/prepublish-check.test.ts index 94273ee81..e41740d63 100644 --- a/test/scripts/prepublish-check.test.ts +++ b/test/scripts/prepublish-check.test.ts @@ -52,6 +52,9 @@ async function makePublishFixture(): Promise { await writeFile(root, 'package.json', JSON.stringify(packageJson, null, 2)); await writeFile(root, 'README.md', '# Comet publish fixture\n'); await writeFile(root, 'eval/pyproject.toml', '[project]\nname = "comet-eval-fixture"\n'); + for (const relativePath of ['eval/.npmignore', 'eval/local/.npmignore']) { + await writeFile(root, relativePath, await fs.readFile(relativePath, 'utf-8')); + } await writeFile( root, 'eval/schemas/comet.eval/v1alpha1.schema.json', @@ -175,4 +178,28 @@ describe('prepublish security check', () => { expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); expect(result.stdout).toContain('[SECURITY] No secrets detected. Safe to publish.'); }); + + it('does not use a broad eval package entry that traverses derived pytest directories', async () => { + const packageJson = JSON.parse(await fs.readFile('package.json', 'utf-8')) as { + files?: string[]; + }; + + expect(packageJson.files).not.toContain('eval'); + expect(packageJson.files?.some((entry) => entry.startsWith('!eval'))).toBe(false); + expect(packageJson.files).toEqual( + expect.arrayContaining([ + 'eval/.env.example', + 'eval/CLAUDE.md', + 'eval/README.md', + 'eval/pyproject.toml', + 'eval/report-html-config.json', + 'eval/simulator-instruction.md', + 'eval/langfuse', + 'eval/langsmith', + 'eval/local', + 'eval/scaffold', + 'eval/schemas', + ]), + ); + }); });