@rpamis/comet 0.4.0-beta.19 → 0.4.0-beta.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +3 -0
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-hook-router.mjs +10 -10
- package/assets/skills/comet-archive/SKILL.md +0 -1
- package/assets/skills/comet-archive/agents/openai.yaml +1 -1
- package/assets/skills/comet-build/SKILL.md +0 -1
- package/assets/skills/comet-build/agents/openai.yaml +1 -1
- package/assets/skills/comet-design/SKILL.md +0 -1
- package/assets/skills/comet-design/agents/openai.yaml +1 -1
- package/assets/skills/comet-hotfix/SKILL.md +0 -1
- package/assets/skills/comet-hotfix/agents/openai.yaml +1 -1
- package/assets/skills/comet-native/SKILL.md +1 -1
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +56 -56
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +77 -77
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +11 -11
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +55 -55
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +54 -54
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +6 -6
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +91 -91
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +63 -63
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +45 -45
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +42 -42
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +67 -67
- package/assets/skills/comet-open/SKILL.md +0 -1
- package/assets/skills/comet-open/agents/openai.yaml +1 -1
- package/assets/skills/comet-tweak/SKILL.md +0 -1
- package/assets/skills/comet-tweak/agents/openai.yaml +1 -1
- package/assets/skills/comet-verify/SKILL.md +0 -1
- package/assets/skills/comet-verify/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-archive/SKILL.md +0 -1
- package/assets/skills-zh/comet-archive/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-build/SKILL.md +0 -1
- package/assets/skills-zh/comet-build/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-design/SKILL.md +0 -1
- package/assets/skills-zh/comet-design/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-hotfix/SKILL.md +0 -1
- package/assets/skills-zh/comet-hotfix/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-native/SKILL.md +1 -1
- package/assets/skills-zh/comet-open/SKILL.md +0 -1
- package/assets/skills-zh/comet-open/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-tweak/SKILL.md +0 -1
- package/assets/skills-zh/comet-tweak/agents/openai.yaml +1 -1
- package/assets/skills-zh/comet-verify/SKILL.md +0 -1
- package/assets/skills-zh/comet-verify/agents/openai.yaml +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +43 -24
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +32 -18
- package/dist/app/commands/init.js.map +1 -1
- package/dist/domains/comet-native/native-change.d.ts +0 -1
- package/dist/domains/comet-native/native-change.d.ts.map +1 -1
- package/dist/domains/comet-native/native-change.js +2 -2
- package/dist/domains/comet-native/native-change.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +1 -1
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +3 -3
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +23 -0
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- package/dist/domains/dashboard/web/index.html +14 -14
- package/dist/domains/integrations/codegraph.d.ts +24 -2
- package/dist/domains/integrations/codegraph.d.ts.map +1 -1
- package/dist/domains/integrations/codegraph.js +307 -1
- package/dist/domains/integrations/codegraph.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,74 +1,74 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var sw=Object.create;var rd=Object.defineProperty;var cw=Object.getOwnPropertyDescriptor;var lw=Object.getOwnPropertyNames;var uw=Object.getPrototypeOf,dw=Object.prototype.hasOwnProperty;var
|
|
5
|
-
`)}};Pr.defaultYaml={explicit:!1,version:"1.2"};Pr.defaultTags={"!!":"tag:yaml.org,2002:"};hd.Directives=Pr});var
|
|
4
|
+
var sw=Object.create;var rd=Object.defineProperty;var cw=Object.getOwnPropertyDescriptor;var lw=Object.getOwnPropertyNames;var uw=Object.getPrototypeOf,dw=Object.prototype.hasOwnProperty;var Wn=(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 fw=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of lw(t))!dw.call(e,n)&&n!==i&&rd(e,n,{get:()=>t[n],enumerable:!(r=cw(t,n))||r.enumerable});return e};var br=(e,t,i)=>(i=e!=null?sw(uw(e)):{},fw(t||!e||!e.__esModule?rd(i,"default",{value:e,enumerable:!0}):i,e));var F=C(ce=>{"use strict";var us=Symbol.for("yaml.alias"),ad=Symbol.for("yaml.document"),zn=Symbol.for("yaml.map"),od=Symbol.for("yaml.pair"),ds=Symbol.for("yaml.scalar"),Jn=Symbol.for("yaml.seq"),ht=Symbol.for("yaml.node.type"),ww=e=>!!e&&typeof e=="object"&&e[ht]===us,yw=e=>!!e&&typeof e=="object"&&e[ht]===ad,Nw=e=>!!e&&typeof e=="object"&&e[ht]===zn,bw=e=>!!e&&typeof e=="object"&&e[ht]===od,sd=e=>!!e&&typeof e=="object"&&e[ht]===ds,kw=e=>!!e&&typeof e=="object"&&e[ht]===Jn;function cd(e){if(e&&typeof e=="object")switch(e[ht]){case zn:case Jn:return!0}return!1}function Sw(e){if(e&&typeof e=="object")switch(e[ht]){case us:case zn:case ds:case Jn:return!0}return!1}var Ew=e=>(sd(e)||cd(e))&&!!e.anchor;ce.ALIAS=us;ce.DOC=ad;ce.MAP=zn;ce.NODE_TYPE=ht;ce.PAIR=od;ce.SCALAR=ds;ce.SEQ=Jn;ce.hasAnchor=Ew;ce.isAlias=ww;ce.isCollection=cd;ce.isDocument=yw;ce.isMap=Nw;ce.isNode=Sw;ce.isPair=bw;ce.isScalar=sd;ce.isSeq=kw});var Er=C(fs=>{"use strict";var ae=F(),ge=Symbol("break visit"),ld=Symbol("skip children"),rt=Symbol("remove node");function Gn(e,t){let i=ud(t);ae.isDocument(e)?Ci(null,e.contents,i,Object.freeze([e]))===rt&&(e.contents=null):Ci(null,e,i,Object.freeze([]))}Gn.BREAK=ge;Gn.SKIP=ld;Gn.REMOVE=rt;function Ci(e,t,i,r){let n=dd(e,t,i,r);if(ae.isNode(n)||ae.isPair(n))return fd(e,r,n),Ci(e,n,i,r);if(typeof n!="symbol"){if(ae.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Ci(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===rt&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){r=Object.freeze(r.concat(t));let a=Ci("key",t.key,i,r);if(a===ge)return ge;a===rt&&(t.key=null);let o=Ci("value",t.value,i,r);if(o===ge)return ge;o===rt&&(t.value=null)}}return n}async function Un(e,t){let i=ud(t);ae.isDocument(e)?await Ri(null,e.contents,i,Object.freeze([e]))===rt&&(e.contents=null):await Ri(null,e,i,Object.freeze([]))}Un.BREAK=ge;Un.SKIP=ld;Un.REMOVE=rt;async function Ri(e,t,i,r){let n=await dd(e,t,i,r);if(ae.isNode(n)||ae.isPair(n))return fd(e,r,n),Ri(e,n,i,r);if(typeof n!="symbol"){if(ae.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Ri(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===rt&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){r=Object.freeze(r.concat(t));let a=await Ri("key",t.key,i,r);if(a===ge)return ge;a===rt&&(t.key=null);let o=await Ri("value",t.value,i,r);if(o===ge)return ge;o===rt&&(t.value=null)}}return n}function ud(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function dd(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(ae.isMap(t))return i.Map?.(e,t,r);if(ae.isSeq(t))return i.Seq?.(e,t,r);if(ae.isPair(t))return i.Pair?.(e,t,r);if(ae.isScalar(t))return i.Scalar?.(e,t,r);if(ae.isAlias(t))return i.Alias?.(e,t,r)}function fd(e,t,i){let r=t[t.length-1];if(ae.isCollection(r))r.items[e]=i;else if(ae.isPair(r))e==="key"?r.key=i:r.value=i;else if(ae.isDocument(r))r.contents=i;else{let n=ae.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}fs.visit=Gn;fs.visitAsync=Un});var ps=C(hd=>{"use strict";var pd=F(),Pw=Er(),xw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Cw=e=>e.replace(/[!,[\]{}]/g,t=>xw[t]),Pr=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+Cw(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&&pd.isNode(t.contents)){let a={};Pw.visit(t.contents,(o,s)=>{pd.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};Pr.defaultYaml={explicit:!1,version:"1.2"};Pr.defaultTags={"!!":"tag:yaml.org,2002:"};hd.Directives=Pr});var Kn=C(xr=>{"use strict";var md=F(),Rw=Er();function Aw(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 vd(e){let t=new Set;return Rw.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function gd(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function _w(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=vd(e));let o=gd(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(md.isScalar(o.node)||md.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}}xr.anchorIsValid=Aw;xr.anchorNames=vd;xr.createNodeAnchors=_w;xr.findNewAnchor=gd});var hs=C(wd=>{"use strict";function Cr(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Cr(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Cr(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Cr(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Cr(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}wd.applyReviver=Cr});var At=C(Nd=>{"use strict";var Iw=F();function yd(e,t,i){if(Array.isArray(e))return e.map((r,n)=>yd(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!Iw.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}Nd.toJS=yd});var Yn=C(kd=>{"use strict";var Tw=hs(),bd=F(),jw=At(),ms=class{constructor(t){Object.defineProperty(this,bd.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(!bd.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=jw.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Tw.applyReviver(a,{"":s},"",s):s}};kd.NodeBase=ms});var Rr=C(Sd=>{"use strict";var $w=Kn(),Ow=Er(),Ai=F(),Hw=Yn(),Dw=At(),vs=class extends Hw.NodeBase{constructor(t){super(Ai.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=[],Ow.visit(t,{Node:(a,o)=>{(Ai.isAlias(o)||Ai.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||(Dw.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=Xn(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($w.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 Xn(e,t,i){if(Ai.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Ai.isCollection(t)){let r=0;for(let n of t.items){let a=Xn(e,n,i);a>r&&(r=a)}return r}else if(Ai.isPair(t)){let r=Xn(e,t.key,i),n=Xn(e,t.value,i);return Math.max(r,n)}return 1}Sd.Alias=vs});var ie=C(gs=>{"use strict";var Bw=F(),Lw=Yn(),Fw=At(),Mw=e=>!e||typeof e!="function"&&typeof e!="object",_t=class extends Lw.NodeBase{constructor(t){super(Bw.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Fw.toJS(this.value,t,i)}toString(){return String(this.value)}};_t.BLOCK_FOLDED="BLOCK_FOLDED";_t.BLOCK_LITERAL="BLOCK_LITERAL";_t.PLAIN="PLAIN";_t.QUOTE_DOUBLE="QUOTE_DOUBLE";_t.QUOTE_SINGLE="QUOTE_SINGLE";gs.Scalar=_t;gs.isScalarValue=Mw});var Ar=C(Pd=>{"use strict";var qw=Rr(),li=F(),Ed=ie(),Vw="tag:yaml.org,2002:";function Ww(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 zw(e,t,i){if(li.isDocument(e)&&(e=e.contents),li.isNode(e))return e;if(li.isPair(e)){let d=i.schema[li.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 qw.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Vw+t.slice(2));let l=Ww(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Ed.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[li.MAP]:Symbol.iterator in Object(e)?o[li.SEQ]:o[li.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 Ed.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Pd.createNode=zw});var Zn=C(Qn=>{"use strict";var Jw=Ar(),nt=F(),Gw=Yn();function ws(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 Jw.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 xd=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ys=class extends Gw.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=>nt.isNode(r)||nt.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(xd(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(nt.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,ws(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(nt.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&&nt.isScalar(a)?a.value:a:nt.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!nt.isPair(i))return!1;let r=i.value;return r==null||t&&nt.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 nt.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(nt.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,ws(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};Qn.Collection=ys;Qn.collectionFromPath=ws;Qn.isEmptyPath=xd});var _r=C(ea=>{"use strict";var Uw=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ns(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Kw=(e,t,i)=>e.endsWith(`
|
|
6
6
|
`)?Ns(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+Ns(i,t):(e.endsWith(" ")?"":" ")+i;
|
|
8
|
+
`+Ns(i,t):(e.endsWith(" ")?"":" ")+i;ea.indentComment=Ns;ea.lineComment=Kw;ea.stringifyComment=Uw});var Rd=C(Ir=>{"use strict";var Yw="flow",bs="block",ta="quoted";function Xw(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,v=!1,p=-1,m=-1,b=-1;i===bs&&(p=Cd(e,p,t.length),p!==-1&&(d=p+c));for(let E;E=e[p+=1];){if(i===ta&&E==="\\"){switch(m=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}b=p}if(E===`
|
|
9
9
|
`)i===bs&&(p=Cd(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(E===" "&&h&&h!==" "&&h!==`
|
|
10
10
|
`&&h!==" "){let k=e[p+1];k&&k!==" "&&k!==`
|
|
11
|
-
`&&k!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===
|
|
12
|
-
${t}${e.slice(0,P)}`:(i===
|
|
11
|
+
`&&k!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===ta){for(;h===" "||h===" ";)h=E,E=e[p+=1],v=!0;let k=p>b+1?p-2:m-1;if(u[k])return e;l.push(k),u[k]=!0,d=k+c,f=void 0}else v=!0}h=E}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let E=0;E<l.length;++E){let k=l[E],P=l[E+1]||e.length;k===0?y=`
|
|
12
|
+
${t}${e.slice(0,P)}`:(i===ta&&u[k]&&(y+=`${e[k]}\\`),y+=`
|
|
13
13
|
${t}${e.slice(k+1,P)}`)}return y}function Cd(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}Ir.FOLD_BLOCK=bs;Ir.FOLD_FLOW=Yw;Ir.FOLD_QUOTED=ta;Ir.foldFlowLines=Xw});var jr=C(Ad=>{"use strict";var Ve=ie(),It=Rd(),ra=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),na=e=>/^(%|---|\.\.\.)/m.test(e);function Qw(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Tr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(na(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:It.foldFlowLines(o,a,It.FOLD_QUOTED,ra(t,!1))}function ks(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Tr(e,t);let i=t.indent||(na(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:It.foldFlowLines(r,i,It.FOLD_FLOW,ra(t,!1))}function _i(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Tr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=ks:a&&!n?r=Tr:r=i?ks:Tr}return r(e,t)}var Ss;try{Ss=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{Ss=/\n+(?!\n|$)/g}function
|
|
23
|
+
|$)`,"g")}catch{Ss=/\n+(?!\n|$)/g}function ia({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return _i(i,r);let l=r.indent||(r.forceBlockIndent||na(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ve.Scalar.BLOCK_FOLDED?!1:t===Ve.Scalar.BLOCK_LITERAL?!0:!Qw(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=i.length;f>0;--f){let P=i[f-1];if(P!==`
|
|
26
26
|
`&&P!==" "&&P!==" ")break}let h=i.substring(f),v=h.indexOf(`
|
|
27
27
|
`);v===-1?d="-":i===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(i=i.slice(0,-h.length),h[h.length-1]===`
|
|
28
28
|
`&&(h=h.slice(0,-1)),h=h.replace(Ss,`$&${l}`));let p=!1,m,b=-1;for(m=0;m<i.length;++m){let P=i[m];if(P===" ")p=!0;else if(P===`
|
|
29
29
|
`)b=m;else break}let y=i.substring(0,b<m?b+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let k=(p?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let P=i.replace(/\n+/g,`
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),N=!1,x=
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),N=!1,x=ra(r,!0);o!=="folded"&&t!==Ve.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{N=!0});let w=It.foldFlowLines(`${y}${P}${h}`,l,It.FOLD_BLOCK,x);if(!N)return`>${k}
|
|
31
31
|
${l}${w}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
|
|
32
32
|
${l}${y}${i}${h}`}function Zw(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
33
|
`)||u&&/[[\]{},]/.test(a))return _i(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
-
`)?_i(a,t):
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return _i(a,t)}return s?d:
|
|
37
|
-
${t.indent}${s}`:s}Es.createStringifyContext=ny;Es.stringify=sy});var jd=C(
|
|
38
|
-
${s}:`):(m=`${m}:`,f&&(m+=Or.lineComment(m,i.indent,l(f))));let b,y,E;mt.isNode(t)?(b=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(b=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&mt.isScalar(t)&&(i.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&mt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,P=
|
|
34
|
+
`)?_i(a,t):ia(e,t,i,r);if(!s&&!u&&n!==Ve.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return ia(e,t,i,r);if(na(a)){if(c==="")return t.forceBlockIndent=!0,ia(e,t,i,r);if(s&&c===l)return _i(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return _i(a,t)}return s?d:It.foldFlowLines(d,c,It.FOLD_FLOW,ra(t,!1))}function ey(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!==Ve.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ve.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ve.Scalar.BLOCK_FOLDED:case Ve.Scalar.BLOCK_LITERAL:return n||a?_i(o.value,t):ia(o,t,i,r);case Ve.Scalar.QUOTE_DOUBLE:return Tr(o.value,t);case Ve.Scalar.QUOTE_SINGLE:return ks(o.value,t);case Ve.Scalar.PLAIN:return Zw(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}Ad.stringifyString=ey});var $r=C(Es=>{"use strict";var ty=Kn(),Tt=F(),iy=_r(),ry=jr();function ny(e,t){let i=Object.assign({blockQuote:!0,commentString:iy.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 ay(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(Tt.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 oy(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Tt.isScalar(e)||Tt.isCollection(e))&&e.anchor;a&&ty.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 sy(e,t,i,r){if(Tt.isPair(e))return e.toString(t,i,r);if(Tt.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=Tt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=ay(t.doc.schema.tags,a));let o=oy(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):Tt.isScalar(a)?ry.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Tt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}Es.createStringifyContext=ny;Es.stringify=sy});var jd=C(Td=>{"use strict";var mt=F(),_d=ie(),Id=$r(),Or=_r();function cy({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=mt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(mt.isCollection(e)||!mt.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||mt.isCollection(e)||(mt.isScalar(e)?e.type===_d.Scalar.BLOCK_FOLDED||e.type===_d.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,p=!1,m=Id.stringify(e,i,()=>v=!0,()=>p=!0);if(!h&&!i.inFlow&&m.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 v&&r&&r(),m===""?"?":h?`? ${m}`:m}else if(a&&!d||t==null&&h)return m=`? ${m}`,f&&!v?m+=Or.lineComment(m,i.indent,l(f)):p&&n&&n(),m;v&&(f=null),h?(f&&(m+=Or.lineComment(m,i.indent,l(f))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,f&&(m+=Or.lineComment(m,i.indent,l(f))));let b,y,E;mt.isNode(t)?(b=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(b=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&mt.isScalar(t)&&(i.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&mt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,P=Id.stringify(t,i,()=>k=!0,()=>p=!0),N=" ";if(f||b||y){if(N=b?`
|
|
39
39
|
`:"",y){let x=l(y);N+=`
|
|
40
40
|
${Or.indentComment(x,i.indent)}`}P===""&&!i.inFlow?N===`
|
|
41
41
|
`&&E&&(N=`
|
|
42
42
|
|
|
43
43
|
`):N+=`
|
|
44
44
|
${i.indent}`}else if(!h&&mt.isCollection(t)){let x=P[0],w=P.indexOf(`
|
|
45
|
-
`),g=w!==-1,S=i.inFlow??t.flow??t.items.length===0;if(g||!S){let $=!1;if(g&&(x==="&"||x==="!")){let
|
|
45
|
+
`),g=w!==-1,S=i.inFlow??t.flow??t.items.length===0;if(g||!S){let $=!1;if(g&&(x==="&"||x==="!")){let T=P.indexOf(" ");x==="&"&&T!==-1&&T<w&&P[T+1]==="!"&&(T=P.indexOf(" ",T+1)),(T===-1||w<T)&&($=!0)}$||(N=`
|
|
46
46
|
${i.indent}`)}}else(P===""||P[0]===`
|
|
47
|
-
`)&&(N="");return m+=N+P,i.inFlow?k&&r&&r():E&&!k?m+=Or.lineComment(m,i.indent,l(E)):p&&n&&n(),m}
|
|
47
|
+
`)&&(N="");return m+=N+P,i.inFlow?k&&r&&r():E&&!k?m+=Or.lineComment(m,i.indent,l(E)):p&&n&&n(),m}Td.stringifyPair=cy});var xs=C(Ps=>{"use strict";var $d=Wn("process");function ly(e,...t){e==="debug"&&console.log(...t)}function uy(e,t){(e==="debug"||e==="warn")&&(typeof $d.emitWarning=="function"?$d.emitWarning(t):console.warn(t))}Ps.debug=ly;Ps.warn=uy});var la=C(ca=>{"use strict";var sa=F(),Od=ie(),aa="<<",oa={identify:e=>e===aa||typeof e=="symbol"&&e.description===aa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Od.Scalar(Symbol(aa)),{addToJSMap:Hd}),stringify:()=>aa},dy=(e,t)=>(oa.identify(t)||sa.isScalar(t)&&(!t.type||t.type===Od.Scalar.PLAIN)&&oa.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===oa.tag&&i.default);function Hd(e,t,i){let r=Dd(e,i);if(sa.isSeq(r))for(let n of r.items)Cs(e,t,n);else if(Array.isArray(r))for(let n of r)Cs(e,t,n);else Cs(e,t,r)}function Cs(e,t,i){let r=Dd(e,i);if(!sa.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 Dd(e,t){return e&&sa.isAlias(t)?t.resolve(e.doc,e):t}ca.addMergeToJSMap=Hd;ca.isMergeKey=dy;ca.merge=oa});var As=C(Fd=>{"use strict";var fy=xs(),Bd=la(),py=$r(),Ld=F(),Rs=At();function hy(e,t,{key:i,value:r}){if(Ld.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Bd.isMergeKey(e,i))Bd.addMergeToJSMap(e,t,r);else{let n=Rs.toJS(i,"",e);if(t instanceof Map)t.set(n,Rs.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=my(i,n,e),o=Rs.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 my(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Ld.isNode(e)&&i?.doc){let r=py.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)+'..."'),fy.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)}Fd.addPairToJSMap=hy});var jt=C(_s=>{"use strict";var Md=Ar(),vy=jd(),gy=As(),ua=F();function wy(e,t,i){let r=Md.createNode(e,void 0,i),n=Md.createNode(t,void 0,i);return new da(r,n)}var da=class e{constructor(t,i=null){Object.defineProperty(this,ua.NODE_TYPE,{value:ua.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return ua.isNode(i)&&(i=i.clone(t)),ua.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return gy.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?vy.stringifyPair(this,t,i,r):JSON.stringify(this)}};_s.Pair=da;_s.createPair=wy});var Is=C(Vd=>{"use strict";var ui=F(),qd=$r(),fa=_r();function yy(e,t,i){return(t.inFlow??e.flow?by:Ny)(e,t,i)}function Ny({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;v<t.length;++v){let p=t[v],m=null;if(ui.isNode(p))!d&&p.spaceBefore&&f.push(""),pa(i,f,p.commentBefore,d),p.comment&&(m=p.comment);else if(ui.isPair(p)){let y=ui.isNode(p.key)?p.key:null;y&&(!d&&y.spaceBefore&&f.push(""),pa(i,f,y.commentBefore,d))}d=!1;let b=qd.stringify(p,u,()=>m=null,()=>d=!0);m&&(b+=fa.lineComment(b,a,l(m))),d&&m&&(d=!1),f.push(r+b)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let p=f[v];h+=p?`
|
|
48
48
|
${c}${p}`:`
|
|
49
49
|
`}}return e?(h+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,E)=>y+E.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),m&&(b+=
|
|
50
|
+
`+fa.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function by({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;v<e.length;++v){let p=e[v],m=null;if(ui.isNode(p))p.spaceBefore&&d.push(""),pa(t,d,p.commentBefore,!1),p.comment&&(m=p.comment);else if(ui.isPair(p)){let y=ui.isNode(p.key)?p.key:null;y&&(y.spaceBefore&&d.push(""),pa(t,d,y.commentBefore,!1),y.comment&&(l=!0));let E=ui.isNode(p.value)?p.value:null;E?(E.comment&&(m=E.comment),E.commentBefore&&(l=!0)):p.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let b=qd.stringify(p,c,()=>m=null);l||(l=d.length>u||b.includes(`
|
|
51
|
+
`)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,E)=>y+E.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),m&&(b+=fa.lineComment(b,r,s(m))),d.push(b),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let v=d.reduce((p,m)=>p+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let p of d)v+=p?`
|
|
52
52
|
${a}${n}${p}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function
|
|
55
|
-
`:" ")}return nN.stringifyString({comment:e,type:t,value:s},r,n,a)}};uf.binary=aN});var
|
|
54
|
+
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function pa({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=fa.indentComment(t(r),e);i.push(a.trimStart())}}Vd.stringifyCollection=yy});var Ot=C(js=>{"use strict";var ky=Is(),Sy=As(),Ey=Zn(),$t=F(),ha=jt(),Py=ie();function Hr(e,t){let i=$t.isScalar(t)?t.value:t;for(let r of e)if($t.isPair(r)&&(r.key===t||r.key===i||$t.isScalar(r.key)&&r.key.value===i))return r}var Ts=class extends Ey.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super($t.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(ha.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;$t.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new ha.Pair(t,t?.value):r=new ha.Pair(t.key,t.value);let n=Hr(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);$t.isScalar(n.value)&&Py.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=Hr(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Hr(this.items,t)?.value;return(!i&&$t.isScalar(n)?n.value:n)??void 0}has(t){return!!Hr(this.items,t)}set(t,i){this.add(new ha.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)Sy.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!$t.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})),ky.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};js.YAMLMap=Ts;js.findPair=Hr});var Ii=C(zd=>{"use strict";var xy=F(),Wd=Ot(),Cy={collection:"map",default:!0,nodeClass:Wd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return xy.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Wd.YAMLMap.from(e,t,i)};zd.map=Cy});var Ht=C(Jd=>{"use strict";var Ry=Ar(),Ay=Is(),_y=Zn(),va=F(),Iy=ie(),Ty=At(),$s=class extends _y.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(va.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=ma(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=ma(t);if(typeof r!="number")return;let n=this.items[r];return!i&&va.isScalar(n)?n.value:n}has(t){let i=ma(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=ma(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];va.isScalar(n)&&Iy.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(Ty.toJS(a,String(n++),i));return r}toString(t,i,r){return t?Ay.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(Ry.createNode(s,void 0,r))}}return a}};function ma(e){let t=va.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Jd.YAMLSeq=$s});var Ti=C(Ud=>{"use strict";var jy=F(),Gd=Ht(),$y={collection:"seq",default:!0,nodeClass:Gd.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return jy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Gd.YAMLSeq.from(e,t,i)};Ud.seq=$y});var Dr=C(Kd=>{"use strict";var Oy=jr(),Hy={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),Oy.stringifyString(e,t,i,r)}};Kd.string=Hy});var ga=C(Qd=>{"use strict";var Yd=ie(),Xd={identify:e=>e==null,createNode:()=>new Yd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Yd.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Xd.test.test(e)?e:t.options.nullStr};Qd.nullTag=Xd});var Os=C(ef=>{"use strict";var Dy=ie(),Zd={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Dy.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Zd.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};ef.boolTag=Zd});var ji=C(tf=>{"use strict";function By({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}tf.stringifyNumber=By});var Ds=C(wa=>{"use strict";var Ly=ie(),Hs=ji(),Fy={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:Hs.stringifyNumber},My={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():Hs.stringifyNumber(e)}},qy={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 Ly.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Hs.stringifyNumber};wa.float=qy;wa.floatExp=My;wa.floatNaN=Fy});var Ls=C(Na=>{"use strict";var rf=ji(),ya=e=>typeof e=="bigint"||Number.isInteger(e),Bs=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function nf(e,t,i){let{value:r}=e;return ya(r)&&r>=0?i+r.toString(t):rf.stringifyNumber(e)}var Vy={identify:e=>ya(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Bs(e,2,8,i),stringify:e=>nf(e,8,"0o")},Wy={identify:ya,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Bs(e,0,10,i),stringify:rf.stringifyNumber},zy={identify:e=>ya(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Bs(e,2,16,i),stringify:e=>nf(e,16,"0x")};Na.int=Wy;Na.intHex=zy;Na.intOct=Vy});var of=C(af=>{"use strict";var Jy=Ii(),Gy=ga(),Uy=Ti(),Ky=Dr(),Yy=Os(),Fs=Ds(),Ms=Ls(),Xy=[Jy.map,Uy.seq,Ky.string,Gy.nullTag,Yy.boolTag,Ms.intOct,Ms.int,Ms.intHex,Fs.floatNaN,Fs.floatExp,Fs.float];af.schema=Xy});var lf=C(cf=>{"use strict";var Qy=ie(),Zy=Ii(),eN=Ti();function sf(e){return typeof e=="bigint"||Number.isInteger(e)}var ba=({value:e})=>JSON.stringify(e),tN=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ba},{identify:e=>e==null,createNode:()=>new Qy.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ba},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ba},{identify:sf,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})=>sf(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:ba}],iN={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},rN=[Zy.map,eN.seq].concat(tN,iN);cf.schema=rN});var Vs=C(uf=>{"use strict";var Br=Wn("buffer"),qs=ie(),nN=jr(),aN={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Br.Buffer=="function")return Br.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Br.Buffer=="function")s=o instanceof Br.Buffer?o.toString("base64"):Br.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=qs.Scalar.BLOCK_LITERAL),t!==qs.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===qs.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return nN.stringifyString({comment:e,type:t,value:s},r,n,a)}};uf.binary=aN});var Ea=C(Sa=>{"use strict";var ka=F(),Ws=jt(),oN=ie(),sN=Ht();function df(e,t){if(ka.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!ka.isPair(r)){if(ka.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Ws.Pair(new oN.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}e.items[i]=ba.isPair(r)?r:new Ws.Pair(r)}}else t("Expected a sequence for this tag");return e}function ff(e,t,i){let{replacer:r}=i,n=new sN.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(Ws.createPair(s,c,i))}return n}var cN={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:df,createNode:ff};ka.createPairs=ff;ka.pairs=cN;ka.resolvePairs=df});var Gs=C(Js=>{"use strict";var pf=F(),zs=At(),Lr=Ot(),lN=Ht(),hf=Sa(),di=class e extends lN.YAMLSeq{constructor(){super(),this.add=Lr.YAMLMap.prototype.add.bind(this),this.delete=Lr.YAMLMap.prototype.delete.bind(this),this.get=Lr.YAMLMap.prototype.get.bind(this),this.has=Lr.YAMLMap.prototype.has.bind(this),this.set=Lr.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(pf.isPair(n)?(a=zs.toJS(n.key,"",i),o=zs.toJS(n.value,a,i)):a=zs.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=hf.createPairs(t,i,r),a=new this;return a.items=n.items,a}};di.tag="tag:yaml.org,2002:omap";var uN={collection:"seq",identify:e=>e instanceof Map,nodeClass:di,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=hf.resolvePairs(e,t),r=[];for(let{key:n}of i.items)pf.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new di,i)},createNode:(e,t,i)=>di.from(e,t,i)};Js.YAMLOMap=di;Js.omap=uN});var yf=C(Us=>{"use strict";var mf=ie();function vf({value:e,source:t},i){return t&&(e?gf:wf).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var gf={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 mf.Scalar(!0),stringify:vf},wf={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 mf.Scalar(!1),stringify:vf};Us.falseTag=wf;Us.trueTag=gf});var Nf=C(Ea=>{"use strict";var dN=ie(),Ks=ji(),fN={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:Ks.stringifyNumber},pN={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():Ks.stringifyNumber(e)}},hN={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 dN.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:Ks.stringifyNumber};Ea.float=hN;Ea.floatExp=pN;Ea.floatNaN=fN});var kf=C(Mr=>{"use strict";var bf=ji(),Fr=e=>typeof e=="bigint"||Number.isInteger(e);function Pa(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 Ys(e,t,i){let{value:r}=e;if(Fr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return bf.stringifyNumber(e)}var mN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Pa(e,2,2,i),stringify:e=>Ys(e,2,"0b")},vN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Pa(e,1,8,i),stringify:e=>Ys(e,8,"0")},gN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Pa(e,0,10,i),stringify:bf.stringifyNumber},wN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Pa(e,2,16,i),stringify:e=>Ys(e,16,"0x")};Mr.int=gN;Mr.intBin=mN;Mr.intHex=wN;Mr.intOct=vN});var Qs=C(Xs=>{"use strict";var Ra=F(),xa=jt(),Ca=Ot(),fi=class e extends Ca.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Ra.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new xa.Pair(t.key,null):i=new xa.Pair(t,null),Ca.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Ca.findPair(this.items,t);return!i&&Ra.isPair(r)?Ra.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=Ca.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new xa.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(xa.createPair(o,null,r));return a}};fi.tag="tag:yaml.org,2002:set";var yN={collection:"map",identify:e=>e instanceof Set,nodeClass:fi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>fi.from(e,t,i),resolve(e,t){if(Ra.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new fi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Xs.YAMLSet=fi;Xs.set=yN});var ec=C(Aa=>{"use strict";var NN=ji();function Zs(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 Sf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return NN.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 bN={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})=>Zs(e,i),stringify:Sf},kN={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=>Zs(e,!1),stringify:Sf},Ef={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(Ef.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=Zs(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$/,"")??""};Aa.floatTime=kN;Aa.intTime=bN;Aa.timestamp=Ef});var Cf=C(xf=>{"use strict";var SN=Ti(),EN=va(),PN=Ii(),xN=Dr(),CN=Vs(),Pf=yf(),tc=Nf(),_a=kf(),RN=ca(),AN=Gs(),_N=Sa(),TN=Qs(),ic=ec(),IN=[SN.map,PN.seq,xN.string,EN.nullTag,Pf.trueTag,Pf.falseTag,_a.intBin,_a.intOct,_a.int,_a.intHex,tc.floatNaN,tc.floatExp,tc.float,CN.binary,RN.merge,AN.omap,_N.pairs,TN.set,ic.intTime,ic.floatTime,ic.timestamp];xf.schema=IN});var Df=C(ac=>{"use strict";var Tf=Ti(),jN=va(),If=Ii(),$N=Dr(),ON=Os(),rc=Ds(),nc=Ls(),HN=of(),DN=lf(),jf=Vs(),qr=ca(),$f=Gs(),Of=Sa(),Rf=Cf(),Hf=Qs(),Ta=ec(),Af=new Map([["core",HN.schema],["failsafe",[Tf.map,If.seq,$N.string]],["json",DN.schema],["yaml11",Rf.schema],["yaml-1.1",Rf.schema]]),_f={binary:jf.binary,bool:ON.boolTag,float:rc.float,floatExp:rc.floatExp,floatNaN:rc.floatNaN,floatTime:Ta.floatTime,int:nc.int,intHex:nc.intHex,intOct:nc.intOct,intTime:Ta.intTime,map:Tf.map,merge:qr.merge,null:jN.nullTag,omap:$f.omap,pairs:Of.pairs,seq:If.seq,set:Hf.set,timestamp:Ta.timestamp},BN={"tag:yaml.org,2002:binary":jf.binary,"tag:yaml.org,2002:merge":qr.merge,"tag:yaml.org,2002:omap":$f.omap,"tag:yaml.org,2002:pairs":Of.pairs,"tag:yaml.org,2002:set":Hf.set,"tag:yaml.org,2002:timestamp":Ta.timestamp};function LN(e,t,i){let r=Af.get(t);if(r&&!e)return i&&!r.includes(qr.merge)?r.concat(qr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Af.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(qr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?_f[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(_f).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},[])}ac.coreKnownTags=BN;ac.getTags=LN});var cc=C(Bf=>{"use strict";var oc=F(),FN=Ti(),MN=Ii(),qN=Dr(),Ia=Df(),VN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,sc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ia.getTags(t,"compat"):t?Ia.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ia.coreKnownTags:{},this.tags=Ia.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,oc.MAP,{value:FN.map}),Object.defineProperty(this,oc.SCALAR,{value:qN.string}),Object.defineProperty(this,oc.SEQ,{value:MN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?VN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Bf.Schema=sc});var Ff=C(Lf=>{"use strict";var WN=F(),lc=$r(),Vr=_r();function zN(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=lc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Vr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(WN.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Vr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=lc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Vr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(lc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=ka.isPair(r)?r:new Ws.Pair(r)}}else t("Expected a sequence for this tag");return e}function ff(e,t,i){let{replacer:r}=i,n=new sN.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(Ws.createPair(s,c,i))}return n}var cN={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:df,createNode:ff};Sa.createPairs=ff;Sa.pairs=cN;Sa.resolvePairs=df});var Gs=C(Js=>{"use strict";var pf=F(),zs=At(),Lr=Ot(),lN=Ht(),hf=Ea(),di=class e extends lN.YAMLSeq{constructor(){super(),this.add=Lr.YAMLMap.prototype.add.bind(this),this.delete=Lr.YAMLMap.prototype.delete.bind(this),this.get=Lr.YAMLMap.prototype.get.bind(this),this.has=Lr.YAMLMap.prototype.has.bind(this),this.set=Lr.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(pf.isPair(n)?(a=zs.toJS(n.key,"",i),o=zs.toJS(n.value,a,i)):a=zs.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=hf.createPairs(t,i,r),a=new this;return a.items=n.items,a}};di.tag="tag:yaml.org,2002:omap";var uN={collection:"seq",identify:e=>e instanceof Map,nodeClass:di,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=hf.resolvePairs(e,t),r=[];for(let{key:n}of i.items)pf.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new di,i)},createNode:(e,t,i)=>di.from(e,t,i)};Js.YAMLOMap=di;Js.omap=uN});var yf=C(Us=>{"use strict";var mf=ie();function vf({value:e,source:t},i){return t&&(e?gf:wf).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var gf={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 mf.Scalar(!0),stringify:vf},wf={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 mf.Scalar(!1),stringify:vf};Us.falseTag=wf;Us.trueTag=gf});var Nf=C(Pa=>{"use strict";var dN=ie(),Ks=ji(),fN={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:Ks.stringifyNumber},pN={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():Ks.stringifyNumber(e)}},hN={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 dN.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:Ks.stringifyNumber};Pa.float=hN;Pa.floatExp=pN;Pa.floatNaN=fN});var kf=C(Mr=>{"use strict";var bf=ji(),Fr=e=>typeof e=="bigint"||Number.isInteger(e);function xa(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 Ys(e,t,i){let{value:r}=e;if(Fr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return bf.stringifyNumber(e)}var mN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>xa(e,2,2,i),stringify:e=>Ys(e,2,"0b")},vN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>xa(e,1,8,i),stringify:e=>Ys(e,8,"0")},gN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>xa(e,0,10,i),stringify:bf.stringifyNumber},wN={identify:Fr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>xa(e,2,16,i),stringify:e=>Ys(e,16,"0x")};Mr.int=gN;Mr.intBin=mN;Mr.intHex=wN;Mr.intOct=vN});var Qs=C(Xs=>{"use strict";var Aa=F(),Ca=jt(),Ra=Ot(),fi=class e extends Ra.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Aa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Ca.Pair(t.key,null):i=new Ca.Pair(t,null),Ra.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Ra.findPair(this.items,t);return!i&&Aa.isPair(r)?Aa.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=Ra.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Ca.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(Ca.createPair(o,null,r));return a}};fi.tag="tag:yaml.org,2002:set";var yN={collection:"map",identify:e=>e instanceof Set,nodeClass:fi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>fi.from(e,t,i),resolve(e,t){if(Aa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new fi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Xs.YAMLSet=fi;Xs.set=yN});var ec=C(_a=>{"use strict";var NN=ji();function Zs(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 Sf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return NN.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 bN={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})=>Zs(e,i),stringify:Sf},kN={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=>Zs(e,!1),stringify:Sf},Ef={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(Ef.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=Zs(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$/,"")??""};_a.floatTime=kN;_a.intTime=bN;_a.timestamp=Ef});var Cf=C(xf=>{"use strict";var SN=Ii(),EN=ga(),PN=Ti(),xN=Dr(),CN=Vs(),Pf=yf(),tc=Nf(),Ia=kf(),RN=la(),AN=Gs(),_N=Ea(),IN=Qs(),ic=ec(),TN=[SN.map,PN.seq,xN.string,EN.nullTag,Pf.trueTag,Pf.falseTag,Ia.intBin,Ia.intOct,Ia.int,Ia.intHex,tc.floatNaN,tc.floatExp,tc.float,CN.binary,RN.merge,AN.omap,_N.pairs,IN.set,ic.intTime,ic.floatTime,ic.timestamp];xf.schema=TN});var Df=C(ac=>{"use strict";var If=Ii(),jN=ga(),Tf=Ti(),$N=Dr(),ON=Os(),rc=Ds(),nc=Ls(),HN=of(),DN=lf(),jf=Vs(),qr=la(),$f=Gs(),Of=Ea(),Rf=Cf(),Hf=Qs(),Ta=ec(),Af=new Map([["core",HN.schema],["failsafe",[If.map,Tf.seq,$N.string]],["json",DN.schema],["yaml11",Rf.schema],["yaml-1.1",Rf.schema]]),_f={binary:jf.binary,bool:ON.boolTag,float:rc.float,floatExp:rc.floatExp,floatNaN:rc.floatNaN,floatTime:Ta.floatTime,int:nc.int,intHex:nc.intHex,intOct:nc.intOct,intTime:Ta.intTime,map:If.map,merge:qr.merge,null:jN.nullTag,omap:$f.omap,pairs:Of.pairs,seq:Tf.seq,set:Hf.set,timestamp:Ta.timestamp},BN={"tag:yaml.org,2002:binary":jf.binary,"tag:yaml.org,2002:merge":qr.merge,"tag:yaml.org,2002:omap":$f.omap,"tag:yaml.org,2002:pairs":Of.pairs,"tag:yaml.org,2002:set":Hf.set,"tag:yaml.org,2002:timestamp":Ta.timestamp};function LN(e,t,i){let r=Af.get(t);if(r&&!e)return i&&!r.includes(qr.merge)?r.concat(qr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Af.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(qr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?_f[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(_f).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},[])}ac.coreKnownTags=BN;ac.getTags=LN});var cc=C(Bf=>{"use strict";var oc=F(),FN=Ii(),MN=Ti(),qN=Dr(),ja=Df(),VN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,sc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ja.getTags(t,"compat"):t?ja.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?ja.coreKnownTags:{},this.tags=ja.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,oc.MAP,{value:FN.map}),Object.defineProperty(this,oc.SCALAR,{value:qN.string}),Object.defineProperty(this,oc.SEQ,{value:MN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?VN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Bf.Schema=sc});var Ff=C(Lf=>{"use strict";var WN=F(),lc=$r(),Vr=_r();function zN(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=lc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Vr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(WN.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Vr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=lc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Vr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(lc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
58
|
`)?(i.push("..."),i.push(Vr.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(Vr.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}Lf.stringifyDocument=zN});var Wr=C(Mf=>{"use strict";var JN=Rr(),$i=
|
|
60
|
+
`}Lf.stringifyDocument=zN});var Wr=C(Mf=>{"use strict";var JN=Rr(),$i=Zn(),_e=F(),GN=jt(),UN=At(),KN=cc(),YN=Ff(),uc=Kn(),XN=hs(),QN=Ar(),dc=ps(),fc=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,_e.NODE_TYPE,{value:_e.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 dc.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,{[_e.NODE_TYPE]:{value:_e.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=_e.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Oi(this.contents)&&this.contents.add(t)}addIn(t,i){Oi(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=uc.anchorNames(this);t.anchor=!i||r.has(i)?uc.findNewAnchor(i||"a",r):i}return new JN.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,b=i.filter(m).map(String);b.length>0&&(i=i.concat(b)),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}=uc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=QN.createNode(t,u,v);return s&&_e.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 GN.Pair(n,a)}delete(t){return Oi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return $i.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Oi(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return _e.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return $i.isEmptyPath(t)?!i&&_e.isScalar(this.contents)?this.contents.value:this.contents:_e.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return _e.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return $i.isEmptyPath(t)?this.contents!==void 0:_e.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=$i.collectionFromPath(this.schema,[t],i):Oi(this.contents)&&this.contents.set(t,i)}setIn(t,i){$i.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=$i.collectionFromPath(this.schema,Array.from(t),i):Oi(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 dc.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 dc.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 KN.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=UN.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"?XN.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 YN.stringifyDocument(this,t)}};function Oi(e){if(_e.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Mf.Document=fc});var Gr=C(Jr=>{"use strict";var zr=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},pc=class extends zr{constructor(t,i,r){super("YAMLParseError",t,i,r)}},hc=class extends zr{constructor(t,i,r){super("YAMLWarning",t,i,r)}},ZN=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};Jr.YAMLError=zr;Jr.YAMLParseError=pc;Jr.YAMLWarning=hc;Jr.prettifyError=ZN});var Ur=C(qf=>{"use strict";function eb(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,v=!1,p=null,m=null,b=null,y=null,E=null,k=null,P=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),p&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(p=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:(!k||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,h=!0,(m||b)&&(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,P??(P=w.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),b=w,P??(P=w.offset),l=!1,u=!1,v=!0;break}case i:(m||b)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),k&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),k=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 N=e[e.length-1],x=N?N.offset+N.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"),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:k,spaceBefore:c,comment:d,hasNewline:h,anchor:m,tag:b,newlineAfterProp:y,end:x,start:P??x}}qf.resolveProps=eb});var
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(mc(t.key)||mc(t.value))return!0}return!1;default:return!0}}Vf.containsNewline=mc});var vc=C(Wf=>{"use strict";var tb
|
|
65
|
+
`}};Jr.YAMLError=zr;Jr.YAMLParseError=pc;Jr.YAMLWarning=hc;Jr.prettifyError=ZN});var Ur=C(qf=>{"use strict";function eb(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,v=!1,p=null,m=null,b=null,y=null,E=null,k=null,P=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),p&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(p=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:(!k||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,h=!0,(m||b)&&(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,P??(P=w.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),b=w,P??(P=w.offset),l=!1,u=!1,v=!0;break}case i:(m||b)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),k&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),k=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 N=e[e.length-1],x=N?N.offset+N.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"),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:k,spaceBefore:c,comment:d,hasNewline:h,anchor:m,tag:b,newlineAfterProp:y,end:x,start:P??x}}qf.resolveProps=eb});var $a=C(Vf=>{"use strict";function mc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(mc(t.key)||mc(t.value))return!0}return!1;default:return!0}}Vf.containsNewline=mc});var vc=C(Wf=>{"use strict";var tb=$a();function ib(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&tb.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Wf.flowIndentCheck=ib});var gc=C(Jf=>{"use strict";var zf=F();function rb(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||zf.isScalar(a)&&zf.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Jf.mapIncludes=rb});var Qf=C(Xf=>{"use strict";var Gf=jt(),nb=Ot(),Uf=Ur(),ab=$a(),Kf=vc(),ob=gc(),Yf="All mapping items must start at the same column";function sb({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??nb.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:v}=u,p=Uf.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!p.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",Yf)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
|
|
67
67
|
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||ab.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",Yf);i.atKey=!0;let b=p.end,y=f?e(i,f,p,n):t(i,b,d,null,p,n);i.schema.compat&&Kf.flowIndentCheck(r.indent,f,n),i.atKey=!1,ob.mapIncludes(i,s.items,y)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let E=Uf.resolveProps(h??[],{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&&p.start<E.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(i,v,E,n):t(i,c,h,null,E,n);i.schema.compat&&Kf.flowIndentCheck(r.indent,v,n),c=k.range[2];let P=new Gf.Pair(y,k);i.options.keepSourceTokens&&(P.srcToken=u),s.items.push(P)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),E.comment&&(y.comment?y.comment+=`
|
|
68
|
-
`+E.comment:y.comment=E.comment);let k=new Gf.Pair(y);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Xf.resolveBlockMap=sb});var ep=C(Zf=>{"use strict";var cb=Ht(),lb=Ur(),ub=vc();function db({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??cb.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=lb.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&&ub.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Zf.resolveBlockSeq=db});var Hi=C(tp=>{"use strict";function fb(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}}tp.resolveEnd=fb});var ap=C(np=>{"use strict";var pb=F(),hb=jt(),ip=Ot(),mb=Ht(),vb=Hi(),rp=Ur(),gb
|
|
68
|
+
`+E.comment:y.comment=E.comment);let k=new Gf.Pair(y);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Xf.resolveBlockMap=sb});var ep=C(Zf=>{"use strict";var cb=Ht(),lb=Ur(),ub=vc();function db({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??cb.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=lb.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&&ub.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Zf.resolveBlockSeq=db});var Hi=C(tp=>{"use strict";function fb(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}}tp.resolveEnd=fb});var ap=C(np=>{"use strict";var pb=F(),hb=jt(),ip=Ot(),mb=Ht(),vb=Hi(),rp=Ur(),gb=$a(),wb=gc(),wc="Block collections are not allowed within flow collections",yc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function yb({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?ip.YAMLMap:mb.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<r.items.length;++m){let b=r.items[m],{start:y,key:E,sep:k,value:P}=b,N=rp.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:E??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!k&&!P){m===0&&N.comma?n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),N.comment&&(l.comment?l.comment+=`
|
|
69
69
|
`+N.comment:l.comment=N.comment),d=N.end;continue}!o&&i.options.strict&&gb.containsNewline(E)&&n(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)N.comma&&n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(N.comma||n(N.start,"MISSING_CHAR",`Missing , between ${s} items`),N.comment){let x="";e:for(let w of y)switch(w.type){case"comma":case"space":break;case"comment":x=w.source.substring(1);break e;default:break e}if(x){let w=l.items[l.items.length-1];pb.isPair(w)&&(w=w.value??w.key),w.comment?w.comment+=`
|
|
70
|
-
`+x:w.comment=x,N.comment=N.comment.substring(x.length+1)}}if(!o&&!k&&!N.found){let x=P?e(i,P,N,n):t(i,N.end,k,null,N,n);l.items.push(x),d=x.range[2],yc(P)&&n(x.range,"BLOCK_IN_FLOW",wc)}else{i.atKey=!0;let x=N.end,w=E?e(i,E,N,n):t(i,x,y,null,N,n);yc(E)&&n(w.range,"BLOCK_IN_FLOW",wc),i.atKey=!1;let g=rp.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:P,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(g.found){if(!o&&!N.found&&i.options.strict){if(k)for(let
|
|
71
|
-
`+g.comment:w.comment=g.comment);let $=new hb.Pair(w,S);if(i.options.keepSourceTokens&&($.srcToken=b),o){let
|
|
70
|
+
`+x:w.comment=x,N.comment=N.comment.substring(x.length+1)}}if(!o&&!k&&!N.found){let x=P?e(i,P,N,n):t(i,N.end,k,null,N,n);l.items.push(x),d=x.range[2],yc(P)&&n(x.range,"BLOCK_IN_FLOW",wc)}else{i.atKey=!0;let x=N.end,w=E?e(i,E,N,n):t(i,x,y,null,N,n);yc(E)&&n(w.range,"BLOCK_IN_FLOW",wc),i.atKey=!1;let g=rp.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:P,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(g.found){if(!o&&!N.found&&i.options.strict){if(k)for(let T of k){if(T===g.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<g.found.offset-1024&&n(g.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else P&&("source"in P&&P.source?.[0]===":"?n(P,"MISSING_CHAR",`Missing space after : in ${s}`):n(g.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let S=P?e(i,P,g,n):g.found?t(i,g.end,k,null,g,n):null;S?yc(P)&&n(S.range,"BLOCK_IN_FLOW",wc):g.comment&&(w.comment?w.comment+=`
|
|
71
|
+
`+g.comment:w.comment=g.comment);let $=new hb.Pair(w,S);if(i.options.keepSourceTokens&&($.srcToken=b),o){let T=l;wb.mapIncludes(i,T.items,w)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),T.items.push($)}else{let T=new ip.YAMLMap(i.schema);T.flow=!0,T.items.push($);let fe=(S??w).range;T.range=[w.range[0],fe[1],fe[2]],l.items.push(T)}d=S?S.range[2]:g.end}}let f=o?"}":"]",[h,...v]=r.end,p=d;if(h?.source===f)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),b=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",b),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=vb.resolveEnd(v,p,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
72
72
|
`+m.comment:l.comment=m.comment),l.range=[r.offset,p,m.offset]}else l.range=[r.offset,p,p];return l}np.resolveFlowCollection=yb});var sp=C(op=>{"use strict";var Nb=F(),bb=ie(),kb=Ot(),Sb=Ht(),Eb=Qf(),Pb=ep(),xb=ap();function Nc(e,t,i,r,n,a){let o=i.type==="block-map"?Eb.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Pb.resolveBlockSeq(e,t,i,r,a):xb.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 Cb(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,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===kb.YAMLMap.tagName&&s==="map"||o===Sb.YAMLSeq.tagName&&s==="seq")return Nc(e,t,i,n,o);let c=t.schema.tags.find(f=>f.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),Nc(e,t,i,n,o)}let l=Nc(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Nb.isNode(u)?u:new bb.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}op.composeCollection=Cb});var kc=C(cp=>{"use strict";var bc=ie();function Rb(e,t,i){let r=t.offset,n=Ab(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?bc.Scalar.BLOCK_FOLDED:bc.Scalar.BLOCK_LITERAL,o=t.source?_b(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:p,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let p=0;p<s;++p){let[m,b]=o[p];if(b===""||b==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=p,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+b.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let d="",f="",h=!1;for(let p=0;p<u;++p)d+=o[p][0].slice(c)+`
|
|
74
74
|
`;for(let p=u;p<s;++p){let[m,b]=o[p];l+=m.length+b.length+1;let y=b[b.length-1]==="\r";if(y&&(b=b.slice(0,-1)),b&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(y?2:1),"BAD_INDENT",k),m=""}a===bc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+b,f=`
|
|
@@ -84,7 +84,7 @@ ${l}
|
|
|
84
84
|
`+o[p][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Ab({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<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function _b(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}cp.resolveBlockScalar=Rb});var Ec=C(up=>{"use strict";var Sc=ie(),
|
|
87
|
+
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Ab({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<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function _b(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}cp.resolveBlockScalar=Rb});var Ec=C(up=>{"use strict";var Sc=ie(),Ib=Hi();function Tb(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=Sc.Scalar.PLAIN,c=jb(a,l);break;case"single-quoted-scalar":s=Sc.Scalar.QUOTE_SINGLE,c=$b(a,l);break;case"double-quoted-scalar":s=Sc.Scalar.QUOTE_DOUBLE,c=Ob(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=Ib.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function jb(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}`),lp(e)}function $b(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),lp(e.slice(1,-1)).replace(/''/g,"'")}function lp(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
@@ -99,14 +99,14 @@ ${l}
|
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
101
|
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Db={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Bb(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}}up.resolveFlowScalar=
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Bb(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}}up.resolveFlowScalar=Tb});var pp=C(fp=>{"use strict";var pi=F(),dp=ie(),Lb=kc(),Fb=Ec();function Mb(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Lb.resolveBlockScalar(e,t,r):Fb.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[pi.SCALAR]:c?l=qb(e.schema,n,c,i,r):t.type==="scalar"?l=Vb(e,n,t,r):l=e.schema[pi.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=pi.isScalar(d)?d:new dp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new dp.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 qb(e,t,i,r,n){if(i==="!")return e[pi.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[pi.SCALAR])}function Vb({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[pi.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[pi.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}fp.composeScalar=Mb});var mp=C(hp=>{"use strict";function Wb(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}hp.emptyScalarPosition=Wb});var wp=C(xc=>{"use strict";var zb=Rr(),Jb=F(),Gb=sp(),vp=pp(),Ub=Hi(),Kb=mp(),Yb={composeNode:gp,composeEmptyNode:Pc};function gp(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=Xb(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=vp.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Gb.composeCollection(Yb,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=Pc(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&&(!Jb.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 Pc(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Kb.emptyScalarPosition(t,i,r),indent:-1,source:""},d=vp.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 Xb({options:e},{offset:t,source:i,end:r},n){let a=new zb.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=Ub.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}xc.composeEmptyNode=Pc;xc.composeNode=gp});var bp=C(Np=>{"use strict";var Qb=Wr(),yp=wp(),Zb=Hi(),ek=Ur();function tk(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Qb.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=ek.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?yp.composeNode(l,n,u,o):yp.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Zb.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Np.composeDoc=tk});var Rc=C(Ep=>{"use strict";var ik=Wn("process"),rk=ps(),nk=Wr(),Kr=Gr(),kp=F(),ak=bp(),ok=Hi();function Yr(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 Sp(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
105
|
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Cc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Yr(i);a?this.warnings.push(new Kr.YAMLWarning(o,r,n)):this.errors.push(new Kr.YAMLParseError(o,r,n))},this.directives=new rk.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Sp(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
106
|
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(kp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];kp.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
108
|
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Sp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(ik.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Yr(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=ak.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 Kr.YAMLParseError(Yr(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 Kr.YAMLParseError(Yr(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=ok.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Kr.YAMLParseError(Yr(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 nk.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}}};Ep.Composer=Cc});var Cp=C(
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Kr.YAMLParseError(Yr(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 nk.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}}};Ep.Composer=Cc});var Cp=C(Oa=>{"use strict";var sk=kc(),ck=Ec(),lk=Gr(),Pp=jr();function uk(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 lk.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ck.resolveFlowScalar(e,t,r);case"block-scalar":return sk.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function dk(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Pp.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
112
|
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return xp(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
@@ -114,10 +114,10 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+1)+`
|
|
115
115
|
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];xp(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
116
|
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function xp(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 Ac(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Oa.createScalarToken=dk;Oa.resolveAsScalar=uk;Oa.setScalarValue=fk});var Ap=C(Rp=>{"use strict";var hk=e=>"type"in e?Da(e):Ha(e);function Da(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Da(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ha(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ha(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ha(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 Ha({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Da(t)),i)for(let a of i)n+=a.source;return r&&(n+=Da(r)),n}Rp.stringify=hk});var jp=C(Tp=>{"use strict";var _c=Symbol("break visit"),mk=Symbol("skip children"),_p=Symbol("remove item");function hi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Ip(Object.freeze([]),e,t)}hi.BREAK=_c;hi.SKIP=mk;hi.REMOVE=_p;hi.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};hi.parentCollection=(e,t)=>{let i=hi.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 Ip(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Ip(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===_c)return _c;s===_p&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Tp.visit=hi});var Ba=C(we=>{"use strict";var Ic=Cp(),vk=Ap(),gk=jp(),Tc="\uFEFF",jc="",$c="",Oc="",wk=e=>!!e&&"items"in e,yk=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Nk(e){switch(e){case Tc:return"<BOM>";case jc:return"<DOC>";case $c:return"<FLOW_END>";case Oc:return"<SCALAR>";default:return JSON.stringify(e)}}function bk(e){switch(e){case Tc:return"byte-order-mark";case jc:return"doc-mode";case $c:return"flow-error-end";case Oc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}we.createScalarToken=
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var $p=new Set("0123456789ABCDEFabcdef"),kk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}we.createScalarToken=Ic.createScalarToken;we.resolveAsScalar=Ic.resolveAsScalar;we.setScalarValue=Ic.setScalarValue;we.stringify=vk.stringify;we.visit=gk.visit;we.BOM=Tc;we.DOCUMENT=jc;we.FLOW_END=$c;we.SCALAR=Oc;we.isCollection=wk;we.isScalar=yk;we.prettyToken=Nk;we.tokenType=bk});var Bc=C(Op=>{"use strict";var Xr=Ba();function We(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var $p=new Set("0123456789ABCDEFabcdef"),kk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),La=new Set(",[]{}"),Sk=new Set(` ,[]{}
|
|
121
121
|
\r `),Hc=e=>!e||Sk.has(e),Dc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
@@ -130,53 +130,53 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
130
130
|
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Xr.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(We(a)||t&&
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Xr.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(We(a)||t&&La.has(a))break;i=r}else if(We(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
|
-
`,a=this.buffer[r+1]):i=r),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&La.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&La.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Xr.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(Hc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(We(r)||i&&La.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(;!We(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(kk.has(i))i=this.buffer[++t];else if(i==="%"&&$p.has(this.buffer[t+1])&&$p.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Op.Lexer=Dc});var Fc=C(Hp=>{"use strict";var Lc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Hp.LineCounter=Lc});var qc=C(Mp=>{"use strict";var Ek=
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Op.Lexer=Dc});var Fc=C(Hp=>{"use strict";var Lc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Hp.LineCounter=Lc});var qc=C(Mp=>{"use strict";var Ek=Wn("process"),Dp=Ba(),Pk=Bc();function Dt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Bp(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Fp(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Fa(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Di(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Ma(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function Lp(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Dt(t.start,"explicit-key-ind")&&!Dt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Fp(t.value)?t.value.end?Ma(t.value.end,t.sep):t.value.end=t.sep:Ma(t.start,t.sep),delete t.sep)}var Mc=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Pk.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,Ek.env.LOG_TOKENS&&console.log("|",Dp.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Dp.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Lp(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&&Bp(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Bp(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=Fa(this.peek(2)),r=Di(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Ma(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Dt(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(Fp(i.key)&&!Dt(i.sep,"newline")){let o=Di(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(Dt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Di(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]}):Dt(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&&!Dt(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)){Ma(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||Dt(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=Fa(r),a=Di(n);Lp(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=
|
|
143
|
-
${Sr(t)}`).digest("hex")}var Ll=br(Bi(),1);import{promises as hm}from"fs";import bt from"path";import{createHash as Uk}from"node:crypto";import{promises as ze}from"node:fs";import Ie from"node:path";import{TextDecoder as Kk}from"node:util";import Wc from"path";var zk=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Jk=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Gk(e){return e.toLowerCase().startsWith(".env")}function at(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Gk(r))?"environment-file":i.some(r=>Jk.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>zk.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function zc(e,t){let i=at(t);if(i)return i;let r=Wc.resolve(e.projectRoot,...t.split("/")),n=Wc.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Wc.resolve(e.configFile)?"native-runtime":null}function Lt(e){return e!==0&&e!==0n&&e!=="0"}function Te(e,t){return Lt(e.dev)&&Lt(t.dev)&&Lt(e.ino)&&Lt(t.ino)}function W(e,t){let i=Lt(e.dev)&&Lt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Lt(e.ino)&&Lt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var en=1024*1024;function Jc(e,t){let i=Ie.relative(e,t);return i===""||!Ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ie.sep}`)}function Yk(e){let t=Ie.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})||Ie.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=at(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 Xk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Qk(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qa(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Te(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Up(e){let t=await ze.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ze.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Zk(e,t){let i=Ie.resolve(e),r=Ie.resolve(t);if(!Jc(i,r))throw new Error("Native artifact path is outside its root");let n=[await Up(i)],a=i;for(let o of Ie.relative(i,r).split(Ie.sep).filter(Boolean)){a=Ie.join(a,o);let s=await Up(a);if(!Jc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Kp(e){for(let t of e){let i=await ze.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Qk(t,i)||await ze.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function oe(e){let t=Yk(e.ref),i=e.maxBytes===null?null:Xk(e.maxBytes??en),r=Ie.resolve(e.root,...t.split("/")),n=await Zk(e.root,Ie.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await ze.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 ze.realpath(r);if(!Jc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ze.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),ze.lstat(r),ze.realpath(r)]);if(await Kp(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!qa(a,c)||!qa(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,k=await s.read(h,0,Math.min(h.length,E),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),ze.lstat(r),ze.realpath(r)]);if(await Kp(n),!p.isFile()||p.isSymbolicLink()||m!==o||!qa(c,v)||!qa(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),y;try{y=new Kk("utf-8",{fatal:!0}).decode(b)}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:Uk("sha256").update(b).digest("hex"),text:y}}finally{await s.close()}}var Uc=br(Bi(),1);import Li from"path";var tn=64*1024,Va=1024,Wa=64,Qp=5,eS=12e4,Yp=6e5,tS=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],iS=["**/.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"],rS=[...tS,...iS].sort((e,t)=>e.localeCompare(t,"en"));var Je={include:["**/*"],exclude:[...rS],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function nS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Li.posix.isAbsolute(i)||Li.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 Fi(e){let t=nS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Zp(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 za(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||Li.posix.isAbsolute(r)||Li.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 Ft(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function eh(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 Ja(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>Va)throw new Error(`${t} exceeds ${Va} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Wa)throw new Error(`${t} contains more than ${Wa} wildcard tokens`);return e}function Xp(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=>Ja(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Gc(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 aS(e){if(e===void 0)return{...Je,include:[...Je.include],exclude:[...Je.exclude]};let t=Ft(e,"native.snapshot");return{include:Xp(t.include,"native.snapshot.include",Je.include),exclude:Xp(t.exclude,"native.snapshot.exclude",Je.exclude),max_files:Gc(t.max_files,Je.max_files,"native.snapshot.max_files"),max_total_bytes:Gc(t.max_total_bytes,Je.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Gc(t.max_duration_ms,Je.max_duration_ms,"native.snapshot.max_duration_ms")}}function oS(e){if(e===void 0)return;let t=Ft(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=Ft(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:Fi(r),toArtifactRoot:Fi(n),stage:a,...o?{cleanup:o}:{}}}function sS(e){if(e===void 0)return;let t=Ft(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ft(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Li.posix.isAbsolute(r[0])||Li.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??eS;if(!Number.isSafeInteger(n)||n<1||n>Yp)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Yp}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function cS(e,t={}){let i=Ft(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??Qp;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=oS(i.pending_root_move),c=sS(i.finish);return{artifact_root:Fi(r),language:eh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:aS(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function lS(e){let t=Ft(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:Zp(t.artifact_layout),language:eh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function uS(e){let i=Ft(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)=>za(r,`hook.allow_paths[${n}]`)))]}}function dS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function fS(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 rn(e,t={}){let i=(0,Uc.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=dS(n.ambient_resume),o=n.hook===void 0?void 0:uS(n.hook),s=n.native===void 0?void 0:cS(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:lS(n.classic),l=fS(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}:{}}}import{createHash as hS}from"crypto";import{promises as Ka}from"fs";import Mt from"path";import{constants as Ga,promises as mi}from"fs";var ot=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Kc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function th(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function nn(e){return{dev:e.dev,ino:e.ino,birthtime:Kc(e)}}function Ua(e,t){let i=nn(e),r=nn(t);return Te(i,r)?W(i,r):W(i,r)&&Kc(e)===Kc(t)&&th(e)===th(t)&&e.size===t.size}async function Mi(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 mi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ot("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ot("too-large",`${r} exceeds ${t} bytes`);let o=await mi.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:nn(a)});let s=process.platform==="win32"?Ga.O_RDONLY:Ga.O_RDONLY|Ga.O_NOFOLLOW|Ga.O_NONBLOCK,c;try{c=await mi.open(e,s)}catch(l){throw l.code==="ELOOP"?new ot("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),mi.lstat(e,{bigint:n}),mi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ua(a,l)||!Ua(a,u))throw new ot("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:nn(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:E}=await c.read(v,0,Math.min(v.length,y),null);if(E===0)break;if(h+=E,h>t)throw new ot("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([c.stat({bigint:n}),mi.lstat(e,{bigint:n}),mi.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||b!==o||!Ua(a,p)||!Ua(a,m))throw new ot("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:nn(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:b}}finally{await c.close()}}function pS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Yc(e,t){let i=Mt.relative(e,t);return i===""||!Mt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Mt.sep}`)}async function ih(e,t){let i=Mt.resolve(e),r=await Ka.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ka.realpath(i)}async function rh(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Mt.join(n,i[a]);let o;try{o=await Ka.lstat(n)}catch(u){if(pS(u))return{exists:!1,kind:"missing"};throw u}let s=Mt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Ka.realpath(n);if(!Yc(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function qi(e,t,i){let r=za(t,i.label),n=Mt.resolve(e),a=await ih(n,i.label),o=r.split("/"),s=Mt.resolve(n,...o);if(!Yc(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await rh(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function qt(e,t,i,r){let n=await qi(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await ih(n.projectRoot,r.label);return Mi(n.target,i,{...r,verify:async(o,s)=>{if(!Yc(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await rh(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var an=".comet/config.yaml";function mS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ya(e,t={}){return(await Xa(e,t)).document}async function vS(e){try{return(await qt(e,an,tn,{label:an})).bytes}catch(t){if(mS(t))return null;throw t}}function gS(e){return e?{exists:!0,sha256:hS("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Xa(e,t={}){let i=await vS(e);return{document:i?rn(i.toString("utf8"),t):null,identity:gS(i)}}async function Xc(e){return(await Ya(e))?.config??null}var WI=16*1024;import{existsSync as ah,promises as Vt}from"fs";import q from"path";import kS from"os";var il=".comet/config.yaml",SS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function el(e){try{return await Vt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ES(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 Wi(e,t){let i=q.relative(e,t);return i===""||!q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${q.sep}`)}async function Vi(e){let t=[],i=e;for(;!await el(i);){let n=q.dirname(i);if(n===i)break;t.push(q.basename(i)),i=n}let r=await Vt.realpath(i);return q.resolve(r,...t.reverse())}async function tl(e){try{return(await Vt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function rl(e){let t=q.resolve(e);try{(await Vt.stat(t)).isDirectory()||(t=q.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=q.resolve(kS.homedir());for(;;){if(!(t===r&&i!==r)){let o=q.join(t,...il.split("/")),s=t===i||await ES(o);if(await el(o)&&s)return t}if(await el(q.join(t,".git")))return t;let a=q.dirname(t);if(a===t)return i;t=a}}function nl(e){return Fi(e)}async function PS(e,t){let i=nl(t),r=q.resolve(e,...i.split("/")),n=await Vt.realpath(e),a=await Vi(r);if(!Wi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function vt(e,t){let i=nl(t),r=await PS(e,i),n=q.join(r,"comet");if(await tl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Vi(r),Vi(n)]);if(!Wi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=q.resolve(e),c=q.join(s,".comet","runtime","native");if(await tl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Vt.realpath(s),Vi(c)]);if(!Wi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:q.join(e,...il.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:q.join(n,"specs"),changesDir:q.join(n,"changes"),archiveDir:q.join(n,"archive"),runtimeDir:c,changesRuntimeDir:q.join(c,"changes"),locksDir:q.join(c,"locks"),transactionsDir:q.join(c,"transactions")}}function sh(e){if(!SS.test(e))throw new Error(`Invalid Native change name: ${e}`)}function zi(e,t){sh(t);let i=q.join(e.changesRuntimeDir,t);if(!L(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function ch(e,t){sh(t);let i=q.join(e.changesDir,t,"runtime");if(!L(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function G(e,t){let i=zi(e,t);if(ah(i))return i;let r=ch(e,t);return ah(r)?r:i}async function oh(e){try{let t=await Vt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function al(e,t){let i=zi(e,t),r=ch(e,t),[n,a]=await Promise.all([oh(i),oh(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 Wt(e,t){if(!t.startsWith("runtime/")||q.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=q.resolve(e,...t.slice(8).split("/"));if(!L(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function se(e,t){let i=q.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 Wi(q.resolve(e),q.resolve(t))}async function z(e,t){let i=q.resolve(e),r=q.resolve(t);if(!Wi(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await tl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Vi(i),Vi(r)]);if(!Wi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var ol=Je;var Qa=Ja;async function Pe(e){let t=(await Ya(e))?.config??null;return t?.native?t:null}import{AsyncLocalStorage as CS}from"async_hooks";var mj=16*1024;var vj=new CS;import uh from"node:path";var RS="comet.native.acceptance.v1",AS=/^acceptance-[a-f0-9]{64}$/u,_S=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),TS=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,IS=/^[a-f0-9]{64}$/u,jS=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function $S(e,t){return e<t?-1:e>t?1:0}var gt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),sn=Object.freeze({maxCriteria:1024}),dh="<!-- comet-native:acceptance-evidence:start -->",fh="<!-- comet-native:acceptance-evidence:end -->";function ph(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 hh(e,t){let i=t.toString(36),r=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function OS(e){if(!IS.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=jS.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]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function HS(e,t){let i=ph(e.text,gt.maxTextBytes),r=e.context.slice(0,gt.maxContextItems).map(n=>ph(n,gt.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 vh(e){let t=OS({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort($S),n=r.slice(0,gt.maxFailedCheckIds),a=e.criteria.slice(t,t+gt.maxItems);for(let c of a){let l=[...i,HS(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:u<e.criteria.length?hh(e.acceptanceHash,u):null,limits:{...gt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>gt.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:o<e.criteria.length?hh(e.acceptanceHash,o):null,limits:{...gt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>gt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function cl(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 sl(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 mh(e){return e.includes("-->")||e.includes("--!>")}function*Ji(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
142
|
+
`,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Fa(t),r=Di(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=Fa(t),r=Di(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())}}};Mp.Parser=Mc});var Jp=C(Zr=>{"use strict";var qp=Rc(),xk=Wr(),Qr=Gr(),Ck=xs(),Rk=F(),Ak=Fc(),Vp=qc();function Wp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ak.LineCounter||null,prettyErrors:t}}function _k(e,t={}){let{lineCounter:i,prettyErrors:r}=Wp(t),n=new Vp.Parser(i?.addNewLine),a=new qp.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Qr.prettifyError(e,i)),s.warnings.forEach(Qr.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function zp(e,t={}){let{lineCounter:i,prettyErrors:r}=Wp(t),n=new Vp.Parser(i?.addNewLine),a=new qp.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 Qr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Qr.prettifyError(e,i)),o.warnings.forEach(Qr.prettifyError(e,i))),o}function Ik(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=zp(e,i);if(!n)return null;if(n.warnings.forEach(a=>Ck.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 Tk(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 Rk.isDocument(e)&&!r?e.toString(i):new xk.Document(e,r,i).toString(i)}Zr.parse=Ik;Zr.parseAllDocuments=_k;Zr.parseDocument=zp;Zr.stringify=Tk});var Bi=C(V=>{"use strict";var jk=Rc(),$k=Wr(),Ok=cc(),Vc=Gr(),Hk=Rr(),Bt=F(),Dk=jt(),Bk=ie(),Lk=Ot(),Fk=Ht(),Mk=Ba(),qk=Bc(),Vk=Fc(),Wk=qc(),qa=Jp(),Gp=Er();V.Composer=jk.Composer;V.Document=$k.Document;V.Schema=Ok.Schema;V.YAMLError=Vc.YAMLError;V.YAMLParseError=Vc.YAMLParseError;V.YAMLWarning=Vc.YAMLWarning;V.Alias=Hk.Alias;V.isAlias=Bt.isAlias;V.isCollection=Bt.isCollection;V.isDocument=Bt.isDocument;V.isMap=Bt.isMap;V.isNode=Bt.isNode;V.isPair=Bt.isPair;V.isScalar=Bt.isScalar;V.isSeq=Bt.isSeq;V.Pair=Dk.Pair;V.Scalar=Bk.Scalar;V.YAMLMap=Lk.YAMLMap;V.YAMLSeq=Fk.YAMLSeq;V.CST=Mk;V.Lexer=qk.Lexer;V.LineCounter=Vk.LineCounter;V.Parser=Wk.Parser;V.parse=qa.parse;V.parseAllDocuments=qa.parseAllDocuments;V.parseDocument=qa.parseDocument;V.stringify=qa.stringify;V.visit=Gp.visit;V.visitAsync=Gp.visitAsync});import ci from"node:path";import{realpathSync as x_}from"node:fs";import{execFileSync as pw}from"child_process";import kr from"path";function Pi(e,t){return pw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function hw(e,t){let i=kr.normalize(e),r=kr.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Me(e){try{let t=kr.resolve(Pi(e,["rev-parse","--show-toplevel"])),r=Pi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?kr.resolve(r.slice(9)):t,a=null;try{a=Pi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!hw(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function nd(e){try{Pi(e,["rev-parse","--is-inside-work-tree"]);let t=Pi(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:kr.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 xi(e){return nd(e).map(t=>t.root)}function cs(e,t){try{let i=Pi(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 mw}from"crypto";function qe(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function vw(e,t){t.has(e)&&qe("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||qe("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&qe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&qe("symbol properties are not supported"),`[${e.map(r=>ls(r,t)).join(",")}]`}finally{t.delete(e)}}function gw(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&qe("only plain objects are supported"),t.has(e)&&qe("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&qe("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))&&qe("accessor properties are not supported"),`${JSON.stringify(o)}:${ls(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ls(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)||qe("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?vw(e,t):gw(e,t);case"bigint":case"function":case"symbol":case"undefined":return qe(`${typeof e} values are not supported`)}return qe("unsupported value type")}function Sr(e){return ls(e,new Set)}function j(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 mw("sha256").update(`${e}
|
|
143
|
+
${Sr(t)}`).digest("hex")}var Ll=br(Bi(),1);import{promises as hm}from"fs";import bt from"path";import{createHash as Uk}from"node:crypto";import{promises as ze}from"node:fs";import Te from"node:path";import{TextDecoder as Kk}from"node:util";import Wc from"path";var zk=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Jk=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Gk(e){return e.toLowerCase().startsWith(".env")}function at(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Gk(r))?"environment-file":i.some(r=>Jk.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>zk.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function zc(e,t){let i=at(t);if(i)return i;let r=Wc.resolve(e.projectRoot,...t.split("/")),n=Wc.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Wc.resolve(e.configFile)?"native-runtime":null}function Lt(e){return e!==0&&e!==0n&&e!=="0"}function Ie(e,t){return Lt(e.dev)&&Lt(t.dev)&&Lt(e.ino)&&Lt(t.ino)}function W(e,t){let i=Lt(e.dev)&&Lt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Lt(e.ino)&&Lt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var en=1024*1024;function Jc(e,t){let i=Te.relative(e,t);return i===""||!Te.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Te.sep}`)}function Yk(e){let t=Te.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})||Te.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=at(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 Xk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Qk(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Va(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ie(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Up(e){let t=await ze.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ze.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Zk(e,t){let i=Te.resolve(e),r=Te.resolve(t);if(!Jc(i,r))throw new Error("Native artifact path is outside its root");let n=[await Up(i)],a=i;for(let o of Te.relative(i,r).split(Te.sep).filter(Boolean)){a=Te.join(a,o);let s=await Up(a);if(!Jc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Kp(e){for(let t of e){let i=await ze.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Qk(t,i)||await ze.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function oe(e){let t=Yk(e.ref),i=e.maxBytes===null?null:Xk(e.maxBytes??en),r=Te.resolve(e.root,...t.split("/")),n=await Zk(e.root,Te.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await ze.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 ze.realpath(r);if(!Jc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ze.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),ze.lstat(r),ze.realpath(r)]);if(await Kp(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Va(a,c)||!Va(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,k=await s.read(h,0,Math.min(h.length,E),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),ze.lstat(r),ze.realpath(r)]);if(await Kp(n),!p.isFile()||p.isSymbolicLink()||m!==o||!Va(c,v)||!Va(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),y;try{y=new Kk("utf-8",{fatal:!0}).decode(b)}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:Uk("sha256").update(b).digest("hex"),text:y}}finally{await s.close()}}var Uc=br(Bi(),1);import Li from"path";var tn=64*1024,Wa=1024,za=64,Qp=5,eS=12e4,Yp=6e5,tS=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],iS=["**/.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"],rS=[...tS,...iS].sort((e,t)=>e.localeCompare(t,"en"));var Je={include:["**/*"],exclude:[...rS],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function nS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Li.posix.isAbsolute(i)||Li.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 Fi(e){let t=nS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Zp(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 Ja(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||Li.posix.isAbsolute(r)||Li.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 Ft(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function eh(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 Ga(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>Wa)throw new Error(`${t} exceeds ${Wa} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>za)throw new Error(`${t} contains more than ${za} wildcard tokens`);return e}function Xp(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=>Ga(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Gc(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 aS(e){if(e===void 0)return{...Je,include:[...Je.include],exclude:[...Je.exclude]};let t=Ft(e,"native.snapshot");return{include:Xp(t.include,"native.snapshot.include",Je.include),exclude:Xp(t.exclude,"native.snapshot.exclude",Je.exclude),max_files:Gc(t.max_files,Je.max_files,"native.snapshot.max_files"),max_total_bytes:Gc(t.max_total_bytes,Je.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Gc(t.max_duration_ms,Je.max_duration_ms,"native.snapshot.max_duration_ms")}}function oS(e){if(e===void 0)return;let t=Ft(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=Ft(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:Fi(r),toArtifactRoot:Fi(n),stage:a,...o?{cleanup:o}:{}}}function sS(e){if(e===void 0)return;let t=Ft(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ft(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Li.posix.isAbsolute(r[0])||Li.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??eS;if(!Number.isSafeInteger(n)||n<1||n>Yp)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Yp}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function cS(e,t={}){let i=Ft(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??Qp;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=oS(i.pending_root_move),c=sS(i.finish);return{artifact_root:Fi(r),language:eh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:aS(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function lS(e){let t=Ft(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:Zp(t.artifact_layout),language:eh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function uS(e){let i=Ft(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)=>Ja(r,`hook.allow_paths[${n}]`)))]}}function dS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function fS(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 rn(e,t={}){let i=(0,Uc.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=dS(n.ambient_resume),o=n.hook===void 0?void 0:uS(n.hook),s=n.native===void 0?void 0:cS(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:lS(n.classic),l=fS(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}:{}}}import{createHash as hS}from"crypto";import{promises as Ya}from"fs";import Mt from"path";import{constants as Ua,promises as mi}from"fs";var ot=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Kc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function th(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function nn(e){return{dev:e.dev,ino:e.ino,birthtime:Kc(e)}}function Ka(e,t){let i=nn(e),r=nn(t);return Ie(i,r)?W(i,r):W(i,r)&&Kc(e)===Kc(t)&&th(e)===th(t)&&e.size===t.size}async function Mi(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 mi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ot("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ot("too-large",`${r} exceeds ${t} bytes`);let o=await mi.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:nn(a)});let s=process.platform==="win32"?Ua.O_RDONLY:Ua.O_RDONLY|Ua.O_NOFOLLOW|Ua.O_NONBLOCK,c;try{c=await mi.open(e,s)}catch(l){throw l.code==="ELOOP"?new ot("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),mi.lstat(e,{bigint:n}),mi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ka(a,l)||!Ka(a,u))throw new ot("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:nn(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:E}=await c.read(v,0,Math.min(v.length,y),null);if(E===0)break;if(h+=E,h>t)throw new ot("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([c.stat({bigint:n}),mi.lstat(e,{bigint:n}),mi.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||b!==o||!Ka(a,p)||!Ka(a,m))throw new ot("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:nn(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:b}}finally{await c.close()}}function pS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Yc(e,t){let i=Mt.relative(e,t);return i===""||!Mt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Mt.sep}`)}async function ih(e,t){let i=Mt.resolve(e),r=await Ya.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ya.realpath(i)}async function rh(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Mt.join(n,i[a]);let o;try{o=await Ya.lstat(n)}catch(u){if(pS(u))return{exists:!1,kind:"missing"};throw u}let s=Mt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Ya.realpath(n);if(!Yc(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function qi(e,t,i){let r=Ja(t,i.label),n=Mt.resolve(e),a=await ih(n,i.label),o=r.split("/"),s=Mt.resolve(n,...o);if(!Yc(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await rh(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function qt(e,t,i,r){let n=await qi(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await ih(n.projectRoot,r.label);return Mi(n.target,i,{...r,verify:async(o,s)=>{if(!Yc(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await rh(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var an=".comet/config.yaml";function mS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Xa(e,t={}){return(await Qa(e,t)).document}async function vS(e){try{return(await qt(e,an,tn,{label:an})).bytes}catch(t){if(mS(t))return null;throw t}}function gS(e){return e?{exists:!0,sha256:hS("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Qa(e,t={}){let i=await vS(e);return{document:i?rn(i.toString("utf8"),t):null,identity:gS(i)}}async function Xc(e){return(await Xa(e))?.config??null}var VT=16*1024;import{existsSync as ah,promises as Vt}from"fs";import q from"path";import kS from"os";var il=".comet/config.yaml",SS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function el(e){try{return await Vt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ES(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 Wi(e,t){let i=q.relative(e,t);return i===""||!q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${q.sep}`)}async function Vi(e){let t=[],i=e;for(;!await el(i);){let n=q.dirname(i);if(n===i)break;t.push(q.basename(i)),i=n}let r=await Vt.realpath(i);return q.resolve(r,...t.reverse())}async function tl(e){try{return(await Vt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function rl(e){let t=q.resolve(e);try{(await Vt.stat(t)).isDirectory()||(t=q.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=q.resolve(kS.homedir());for(;;){if(!(t===r&&i!==r)){let o=q.join(t,...il.split("/")),s=t===i||await ES(o);if(await el(o)&&s)return t}if(await el(q.join(t,".git")))return t;let a=q.dirname(t);if(a===t)return i;t=a}}function nl(e){return Fi(e)}async function PS(e,t){let i=nl(t),r=q.resolve(e,...i.split("/")),n=await Vt.realpath(e),a=await Vi(r);if(!Wi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function vt(e,t){let i=nl(t),r=await PS(e,i),n=q.join(r,"comet");if(await tl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Vi(r),Vi(n)]);if(!Wi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=q.resolve(e),c=q.join(s,".comet","runtime","native");if(await tl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Vt.realpath(s),Vi(c)]);if(!Wi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:q.join(e,...il.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:q.join(n,"specs"),changesDir:q.join(n,"changes"),archiveDir:q.join(n,"archive"),runtimeDir:c,changesRuntimeDir:q.join(c,"changes"),locksDir:q.join(c,"locks"),transactionsDir:q.join(c,"transactions")}}function sh(e){if(!SS.test(e))throw new Error(`Invalid Native change name: ${e}`)}function zi(e,t){sh(t);let i=q.join(e.changesRuntimeDir,t);if(!L(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function ch(e,t){sh(t);let i=q.join(e.changesDir,t,"runtime");if(!L(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function G(e,t){let i=zi(e,t);if(ah(i))return i;let r=ch(e,t);return ah(r)?r:i}async function oh(e){try{let t=await Vt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function al(e,t){let i=zi(e,t),r=ch(e,t),[n,a]=await Promise.all([oh(i),oh(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 Wt(e,t){if(!t.startsWith("runtime/")||q.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=q.resolve(e,...t.slice(8).split("/"));if(!L(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function se(e,t){let i=q.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 Wi(q.resolve(e),q.resolve(t))}async function z(e,t){let i=q.resolve(e),r=q.resolve(t);if(!Wi(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await tl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Vi(i),Vi(r)]);if(!Wi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var ol=Je;var Za=Ga;async function Pe(e){let t=(await Xa(e))?.config??null;return t?.native?t:null}import{AsyncLocalStorage as CS}from"async_hooks";var hj=16*1024;var mj=new CS;import uh from"node:path";var RS="comet.native.acceptance.v1",AS=/^acceptance-[a-f0-9]{64}$/u,_S=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),IS=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,TS=/^[a-f0-9]{64}$/u,jS=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function $S(e,t){return e<t?-1:e>t?1:0}var gt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),sn=Object.freeze({maxCriteria:1024}),dh="<!-- comet-native:acceptance-evidence:start -->",fh="<!-- comet-native:acceptance-evidence:end -->";function ph(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 hh(e,t){let i=t.toString(36),r=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function OS(e){if(!TS.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=jS.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]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function HS(e,t){let i=ph(e.text,gt.maxTextBytes),r=e.context.slice(0,gt.maxContextItems).map(n=>ph(n,gt.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 vh(e){let t=OS({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort($S),n=r.slice(0,gt.maxFailedCheckIds),a=e.criteria.slice(t,t+gt.maxItems);for(let c of a){let l=[...i,HS(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:u<e.criteria.length?hh(e.acceptanceHash,u):null,limits:{...gt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>gt.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:o<e.criteria.length?hh(e.acceptanceHash,o):null,limits:{...gt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>gt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function cl(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 sl(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 mh(e){return e.includes("-->")||e.includes("--!>")}function*Ji(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
144
144
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
145
|
-
`,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=sl(l,t);else if(i)mh(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=sl(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!mh(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function DS(e){return[...Ji(e)].map(({line:t,body:i})=>({line:t,body:i}))}function
|
|
145
|
+
`,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=sl(l,t);else if(i)mh(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=sl(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!mh(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function DS(e){return[...Ji(e)].map(({line:t,body:i})=>({line:t,body:i}))}function eo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function BS(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function ll(e,t,i,r=[],n="content-hash"){let a=eo(i),o=t.replaceAll("\\","/").trim(),s=r.map(eo);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${j(RS,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function ul(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function LS(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Ji(e)){n=s+1;let c=o?cl(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function dl(e,t="brief.md",i=sn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=LS(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Ji(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Ji(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),ul(o.map(l=>ll("brief-example",t,l.join(`
|
|
146
146
|
`),[],r)),"Brief",r)}function fl(e,t="spec.md",i=sn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(ll("spec-scenario",t,[o.title,...o.body].join(`
|
|
147
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of Ji(e)){let u=l?cl(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=
|
|
148
|
-
`).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=gh(o),c=qS(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function qS(e){let t=gh([...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 ml=br(Bi(),1);import{promises as WS}from"node:fs";var cn="comet.native.v4",eo="comet.native.local-execution.v4";var zS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GS=/^A[1-9][0-9]*$/u,US=/^[a-f0-9]{64}$/u,KS=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"]);function ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(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 ue(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 hl(e,t){return e===null?null:ue(e,t)}function YS(e,t){let i=ue(e,t);if(!US.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Gi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function te(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function XS(e,t){return e===null?null:te(e,t,Number.MIN_SAFE_INTEGER)}function le(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function st(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function to(e,t){return st(e,t,(i,r)=>ue(i,`${t}[${r}]`))}function gi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Ui(e,t){let i=ue(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function vl(e,t,i=!1){let r=ue(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 Ge(e,t){let i=ye(e,t);return Ne(i,new Set(["text","truncated"]),t),{text:ue(i.text,`${t}.text`,{empty:!0}),truncated:Gi(i.truncated,`${t}.truncated`)}}function QS(e,t){let i=`Native spec_changes[${t}]`,r=ye(e,i);Ne(r,new Set(["capability","operation","source"]),i);let n=ue(r.capability,`${i}.capability`);if(!JS.test(n))throw new Error(`${i}.capability is invalid`);let a=le(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:vl(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 ZS(e){let t="Native workspace",i=ye(e,t);Ne(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=le(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=hl(i.change_branch,`${t}.change_branch`),a=hl(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:le(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 eE(e){let t="Native loop",i=ye(e,t);Ne(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=to(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return gi(r,`${t}.previous_unresolved_ids`),{stage:le(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:te(i.goal_cycle,`${t}.goal_cycle`,1),iteration:te(i.iteration,`${t}.iteration`),attempt:te(i.attempt,`${t}.attempt`),retry_epoch:te(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:te(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:te(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:te(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:hl(i.next_action,`${t}.next_action`)}}function tE(e,t){let i=`Native acceptance[${t}]`,r=ye(e,i);Ne(r,new Set(["id","source","text","result","reason"]),i);let n=ue(r.id,`${i}.id`);if(!GS.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:vl(r.source,`${i}.source`),text:ue(r.text,`${i}.text`),result:le(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ge(r.reason,`${i}.reason`)}}function iE(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["name","result","note"]),i),{name:Ge(r.name,`${i}.name`),result:le(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ge(r.note,`${i}.note`)}}function rE(e){let t="Native builder_handoff",i=ye(e,t);Ne(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=to(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return gi(r,`${t}.addressed_acceptance_ids`),{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:ue(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:ue(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),summary:Ge(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:st(i.checks,`${t}.checks`,iE),checks_truncated:Gi(i.checks_truncated,`${t}.checks_truncated`),known_limits:st(i.known_limits,`${t}.known_limits`,(n,a)=>Ge(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Gi(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Ui(i.submitted_at,`${t}.submitted_at`)}}function nE(e,t){let i=`Native blockers[${t}]`,r=ye(e,i);Ne(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=to(r.acceptance_ids,`${i}.acceptance_ids`);return gi(n,`${i}.acceptance_ids`),{owner:le(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ge(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:le(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function aE(e,t){let i=`Native verification.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:ue(r.id,`${i}.id`),name:Ge(r.name,`${i}.name`),argv_display:st(r.argv_display,`${i}.argv_display`,(n,a)=>Ge(n,`${i}.argv_display[${a}]`)),argv_truncated:Gi(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:vl(r.cwd_ref,`${i}.cwd_ref`,!0),status:le(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:XS(r.exit_code,`${i}.exit_code`),duration_ms:te(r.duration_ms,`${i}.duration_ms`)}}function oE(e){let t="Native verification",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=st(i.checks,`${t}.checks`,aE);gi(r.map(a=>a.id),`${t}.checks IDs`);let n=ue(i.identity_provider,`${t}.identity_provider`);return{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ue(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),attempt:te(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":le(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:le(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ge(i.summary,`${t}.summary`),risks:st(i.risks,`${t}.risks`,(a,o)=>Ge(a,`${t}.risks[${o}]`)),risks_truncated:Gi(i.risks_truncated,`${t}.risks_truncated`),completed_at:Ui(i.completed_at,`${t}.completed_at`)}}function sE(e,t){let i=`Native history[${t}]`,r=ye(e,i);Ne(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=to(r.unresolved_ids,`${i}.unresolved_ids`);return gi(n,`${i}.unresolved_ids`),{goal_cycle:te(r.goal_cycle,`${i}.goal_cycle`,1),iteration:te(r.iteration,`${i}.iteration`),attempt:te(r.attempt,`${i}.attempt`),outcome:le(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ge(r.summary,`${i}.summary`),completed_at:Ui(r.completed_at,`${i}.completed_at`)}}function cE(e){let t="Native history_overflow.outcome_counts",i=ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Ne(i,new Set(r),t),{pass:te(i.pass,`${t}.pass`),fail:te(i.fail,`${t}.fail`),blocked:te(i.blocked,`${t}.blocked`),"execution-error":te(i["execution-error"],`${t}.execution-error`),recovery:te(i.recovery,`${t}.recovery`)}}function lE(e){let t="Native history_overflow",i=ye(e,t);Ne(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=te(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Ui(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Ui(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=cE(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 uE(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 dE(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 ln(e){let t=ye(e,"Native portable state");if(Ne(t,KS,"Native portable state"),t.schema!==cn)throw new Error(`Native portable state schema must be ${cn}`);let i=ue(t.name,"Native state name");if(!zS.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=st(t.spec_changes,"Native spec_changes",QS);gi(r.map(s=>s.capability),"Native spec change capabilities");let n=st(t.acceptance,"Native acceptance",tE);gi(n.map(s=>s.id),"Native acceptance IDs");let a=st(t.history,"Native history",sE);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:cn,name:i,language:le(t.language,["en","zh-CN"],"Native state language"),phase:le(t.phase,["shape","build","verify","archive"],"Native state phase"),status:le(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:te(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:YS(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:ZS(t.workspace),loop:eE(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:rE(t.builder_handoff),blockers:st(t.blockers,"Native blockers",nE),verification:t.verification===null?null:oE(t.verification),history:a,history_overflow:lE(t.history_overflow),verification_result:le(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:le(t.verification_report,["verification.md"],"Native verification_report"),archived:Gi(t.archived,"Native archived"),created_at:Ui(t.created_at,"Native created_at")};return uE(o),dE(o),o}function fE(e,t){let i=(0,ml.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 un(e){let t=await WS.readFile(e,"utf8");return ln(fE(t,"Native portable state"))}var zt="comet.native.v3",Jt="comet.native.v2",Gt="comet.native.v1",Ki="comet.native.transition.v3",Yi="comet.native.transition.v2",dn="comet.native.transition.v1";var bh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Mj=new RegExp(`^portable-archive-(${bh})\\.json$`,"u"),qj=new RegExp(`^portable-migration-(${bh})\\.json$`,"u");import{TextDecoder as yE}from"util";import{createHash as pE}from"node:crypto";import{constants as io,promises as xe}from"node:fs";import Ue from"node:path";import{TextDecoder as hE}from"node:util";function no(e,t){let i=Ue.relative(e,t);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function kh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function mE(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ro(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 gl(e,t){let i=await xe.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await xe.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function wl(e,t,i){let r=Ue.resolve(e),n=Ue.resolve(t);if(!no(r,n))throw new Error(`${i} is outside its managed root`);let a=[await gl(r,i)],o=r;for(let s of Ue.relative(r,n).split(Ue.sep).filter(Boolean)){await ct(a,i),o=Ue.join(o,s);let c=await gl(o,i);if(!no(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ct(a,i),a}async function ct(e,t){for(let i of e){let r=await xe.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!mE(i,r)||await xe.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function gE(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 wt(e){let t=kh(e.maxBytes),i=Ue.resolve(e.file),r=await wl(e.root,Ue.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>gl(Ue.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ct(r,e.label);let a=await xe.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=vE(a),s=await xe.realpath(i);if(!no(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>no(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?io.O_RDONLY:io.O_RDONLY|io.O_NOFOLLOW|io.O_NONBLOCK,l=await xe.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([xe.lstat(i),xe.realpath(i)]);if(await ct(r,e.label),await ct(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ro(o,u)||!ro(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await gE(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),xe.lstat(i),xe.realpath(i)]);if(await ct(r,e.label),await ct(n,e.label),!p.isFile()||p.isSymbolicLink()||m!==s||!ro(o,v)||!ro(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:pE("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Sh(e){let t=await wt(e),i;try{i=new hE("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 fn(e){let t=await wl(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await xe.readdir(e.directory,{withFileTypes:!0});else{let r=kh(e.maxEntries);i=[];let n=await xe.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 ct(t,e.label),{entries:i,verify:()=>ct(t,e.label)}}async function yl(e){let t=await wl(e.root,e.directory,e.label);return{verify:()=>ct(t,e.label)}}var n$=256*1024,a$=1024*1024,o$=16*1024;var s$=64*1024*1024;var c$=new yE("utf-8",{fatal:!0});import{createHash as lo}from"crypto";import{spawn as Dh}from"node:child_process";import{promises as Y}from"fs";import D from"path";import{createHash as Rh}from"crypto";import{createReadStream as bE}from"fs";async function Nl(e){let t=Rh("sha256");for await(let i of bE(e))t.update(i);return t.digest("hex")}function U(e){return Rh("sha256").update(e).digest("hex")}var ao={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},xl=1e3,kE=8*1024*1024,SE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EE=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),PE=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),xE=new Set(["schema","include","exclude","hash"]),CE=new Set(["provider","gitSelection","physicalSelection","projection"]),RE=new Set(["provider","selection"]),AE=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),_E=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),TE=new Set(["schema","status","before","after"]),IE=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),jE=new Set(["path","hash","size","type","gitObjectId"]),$E=new Set(["path","size","type","reason"]),OE=new Set(["ref","hash","count"]),HE=new Set(["change-created","legacy-migration","explicit"]),DE=new Set(["file","directory","other"]),BE=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"]),uo=/^[a-f0-9]{64}$/u,Bh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,LE=new Set(["EACCES","EPERM"]),rr=64*1024,El=64*1024,FE=6e4,ME=1e3,qE=2,Cl={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},VE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Lh(e){let t=e.deadlineMs??FE;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 Ke(e){return Math.max(0,e.deadlineAt-Date.now())}function O(e){return Ke(e)>=1}function bl(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 tr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function WE(e){let t={...VE,...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 zE(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&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.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=Dh(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),ME),u.unref()}catch{d(!1)}});for(let s=0;s<qE;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Rl(e,t,i,r){let n=Ke(e);if(n<1)throw bl();let a=e.gitProcess,o=Dh(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=zE(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?bl(v.error):bl()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Fh(e){let t={...Cl,...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 oo(e,t,i,r=El){let{child:n,completion:a}=Rl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=rr)return;let v=rr-c,p=Buffer.from(h).subarray(0,v);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 kl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function hn(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}=Rl(e,t,i,r.stdin!==void 0),c=[],l=lo("sha256"),u=[],d=0,f=0,h=0,v=0,p=Buffer.alloc(0),m=!1,b=!1,y=!1,E=k=>{let P=0;for(;P<k.byteLength;){let N=k.indexOf(0,P),x=N<0?k.byteLength:N,w=k.subarray(P,x);if(!m&&w.byteLength>0&&(p.byteLength+w.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),m=!0,b=!0):p=Buffer.concat([p,w])),N<0)break;v+=1,p.byteLength===0&&!m&&(y=!0);let g=p.byteLength+1;!m&&v<=r.maxRecords&&h+g<=r.maxBytes?(c.push(p),h+=g):b=!0,p=Buffer.alloc(0),m=!1,P=N+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(b=!0);let P=r.outputChunkBytes;if(P===void 0){E(k);return}for(let N=0;N<k.byteLength;N+=P)E(k.subarray(N,Math.min(k.byteLength,N+P)))}),o.stderr.on("data",k=>{if(d>=rr)return;let P=rr-d,N=Buffer.from(k).subarray(0,P);u.push(N),d+=N.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:P})=>{let N=r.acceptedExitCodes??[0];if(k!==null&&N.includes(k)&&P===null&&!y&&p.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${P?`: ${P.message}`:y||p.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 so(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 JE(e,t,i){if(i.length===0)return new Set;let r=await hn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Cl,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=so(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function GE(e,t,i){let{child:r,completion:n}=Rl(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>=rr)return;let d=rr-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 ir(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function UE(e,t){return e.map(i=>{let r=ir(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function KE(e){let t=D.resolve(e);for(;;){try{return await Y.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function Mh(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=ir(h);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 hn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await hn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await hn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function qh(e){return{stageBefore:kl(e.stagedBefore),combined:kl(e.combined),stageAfter:kl(e.stagedAfter)}}async function Vh(e,t,i=Cl,r={}){let n=D.resolve(t.projectRoot);if(!await KE(n))return null;let a;try{a=await oo(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw tr(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 Mh(e,t,i,r)}catch(y){throw tr(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 k=so(E),P=k.indexOf(" ");if(P<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let N=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,P))?.groups;if(!N)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=ir(k.slice(P+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),N.stage==="0"&&d.set(x,N.objectId),N.mode==="160000"&&N.stage==="0"&&f.add(x)}};h(s.records),h(l.records);let v=c.records.map(so),p=UE(v,"combined"),m=new Set(p.filter(y=>!u.has(y))),b=new Set(p.filter((y,E)=>!u.has(y)&&v[E].endsWith("/")));for(let y of f)b.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:qh(o)}}function Xt(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Ah(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function YE(e,t){return!Xt(e.stageBefore,e.stageAfter)||!Xt(e.stageAfter,t.stageBefore)||!Xt(e.combined,t.combined)||!Xt(t.stageBefore,t.stageAfter)}async function Wh(e,t,i,r,n){let a;try{a=await Mh(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw tr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=qh(a),c=Ah(o)||Ah(s),l=YE(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:U(`comet.native.git-selection-overflow.v2
|
|
149
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var XE=(1n<<256n)-1n;function QE(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function _h(e){let t=D.resolve(e.paths.projectRoot),i=D.resolve(e.paths.nativeRoot),r=D.resolve(e.paths.runtimeDir),n=D.resolve(e.paths.configFile),a=D.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,p=!1,m=()=>Ke(e.execution)>=1?!0:(h=!0,p=!0,!1),b=k=>{let P=Buffer.from(`${k.type}\0${k.path}`,"utf8"),N=
|
|
147
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of Ji(e)){let u=l?cl(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=eo(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(),ul(n,"Specification",r)}function pl(e,t="spec.md",i=sn.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(ll("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 Ji(e)){let f=d?cl(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||sl(u,null)!==null||h.startsWith("<!--")||h==="-->"||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 v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[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(),ul(n,"Specification mandatory requirements",r)}function FS(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||BS(i)||uh.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=uh.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(!IS.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function MS(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=>!_S.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function gh(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=MS(i,r),a=n.acceptance_id;if(typeof a!="string"||!AS.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 FS(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 wh(e){let t=DS(e);if(t.some(({line:l,body:u})=>!u&&(l===dh||l===fh)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===dh?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===fh?[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(`
|
|
148
|
+
`).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=gh(o),c=qS(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function qS(e){let t=gh([...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 ml=br(Bi(),1);import{promises as WS}from"node:fs";var cn="comet.native.v4",to="comet.native.local-execution.v4";var zS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GS=/^A[1-9][0-9]*$/u,US=/^[a-f0-9]{64}$/u,KS=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"]);function ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(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 ue(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 hl(e,t){return e===null?null:ue(e,t)}function YS(e,t){let i=ue(e,t);if(!US.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Gi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function te(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function XS(e,t){return e===null?null:te(e,t,Number.MIN_SAFE_INTEGER)}function le(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function st(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function io(e,t){return st(e,t,(i,r)=>ue(i,`${t}[${r}]`))}function gi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Ui(e,t){let i=ue(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function vl(e,t,i=!1){let r=ue(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 Ge(e,t){let i=ye(e,t);return Ne(i,new Set(["text","truncated"]),t),{text:ue(i.text,`${t}.text`,{empty:!0}),truncated:Gi(i.truncated,`${t}.truncated`)}}function QS(e,t){let i=`Native spec_changes[${t}]`,r=ye(e,i);Ne(r,new Set(["capability","operation","source"]),i);let n=ue(r.capability,`${i}.capability`);if(!JS.test(n))throw new Error(`${i}.capability is invalid`);let a=le(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:vl(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 ZS(e){let t="Native workspace",i=ye(e,t);Ne(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=le(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=hl(i.change_branch,`${t}.change_branch`),a=hl(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:le(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 eE(e){let t="Native loop",i=ye(e,t);Ne(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=io(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return gi(r,`${t}.previous_unresolved_ids`),{stage:le(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:te(i.goal_cycle,`${t}.goal_cycle`,1),iteration:te(i.iteration,`${t}.iteration`),attempt:te(i.attempt,`${t}.attempt`),retry_epoch:te(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:te(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:te(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:te(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:hl(i.next_action,`${t}.next_action`)}}function tE(e,t){let i=`Native acceptance[${t}]`,r=ye(e,i);Ne(r,new Set(["id","source","text","result","reason"]),i);let n=ue(r.id,`${i}.id`);if(!GS.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:vl(r.source,`${i}.source`),text:ue(r.text,`${i}.text`),result:le(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ge(r.reason,`${i}.reason`)}}function iE(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["name","result","note"]),i),{name:Ge(r.name,`${i}.name`),result:le(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ge(r.note,`${i}.note`)}}function rE(e){let t="Native builder_handoff",i=ye(e,t);Ne(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=io(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return gi(r,`${t}.addressed_acceptance_ids`),{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:ue(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:ue(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),summary:Ge(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:st(i.checks,`${t}.checks`,iE),checks_truncated:Gi(i.checks_truncated,`${t}.checks_truncated`),known_limits:st(i.known_limits,`${t}.known_limits`,(n,a)=>Ge(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Gi(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Ui(i.submitted_at,`${t}.submitted_at`)}}function nE(e,t){let i=`Native blockers[${t}]`,r=ye(e,i);Ne(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=io(r.acceptance_ids,`${i}.acceptance_ids`);return gi(n,`${i}.acceptance_ids`),{owner:le(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ge(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:le(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function aE(e,t){let i=`Native verification.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:ue(r.id,`${i}.id`),name:Ge(r.name,`${i}.name`),argv_display:st(r.argv_display,`${i}.argv_display`,(n,a)=>Ge(n,`${i}.argv_display[${a}]`)),argv_truncated:Gi(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:vl(r.cwd_ref,`${i}.cwd_ref`,!0),status:le(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:XS(r.exit_code,`${i}.exit_code`),duration_ms:te(r.duration_ms,`${i}.duration_ms`)}}function oE(e){let t="Native verification",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=st(i.checks,`${t}.checks`,aE);gi(r.map(a=>a.id),`${t}.checks IDs`);let n=ue(i.identity_provider,`${t}.identity_provider`);return{candidate_id:ue(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ue(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),attempt:te(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":le(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:le(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ge(i.summary,`${t}.summary`),risks:st(i.risks,`${t}.risks`,(a,o)=>Ge(a,`${t}.risks[${o}]`)),risks_truncated:Gi(i.risks_truncated,`${t}.risks_truncated`),completed_at:Ui(i.completed_at,`${t}.completed_at`)}}function sE(e,t){let i=`Native history[${t}]`,r=ye(e,i);Ne(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=io(r.unresolved_ids,`${i}.unresolved_ids`);return gi(n,`${i}.unresolved_ids`),{goal_cycle:te(r.goal_cycle,`${i}.goal_cycle`,1),iteration:te(r.iteration,`${i}.iteration`),attempt:te(r.attempt,`${i}.attempt`),outcome:le(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ge(r.summary,`${i}.summary`),completed_at:Ui(r.completed_at,`${i}.completed_at`)}}function cE(e){let t="Native history_overflow.outcome_counts",i=ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Ne(i,new Set(r),t),{pass:te(i.pass,`${t}.pass`),fail:te(i.fail,`${t}.fail`),blocked:te(i.blocked,`${t}.blocked`),"execution-error":te(i["execution-error"],`${t}.execution-error`),recovery:te(i.recovery,`${t}.recovery`)}}function lE(e){let t="Native history_overflow",i=ye(e,t);Ne(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=te(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Ui(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Ui(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=cE(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 uE(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 dE(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 ln(e){let t=ye(e,"Native portable state");if(Ne(t,KS,"Native portable state"),t.schema!==cn)throw new Error(`Native portable state schema must be ${cn}`);let i=ue(t.name,"Native state name");if(!zS.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=st(t.spec_changes,"Native spec_changes",QS);gi(r.map(s=>s.capability),"Native spec change capabilities");let n=st(t.acceptance,"Native acceptance",tE);gi(n.map(s=>s.id),"Native acceptance IDs");let a=st(t.history,"Native history",sE);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:cn,name:i,language:le(t.language,["en","zh-CN"],"Native state language"),phase:le(t.phase,["shape","build","verify","archive"],"Native state phase"),status:le(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:te(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:YS(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:ZS(t.workspace),loop:eE(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:rE(t.builder_handoff),blockers:st(t.blockers,"Native blockers",nE),verification:t.verification===null?null:oE(t.verification),history:a,history_overflow:lE(t.history_overflow),verification_result:le(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:le(t.verification_report,["verification.md"],"Native verification_report"),archived:Gi(t.archived,"Native archived"),created_at:Ui(t.created_at,"Native created_at")};return uE(o),dE(o),o}function fE(e,t){let i=(0,ml.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 un(e){let t=await WS.readFile(e,"utf8");return ln(fE(t,"Native portable state"))}var zt="comet.native.v3",Jt="comet.native.v2",Gt="comet.native.v1",Ki="comet.native.transition.v3",Yi="comet.native.transition.v2",dn="comet.native.transition.v1";var bh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Fj=new RegExp(`^portable-archive-(${bh})\\.json$`,"u"),Mj=new RegExp(`^portable-migration-(${bh})\\.json$`,"u");import{TextDecoder as yE}from"util";import{createHash as pE}from"node:crypto";import{constants as ro,promises as xe}from"node:fs";import Ue from"node:path";import{TextDecoder as hE}from"node:util";function ao(e,t){let i=Ue.relative(e,t);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function kh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function mE(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function no(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 gl(e,t){let i=await xe.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await xe.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function wl(e,t,i){let r=Ue.resolve(e),n=Ue.resolve(t);if(!ao(r,n))throw new Error(`${i} is outside its managed root`);let a=[await gl(r,i)],o=r;for(let s of Ue.relative(r,n).split(Ue.sep).filter(Boolean)){await ct(a,i),o=Ue.join(o,s);let c=await gl(o,i);if(!ao(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ct(a,i),a}async function ct(e,t){for(let i of e){let r=await xe.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!mE(i,r)||await xe.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function gE(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 wt(e){let t=kh(e.maxBytes),i=Ue.resolve(e.file),r=await wl(e.root,Ue.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>gl(Ue.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ct(r,e.label);let a=await xe.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=vE(a),s=await xe.realpath(i);if(!ao(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ao(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ro.O_RDONLY:ro.O_RDONLY|ro.O_NOFOLLOW|ro.O_NONBLOCK,l=await xe.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([xe.lstat(i),xe.realpath(i)]);if(await ct(r,e.label),await ct(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!no(o,u)||!no(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await gE(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),xe.lstat(i),xe.realpath(i)]);if(await ct(r,e.label),await ct(n,e.label),!p.isFile()||p.isSymbolicLink()||m!==s||!no(o,v)||!no(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:pE("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Sh(e){let t=await wt(e),i;try{i=new hE("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 fn(e){let t=await wl(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await xe.readdir(e.directory,{withFileTypes:!0});else{let r=kh(e.maxEntries);i=[];let n=await xe.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 ct(t,e.label),{entries:i,verify:()=>ct(t,e.label)}}async function yl(e){let t=await wl(e.root,e.directory,e.label);return{verify:()=>ct(t,e.label)}}var r$=256*1024,n$=1024*1024,a$=16*1024;var o$=64*1024*1024;var s$=new yE("utf-8",{fatal:!0});import{createHash as uo}from"crypto";import{spawn as Dh}from"node:child_process";import{promises as Y}from"fs";import D from"path";import{createHash as Rh}from"crypto";import{createReadStream as bE}from"fs";async function Nl(e){let t=Rh("sha256");for await(let i of bE(e))t.update(i);return t.digest("hex")}function U(e){return Rh("sha256").update(e).digest("hex")}var oo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},xl=1e3,kE=8*1024*1024,SE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EE=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),PE=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),xE=new Set(["schema","include","exclude","hash"]),CE=new Set(["provider","gitSelection","physicalSelection","projection"]),RE=new Set(["provider","selection"]),AE=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),_E=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),IE=new Set(["schema","status","before","after"]),TE=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),jE=new Set(["path","hash","size","type","gitObjectId"]),$E=new Set(["path","size","type","reason"]),OE=new Set(["ref","hash","count"]),HE=new Set(["change-created","legacy-migration","explicit"]),DE=new Set(["file","directory","other"]),BE=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"]),fo=/^[a-f0-9]{64}$/u,Bh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,LE=new Set(["EACCES","EPERM"]),rr=64*1024,El=64*1024,FE=6e4,ME=1e3,qE=2,Cl={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},VE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Lh(e){let t=e.deadlineMs??FE;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 Ke(e){return Math.max(0,e.deadlineAt-Date.now())}function O(e){return Ke(e)>=1}function bl(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 tr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function WE(e){let t={...VE,...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 zE(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&&D.win32.isAbsolute(r)?D.win32.resolve(r):"C:\\Windows",a=D.win32.join(n,"System32","taskkill.exe");if(!D.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=Dh(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),ME),u.unref()}catch{d(!1)}});for(let s=0;s<qE;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Rl(e,t,i,r){let n=Ke(e);if(n<1)throw bl();let a=e.gitProcess,o=Dh(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=zE(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?bl(v.error):bl()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Fh(e){let t={...Cl,...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 so(e,t,i,r=El){let{child:n,completion:a}=Rl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=rr)return;let v=rr-c,p=Buffer.from(h).subarray(0,v);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 kl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function hn(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}=Rl(e,t,i,r.stdin!==void 0),c=[],l=uo("sha256"),u=[],d=0,f=0,h=0,v=0,p=Buffer.alloc(0),m=!1,b=!1,y=!1,E=k=>{let P=0;for(;P<k.byteLength;){let N=k.indexOf(0,P),x=N<0?k.byteLength:N,w=k.subarray(P,x);if(!m&&w.byteLength>0&&(p.byteLength+w.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),m=!0,b=!0):p=Buffer.concat([p,w])),N<0)break;v+=1,p.byteLength===0&&!m&&(y=!0);let g=p.byteLength+1;!m&&v<=r.maxRecords&&h+g<=r.maxBytes?(c.push(p),h+=g):b=!0,p=Buffer.alloc(0),m=!1,P=N+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(b=!0);let P=r.outputChunkBytes;if(P===void 0){E(k);return}for(let N=0;N<k.byteLength;N+=P)E(k.subarray(N,Math.min(k.byteLength,N+P)))}),o.stderr.on("data",k=>{if(d>=rr)return;let P=rr-d,N=Buffer.from(k).subarray(0,P);u.push(N),d+=N.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:P})=>{let N=r.acceptedExitCodes??[0];if(k!==null&&N.includes(k)&&P===null&&!y&&p.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${P?`: ${P.message}`:y||p.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 co(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 JE(e,t,i){if(i.length===0)return new Set;let r=await hn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Cl,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=co(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function GE(e,t,i){let{child:r,completion:n}=Rl(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>=rr)return;let d=rr-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 ir(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||D.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||D.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function UE(e,t){return e.map(i=>{let r=ir(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function KE(e){let t=D.resolve(e);for(;;){try{return await Y.lstat(D.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=D.dirname(t);if(i===t)return!1;t=i}}async function Mh(e,t,i,r={}){let n=D.resolve(t.projectRoot),a=D.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=D.relative(n,D.resolve(f)).replaceAll("\\","/"),v=ir(h);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 hn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await hn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await hn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function qh(e){return{stageBefore:kl(e.stagedBefore),combined:kl(e.combined),stageAfter:kl(e.stagedAfter)}}async function Vh(e,t,i=Cl,r={}){let n=D.resolve(t.projectRoot);if(!await KE(n))return null;let a;try{a=await so(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw tr(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 Mh(e,t,i,r)}catch(y){throw tr(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 k=co(E),P=k.indexOf(" ");if(P<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let N=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,P))?.groups;if(!N)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=ir(k.slice(P+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),N.stage==="0"&&d.set(x,N.objectId),N.mode==="160000"&&N.stage==="0"&&f.add(x)}};h(s.records),h(l.records);let v=c.records.map(co),p=UE(v,"combined"),m=new Set(p.filter(y=>!u.has(y))),b=new Set(p.filter((y,E)=>!u.has(y)&&v[E].endsWith("/")));for(let y of f)b.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:qh(o)}}function Xt(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Ah(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function YE(e,t){return!Xt(e.stageBefore,e.stageAfter)||!Xt(e.stageAfter,t.stageBefore)||!Xt(e.combined,t.combined)||!Xt(t.stageBefore,t.stageAfter)}async function Wh(e,t,i,r,n){let a;try{a=await Mh(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw tr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=qh(a),c=Ah(o)||Ah(s),l=YE(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:U(`comet.native.git-selection-overflow.v2
|
|
149
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var XE=(1n<<256n)-1n;function QE(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function _h(e){let t=D.resolve(e.paths.projectRoot),i=D.resolve(e.paths.nativeRoot),r=D.resolve(e.paths.runtimeDir),n=D.resolve(e.paths.configFile),a=D.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,p=!1,m=()=>Ke(e.execution)>=1?!0:(h=!0,p=!0,!1),b=k=>{let P=Buffer.from(`${k.type}\0${k.path}`,"utf8"),N=uo("sha256").update("comet.native.physical-selection-record.v1\0").update(P).digest();for(let x=0;x<c.length;x+=1)c[x]^=N[x];if(l=l+BigInt(`0x${N.toString("hex")}`)&XE,d+=1,f+=P.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,p=!0;return}o.push(k)},y=async k=>{if(p||!m())return;let P;try{P=await Y.opendir(k)}catch(S){if(!m())return;if(!ne(S)&&!re(S)||k===t&&ne(S))throw S;v||=re(S),h||=ne(S),p=!0;return}if(!m()){try{await P.close()}catch(S){if(S.code!=="ERR_DIR_CLOSED")throw S}return}let N=!1,x;try{for(;!p&&m();){let S;try{S=await P.read()}catch(J){if(!m())break;if(!ne(J)&&!re(J)||k===t&&ne(J))throw J;v||=re(J),h||=ne(J),p=!0;break}if(!m()||S===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,p=!0;break}let $=D.join(k,S.name),T=eP(t,$);if($===n||$===a||Ye(i,$)||Ye(r,$)||e.denylist.some(J=>Ye(J,$))||at(T)!==null)continue;if(!m())break;let fe;try{fe=await Y.lstat($)}catch(J){if(!m())break;if(!ne(J)&&!re(J))throw J;if(v=!0,b({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:ne(J)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),p||!m())break;continue}if(!m())break;let X=QE(fe);if(X==="directory"){if(nP(e.policy,T))continue;if(!m())break;let J;try{J=await Y.realpath($)}catch(it){if(!m())break;if(!ne(it)&&!re(it))throw it;if(v=!0,b({path:T,type:X}),s.push({path:T,size:null,type:"directory",reason:ne(it)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),p||!m())break;continue}if(!m())break;if(!L(e.physicalProjectRoot,J)||Ye(e.physicalNativeRoot,J))continue;if(b({path:T,type:X}),await e.hooks?.afterNode?.(T),!m()||(await y($),p))break;continue}if(b({path:T,type:X}),await e.hooks?.afterNode?.(T),!m()||p)break}}catch(S){N=!0,x=S}let w;try{await P.close()}catch(S){w=S}let g=m();if(N)throw x;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await y(t),m(),h?(o.length=0,d=0,f=0):(o.sort((k,P)=>k.path.localeCompare(P.path,"en")),s.sort((k,P)=>k.path.localeCompare(P.path,"en")));let E=h?U(`comet.native.physical-selection-incomplete.v1
|
|
150
150
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):U(`comet.native.physical-selection.v1
|
|
151
|
-
${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:v}}}function zh(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 ZE(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!zh(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 Jh(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function
|
|
151
|
+
${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:v}}}function zh(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 ZE(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!zh(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 Jh(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Ih(e,t){let r=(await so(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Bh.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return U(`gitlink:${r}`)}async function Th(e,t){let i=await Ih(e,t),r=await GE(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Ih(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function pn(e,t){if(at(t)!==null)return!1;let i=D.resolve(e.projectRoot,...t.split("/"));return!Ye(D.resolve(e.nativeRoot),i)&&!Ye(D.resolve(e.runtimeDir),i)}function eP(e,t){return D.relative(e,t).split(D.sep).join("/")}function tP(e,t){return t.map(i=>D.resolve(e,...i.split(/[\\/]/u)))}function Ye(e,t){let i=D.resolve(e),r=D.resolve(t);return r===i||L(i,r)}function ne(e){return LE.has(e.code??"")}function re(e){return e.code==="ENOENT"}function Al(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
152
152
|
`)}function iP(e,t){return U(`comet.native.snapshot-policy.v1
|
|
153
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Sl(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 rP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function jh(e){let t=
|
|
153
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Sl(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 rP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function jh(e){let t=Za(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?rP(n):void 0;if(a&&!a())return!1;let o=Sl(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=Sl(i,c,a),o===null||o.size===0)return!1}return Sl(i,o,a)?.has(i.length)??!1}}function Gh(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Za(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>Za(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=iP(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(jh),excludeMatchers:i.map(jh),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 nP(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function $h(e,t,i){if(!e)return!0;let r=()=>O(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 mn(e,t,i){let r=JSON.stringify(i);return U(`${e}
|
|
154
154
|
${Buffer.byteLength(t)}:${t}
|
|
155
|
-
${Buffer.byteLength(r)}:${r}`)}function Pl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function co(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Pl(i))return e.splice(t,1),i}return null}function Yt(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Te(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function aP(e,t,i,r){if(!O(r))return{status:"budget-exhausted"};let n;try{n=await Y.open(e,"r")}catch(c){if(!O(r))return{status:"budget-exhausted"};throw c}if(!O(r))return await n.close(),{status:"budget-exhausted"};let a=lo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!O(r))return{status:"budget-exhausted"};let c=await n.stat();if(!O(r))return{status:"budget-exhausted"};if(!c.isFile()||!Yt(i,c))return{status:"changed"};for(;;){if(!O(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(!O(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!O(r))return{status:"budget-exhausted"};let d=await n.stat();return O(r)?!d.isFile()||!Yt(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 je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $e(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function er(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function lt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Uh(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=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function oP(e,t){let i=je(e,`Native snapshot entry ${t}`);$e(i,jE,`Native snapshot entry ${t}`);let r=Uh(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!uo.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:lt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Bh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function sP(e,t){let i=je(e,`Native snapshot omission ${t}`);if($e(i,$E,`Native snapshot omission ${t}`),!DE.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!BE.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Uh(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:lt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function cP(e){let t=je(e,"Native snapshot omission overflow");if($e(t,OE,"Native snapshot omission overflow"),typeof t.hash!="string"||!uo.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:er(t.count,"Native snapshot omission overflow count")}}function Zi(e,t){let i=je(e,t);if($e(i,_E,t),typeof i.hash!="string"||!uo.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=lt(i.recordCount,`${t} recordCount`),n=lt(i.storedRecordCount,`${t} storedRecordCount`),a=lt(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 Oh(e){let t=je(e,"Native Git selection evidence");if($e(t,AE,"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=Zi(t.stageBefore,"Native Git selection stageBefore"),r=Zi(t.combined,"Native Git selection combined"),n=Zi(t.stageAfter,"Native Git selection stageAfter"),a=Zi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Zi(t.finalCombined,"Native Git selection finalCombined"),s=Zi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Xt(i,n)||!Xt(n,a)||!Xt(r,o)||!Xt(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 Hh(e,t){let i=je(e,t);if($e(i,IE,t),typeof i.hash!="string"||!uo.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=lt(i.visitedNodeCount,`${t} visitedNodeCount`),n=lt(i.recordCount,`${t} recordCount`),a=lt(i.storedRecordCount,`${t} storedRecordCount`),o=lt(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 lP(e){let t=je(e,"Native physical selection evidence");if($e(t,TE,"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=Hh(t.before,"Native physical selection before"),r=Hh(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!zh(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 wi(e){let t=je(e,"Native content snapshot manifest");if($e(t,EE,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!HE.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let N=je(t.capture,"Native content snapshot capture");if($e(N,CE,"Native content snapshot capture"),N.provider!=="git"&&N.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=N.gitSelection===void 0?void 0:Oh(N.gitSelection),w=N.physicalSelection===void 0?void 0:lP(N.physicalSelection),g=null;if(N.projection!==void 0){let S=je(N.projection,"Native content snapshot projection");if($e(S,RE,"Native content snapshot projection"),S.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...S.selection===void 0?{}:{selection:Oh(S.selection)}}}if(N.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)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=je(t.limits,"Native content snapshot limits");$e(r,PE,"Native content snapshot limits");let n={maxFiles:er(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:er(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:er(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:er(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:er(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let N=je(t.policy,"Native snapshot policy");if($e(N,xE,"Native snapshot policy"),N.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(N.include)||!Array.isArray(N.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Gh({include:N.include,exclude:N.exclude,hash:N.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(oP),s=t.omitted.map(sP),c=lt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:cP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(N=>N.size>n.maxFileBytes)||o.reduce((N,x)=>N+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(N=>N.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>xl||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&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(N=>N.reason==="git-enumeration-limit"),f=s.filter(N=>N.reason==="git-selection-changed");for(let N of[...d,...f])if(N.path!=="."||N.size!==null||N.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,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(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 m=s.filter(N=>N.reason==="physical-enumeration-limit"),b=s.filter(N=>N.reason==="physical-selection-changed");for(let N of[...m,...b])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||b.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",k=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(k!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let P={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(Al(P)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return P}async function Kh(e,t,i={}){let r=wi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=Lh(i),o=Fh(i.gitSelectionLimits),s=await Vh(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Jh(s).filter(w=>pn(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>pn(e,w)),d=(w,g)=>g.some(S=>w===S||w.startsWith(`${S}/`)),f=w=>d(w,l),h=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)&&!h(w)),p=await JE(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!h(w.path)&&pn(e,w.path)&&(c.has(w.path)||!p.has(w.path)));await Wh(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let w of l)b.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)||h(w.path)||!pn(e,w.path)?!1:p.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of b)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,k=r.omissionOverflow?.hash??U("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,k=mn(k,"git-selection",{source:"git-selection",...s.overflow}));let P=w=>{E+=1,k=mn(k,"omission",w)};for(;y.length>xl;){let w=co(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");P(w)}let N=()=>({...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/${k}`,hash:k,count:E}}:{}}),x=N();for(;Al(x)>r.limits.maxManifestBytes;){let w=co(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");P(w),x=N()}return wi(x)}function uP(e,t){if(!SE.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(G(e,t),"baseline-manifest.json")}async function Yh(e,t={}){let i={maxFiles:t.limits?.maxFiles??ao.maxFiles,maxFileBytes:t.limits?.maxFileBytes??ao.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??ao.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??ao.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Gh(t.policy),n=Lh({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Fh(t.gitSelectionLimits),o=WE(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=D.resolve(e.projectRoot),c=await Y.realpath(s),l=D.resolve(e.nativeRoot),u=await Y.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),h=D.join(s,".comet","current-change.json"),v=tP(s,t.denylist??[]),p=[],m=[],b=new Map,y=new Map,E=0,k=0,P=U("comet.native.snapshot-omission-overflow.v1"),N=0,x=!1,w=null,g=_=>{k+=1,P=mn(P,"omission",_)},S=_=>{if(E+=1,m.length<xl){m.push(_);return}if(Pl(_)){let A=co(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),m.push(_);return}g(_)},$=_=>{E+=_.count,k+=_.count,P=mn(P,"git-selection",{source:"git-selection",..._})},I=_=>{k+=1,P=mn(P,"manifest-entry",{reason:"manifest-size",entry:_})},fe=async(_,A)=>{p.push(_),N+=_.size,b.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},X=(_,A)=>{let T=p.findIndex(K=>K.path===_);if(T<0)return;let[B]=p.splice(T,1);N-=B.size,b.delete(_),S(A)},J=async(_,A,T,B)=>{if(!T.isFile()||T.isSymbolicLink()||!O(n))return;let K;try{K=await Y.realpath(_)}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:T.size,type:"file",reason:re(R)?"changed-during-read":"unreadable"});return}if(!O(n)||!L(c,K)||Ye(u,K))return;if(p.length>=i.maxFiles){S({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){S({path:A,size:T.size,type:"file",reason:"file-size"});return}if(N+T.size>i.maxTotalBytes){S({path:A,size:T.size,type:"file",reason:"total-size"});return}let M,H,Z;try{if(M=await aP(K,T.size,T,n),M.status==="budget-exhausted"||!O(n))return;if(M.status==="changed"){S({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!O(n)||(Z=await Y.realpath(_),!O(n)))return;H=await Y.lstat(_)}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:T.size,type:"file",reason:re(R)?"changed-during-read":"unreadable"});return}if(O(n)){if(M.bytes!==T.size||Z!==K||!Yt(T,M.finalStat)||!Yt(M.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==T.size||H.mtimeMs!==T.mtimeMs||H.ctimeMs!==T.ctimeMs){S({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}O(n)&&await fe({path:A,hash:M.hash,size:H.size,type:"file",...B===void 0?{}:{gitObjectId:B}},{kind:"file",target:_,realTarget:K,stat:H})}},it=async(_,A,T)=>{if(!O(n))return;let B,K,M;try{if(B=await Y.readlink(_,{encoding:"buffer"}),!O(n)||(M=await Y.lstat(_),!O(n)))return;K=await Y.readlink(_,{encoding:"buffer"})}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:null,type:"other",reason:re(R)?"changed-during-read":"unreadable"});return}if(!O(n))return;if(!M.isSymbolicLink()||!Yt(T,M)||M.mtimeMs!==T.mtimeMs||M.ctimeMs!==T.ctimeMs||!B.equals(K)){S({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=B.byteLength;if(p.length>=i.maxFiles){S({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){S({path:A,size:H,type:"other",reason:"file-size"});return}if(N+H>i.maxTotalBytes){S({path:A,size:H,type:"other",reason:"total-size"});return}let Z=lo("sha256").update("symlink\0").update(B).digest("hex");O(n)&&await fe({path:A,hash:Z,size:H,type:"file"},{kind:"symlink",target:_,rawTarget:B,stat:M})},Fe=async()=>{for(let[_,A]of[...b]){if(!O(n))return;if(A.kind==="file"){let H,Z;try{if(H=await Y.realpath(A.target),!O(n))return;Z=await Y.lstat(A.target)}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;X(_,{path:_,size:null,type:"file",reason:ne(R)?"unreadable":"changed-during-read"});continue}if(!O(n))return;(H!==A.realTarget||!Z.isFile()||Z.isSymbolicLink()||!Yt(A.stat,Z)||Z.size!==A.stat.size||Z.mtimeMs!==A.stat.mtimeMs||Z.ctimeMs!==A.stat.ctimeMs)&&X(_,{path:_,size:Z.isFile()?Z.size:null,type:Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,Z;try{if(H=await Y.lstat(A.target),!O(n))return;Z=await Y.readlink(A.target,{encoding:"buffer"})}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;X(_,{path:_,size:null,type:"other",reason:ne(R)?"unreadable":"changed-during-read"});continue}if(!O(n))return;(!H.isSymbolicLink()||!Yt(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Z))&&X(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let T,B;try{if(T=await Y.realpath(A.target),!O(n))return;B=await Y.lstat(A.target)}catch{if(!O(n))return;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!O(n))return;if(!(T===A.realTarget&&B.isDirectory()&&!B.isSymbolicLink()&&Yt(A.stat,B)&&L(c,T)&&!Ye(u,T))){X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!O(n))return;M=await Ih(n,T)}catch(H){if(tr(H))throw H;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!O(n))return;M.dirty?X(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!O(n))return;try{let T=await Y.lstat(A);if(!O(n))return;S({path:_,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!O(n))return;if(re(T))continue;if(!ne(T))throw T;S({path:_,size:null,type:"file",reason:"unreadable"})}}},Se=await Vh(n,e,a,t.gitSelectionHooks);if(Se===null){let _=await _h({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let B of _.records){if(B.type!=="file"&&B.type!=="symlink"||b.has(B.path))continue;if(Ke(n)<1)break;if(!$h(r,B.path,n))continue;if(Ke(n)<1)break;let K=D.resolve(s,...B.path.split("/")),M;try{M=await Y.lstat(K)}catch(H){if(!O(n))break;if(!ne(H)&&!re(H))throw H;S({path:B.path,size:null,type:"file",reason:re(H)?"changed-during-read":"unreadable"});continue}if(Ke(n)<1)break;if(B.type==="symlink"&&M.isSymbolicLink()){if(await it(K,B.path,M),Ke(n)<1)break;continue}if(B.type!=="file"||!M.isFile()||M.isSymbolicLink()){S({path:B.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(K,B.path,M),Ke(n)<1)break}Ke(n)>=1&&await Fe();let A=await _h({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),T=ZE(_.evidence,A.evidence);w=T.evidence;for(let B of[..._.omissions,...A.omissions,...T.omissions])m.some(K=>K.path===B.path&&K.reason===B.reason)||S(B)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,T=!1;if(_){let R=wi(_);for(let Q of R.entries)Q.gitObjectId!==void 0&&A.set(Q.path,Q);T=A.size>0}let B=new Set,K=!0;try{let R=await hn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)T=!1,K=!1,A.clear();else for(let Q of R.records){let ee=so(Q),ve=ee.indexOf(" "),pe=ve<0?null:ir(ee.slice(ve+1));if(ve!==1||pe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&B.add(pe)}}catch(R){if(tr(R))throw R;T=!1,K=!1,A.clear()}let M=new Set;try{let R=await oo(n,s,["ls-files","--modified","-z"],El);for(let Q of R.toString("utf8").split("\0")){let ee=ir(Q);ee!==null&&M.add(ee)}}catch{T=!1,K=!1,A.clear()}let H=new Set,Z=new Set;for(let R of Jh(Se)){if(b.has(R)||!pn(e,R))continue;if(Ke(n)<1)break;if(!$h(r,R,n))continue;if(Ke(n)<1)break;let Q=D.resolve(s,...R.split("/"));if(Q===f||Q===h||Ye(d,Q)||v.some(Ee=>Ye(Ee,Q)))continue;if(Se.gitlinks.has(R)){if(p.length>=i.maxFiles){S({path:R,size:0,type:"file",reason:"file-count"});continue}let Ee,qn;try{[Ee,qn]=await Promise.all([Y.realpath(Q),Y.lstat(Q)])}catch{S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(qn.isSymbolicLink()||!qn.isDirectory()||!L(c,Ee)||Ye(u,Ee)){S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ei=await Ih(n,Ee);if(Ei.dirty){S({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await fe({path:R,hash:Ei.hash,size:0,type:"file"},{kind:"gitlink",target:Q,realTarget:Ee,stat:qn,hash:Ei.hash})}catch(Ei){if(tr(Ei))throw Ei;S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await Y.lstat(Q)}catch(Ee){if(re(Ee)&&Se.tracked.has(R)){y.set(R,Q);continue}if(!ne(Ee)&&!re(Ee))throw Ee;S({path:R,size:null,type:"file",reason:re(Ee)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await it(Q,R,ee);continue}if(!ee.isFile()){Se.nestedRepositories.has(R)||S({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let ve=Se.trackedObjectIds.get(R),pe=ve?A.get(R):void 0;if(T&&pe?.gitObjectId!==void 0&&pe.gitObjectId===ve&&!B.has(R)&&!M.has(R)){if(p.length>=i.maxFiles){S({path:R,size:pe.size,type:"file",reason:"file-count"});continue}if(pe.size>i.maxFileBytes){S({path:R,size:pe.size,type:"file",reason:"file-size"});continue}if(N+pe.size>i.maxTotalBytes){S({path:R,size:pe.size,type:"file",reason:"total-size"});continue}p.push({...pe}),N+=pe.size,H.add(R);continue}let id=K&&!B.has(R)&&!M.has(R)?ve:void 0;await J(Q,R,ee,id),id!==void 0&&Z.add(R)}if(await Fe(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Wh(n,e,a,Se,t.gitSelectionHooks?.outputChunkBytes),H.size>0||T&&Z.size>0){let R=await oo(n,s,["ls-files","--modified","-z"],El),Q=new Set;for(let ee of R.toString("utf8").split("\0")){let ve=ir(ee);ve!==null&&Q.add(ve)}for(let ee of H){if(!Q.has(ee))continue;let ve=p.find(pe=>pe.path===ee);X(ee,{path:ee,size:ve?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Z){if(!Q.has(ee))continue;let ve=p.find(pe=>pe.path===ee);ve&&delete ve.gitObjectId}}for(let R of Se.omissions)S(R);Se.overflow&&$(Se.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let ow=Se===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Se.evidence?{gitSelection:Se.evidence}:{}},td=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:ow,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:m,omittedCount:E,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${P}`,hash:P,count:k}}:{}}),ss=td();for(;Al(ss)>i.maxManifestBytes;){if(m.filter(A=>!Pl(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T=0;T<A;T+=1){let B=co(m);if(B===null)break;g(B)}}else if(p.length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let T of p.splice(-A))E+=1,I(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");ss=td()}return ss}async function _l(e,t,i={}){let n=(await Pe(e.projectRoot))?.native.snapshot??ol;return Yh(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 fo(e,t){let i=uP(e,t),r=se(e,i);await z(r,i);try{let n=await Sh({root:r,file:i,maxBytes:kE,label:"Native baseline snapshot manifest"});return wi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as AP}from"crypto";import _P from"path";var Oe=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{constants as po,promises as Xe}from"node:fs";import Qe from"node:path";import{TextDecoder as EP}from"node:util";import NP from"path";var vP=br(Bi(),1);var K$=4*1024*1024;var gP=null;function wP(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Xh(e,t){return(...i)=>{let r=gP;if(r===null)return t(...i);let n=wP(`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 eO=Xh("hookWritePolicy",async e=>(await Xc(e))?.hook??{allow_paths:[]});var Qh=(e,t)=>{let i=e[t];return i==null?null:String(i)};function gn(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 vn(e,t){let i=gn(e,t);if(NP.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 bP(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 Zh(e){if(!e.run_id)return null;let t=gn(e,"run_id"),i=gn(e,"skill"),r=gn(e,"skill_version"),n=gn(e,"skill_hash"),a=vn(e,"pending_ref"),o=vn(e,"trajectory_ref"),s=vn(e,"context_ref"),c=vn(e,"artifacts_ref"),l=vn(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:Qh(e,"current_step"),iteration:u,pending:Qh(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:bP(e)}}var YO=256*1024;var kP=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function SP(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=Zh(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Tl(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=>!kP.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 SP(t)}var nr={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 mo(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function PP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ho(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 xP(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vo(e,t,i){let r=Oe[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Qe.resolve(e),a=Qe.resolve(n,...r.slice(8).split("/"));if(!mo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function em(e){let t=await Xe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Xe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function CP(e,t){let i=Qe.resolve(e),r=Qe.resolve(t);if(!mo(i,r))throw new Error("Native Run path is outside its change");let n=[await em(i)],a=i;for(let o of Qe.relative(i,r).split(Qe.sep).filter(Boolean)){a=Qe.join(a,o);let s;try{s=await em(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!mo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function tm(e){for(let t of e){let i=await Xe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xP(t,i)||await Xe.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function RP(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 go(e,t,i,r,n){let a=await CP(e,Qe.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Xe.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=PP(o),c=await Xe.realpath(t);if(!mo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?po.O_RDONLY:po.O_RDONLY|po.O_NOFOLLOW|po.O_NONBLOCK,u;try{u=await Xe.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),Xe.lstat(t),Xe.realpath(t)]);if(await tm(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!ho(s,d)||!ho(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await RP(u,i,r);await n?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([u.stat(),Xe.lstat(t),Xe.realpath(t)]);if(await tm(a),!m.isFile()||m.isSymbolicLink()||b!==c||!ho(s,p)||!ho(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new EP("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()}}function im(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Il(e){return Tl(e)}async function ar(e,t){let i=vo(e,"stateRef"),r=await go(e,i,nr.runStateBytes,"Native Run state",t);return r?Tl(im(r.text,"Native Run state")):null}async function yi(e,t,i){let r=vo(e,"trajectoryRef",t),n=await go(e,r,nr.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>nr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${nr.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 rm(e,t,i){return(await go(e,vo(e,"trajectoryRef",t),nr.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function wo(e,t,i){let r=await go(e,vo(e,"checkpointRef",t),nr.checkpointBytes,"Native Run checkpoint",i);return r?im(r.text,"Native Run checkpoint"):null}var TP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function jl(e){return AP("sha256").update(e).digest("hex")}function IP(e,t){if(!TP.test(t))throw new Error(`Invalid Native change name: ${t}`);return _P.join(G(e,t),"trajectory.jsonl")}function jP(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function $P(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function OP(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=jP(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(`
|
|
156
|
-
`)])}catch(d){if(!$P(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:jl(t),targetHash:jl(l),tailHash:jl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function HP(e,t){let i=
|
|
157
|
-
${t}`).digest("hex")}async function om(e,t){let i=await
|
|
155
|
+
${Buffer.byteLength(r)}:${r}`)}function Pl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function lo(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Pl(i))return e.splice(t,1),i}return null}function Yt(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ie(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function aP(e,t,i,r){if(!O(r))return{status:"budget-exhausted"};let n;try{n=await Y.open(e,"r")}catch(c){if(!O(r))return{status:"budget-exhausted"};throw c}if(!O(r))return await n.close(),{status:"budget-exhausted"};let a=uo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!O(r))return{status:"budget-exhausted"};let c=await n.stat();if(!O(r))return{status:"budget-exhausted"};if(!c.isFile()||!Yt(i,c))return{status:"changed"};for(;;){if(!O(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(!O(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!O(r))return{status:"budget-exhausted"};let d=await n.stat();return O(r)?!d.isFile()||!Yt(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 je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $e(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function er(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function lt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Uh(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=D.posix.normalize(e);if(i!==e||D.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function oP(e,t){let i=je(e,`Native snapshot entry ${t}`);$e(i,jE,`Native snapshot entry ${t}`);let r=Uh(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!fo.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:lt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Bh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function sP(e,t){let i=je(e,`Native snapshot omission ${t}`);if($e(i,$E,`Native snapshot omission ${t}`),!DE.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!BE.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Uh(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:lt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function cP(e){let t=je(e,"Native snapshot omission overflow");if($e(t,OE,"Native snapshot omission overflow"),typeof t.hash!="string"||!fo.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:er(t.count,"Native snapshot omission overflow count")}}function Zi(e,t){let i=je(e,t);if($e(i,_E,t),typeof i.hash!="string"||!fo.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=lt(i.recordCount,`${t} recordCount`),n=lt(i.storedRecordCount,`${t} storedRecordCount`),a=lt(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 Oh(e){let t=je(e,"Native Git selection evidence");if($e(t,AE,"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=Zi(t.stageBefore,"Native Git selection stageBefore"),r=Zi(t.combined,"Native Git selection combined"),n=Zi(t.stageAfter,"Native Git selection stageAfter"),a=Zi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Zi(t.finalCombined,"Native Git selection finalCombined"),s=Zi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Xt(i,n)||!Xt(n,a)||!Xt(r,o)||!Xt(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 Hh(e,t){let i=je(e,t);if($e(i,TE,t),typeof i.hash!="string"||!fo.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=lt(i.visitedNodeCount,`${t} visitedNodeCount`),n=lt(i.recordCount,`${t} recordCount`),a=lt(i.storedRecordCount,`${t} storedRecordCount`),o=lt(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 lP(e){let t=je(e,"Native physical selection evidence");if($e(t,IE,"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=Hh(t.before,"Native physical selection before"),r=Hh(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!zh(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 wi(e){let t=je(e,"Native content snapshot manifest");if($e(t,EE,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!HE.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let N=je(t.capture,"Native content snapshot capture");if($e(N,CE,"Native content snapshot capture"),N.provider!=="git"&&N.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=N.gitSelection===void 0?void 0:Oh(N.gitSelection),w=N.physicalSelection===void 0?void 0:lP(N.physicalSelection),g=null;if(N.projection!==void 0){let S=je(N.projection,"Native content snapshot projection");if($e(S,RE,"Native content snapshot projection"),S.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...S.selection===void 0?{}:{selection:Oh(S.selection)}}}if(N.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)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=je(t.limits,"Native content snapshot limits");$e(r,PE,"Native content snapshot limits");let n={maxFiles:er(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:er(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:er(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:er(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:er(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let N=je(t.policy,"Native snapshot policy");if($e(N,xE,"Native snapshot policy"),N.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(N.include)||!Array.isArray(N.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Gh({include:N.include,exclude:N.exclude,hash:N.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(oP),s=t.omitted.map(sP),c=lt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:cP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(N=>N.size>n.maxFileBytes)||o.reduce((N,x)=>N+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(N=>N.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>xl||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&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(N=>N.reason==="git-enumeration-limit"),f=s.filter(N=>N.reason==="git-selection-changed");for(let N of[...d,...f])if(N.path!=="."||N.size!==null||N.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,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(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 m=s.filter(N=>N.reason==="physical-enumeration-limit"),b=s.filter(N=>N.reason==="physical-selection-changed");for(let N of[...m,...b])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||b.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",k=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(k!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let P={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(Al(P)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return P}async function Kh(e,t,i={}){let r=wi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=D.resolve(e.projectRoot),a=Lh(i),o=Fh(i.gitSelectionLimits),s=await Vh(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Jh(s).filter(w=>pn(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>pn(e,w)),d=(w,g)=>g.some(S=>w===S||w.startsWith(`${S}/`)),f=w=>d(w,l),h=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)&&!h(w)),p=await JE(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!h(w.path)&&pn(e,w.path)&&(c.has(w.path)||!p.has(w.path)));await Wh(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let w of l)b.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)||h(w.path)||!pn(e,w.path)?!1:p.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of b)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,k=r.omissionOverflow?.hash??U("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,k=mn(k,"git-selection",{source:"git-selection",...s.overflow}));let P=w=>{E+=1,k=mn(k,"omission",w)};for(;y.length>xl;){let w=lo(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");P(w)}let N=()=>({...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/${k}`,hash:k,count:E}}:{}}),x=N();for(;Al(x)>r.limits.maxManifestBytes;){let w=lo(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");P(w),x=N()}return wi(x)}function uP(e,t){if(!SE.test(t))throw new Error(`Invalid Native change name: ${t}`);return D.join(G(e,t),"baseline-manifest.json")}async function Yh(e,t={}){let i={maxFiles:t.limits?.maxFiles??oo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??oo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??oo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??oo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Gh(t.policy),n=Lh({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Fh(t.gitSelectionLimits),o=WE(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=D.resolve(e.projectRoot),c=await Y.realpath(s),l=D.resolve(e.nativeRoot),u=await Y.realpath(l),d=D.resolve(e.runtimeDir),f=D.resolve(e.configFile),h=D.join(s,".comet","current-change.json"),v=tP(s,t.denylist??[]),p=[],m=[],b=new Map,y=new Map,E=0,k=0,P=U("comet.native.snapshot-omission-overflow.v1"),N=0,x=!1,w=null,g=_=>{k+=1,P=mn(P,"omission",_)},S=_=>{if(E+=1,m.length<xl){m.push(_);return}if(Pl(_)){let A=lo(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),m.push(_);return}g(_)},$=_=>{E+=_.count,k+=_.count,P=mn(P,"git-selection",{source:"git-selection",..._})},T=_=>{k+=1,P=mn(P,"manifest-entry",{reason:"manifest-size",entry:_})},fe=async(_,A)=>{p.push(_),N+=_.size,b.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},X=(_,A)=>{let I=p.findIndex(K=>K.path===_);if(I<0)return;let[B]=p.splice(I,1);N-=B.size,b.delete(_),S(A)},J=async(_,A,I,B)=>{if(!I.isFile()||I.isSymbolicLink()||!O(n))return;let K;try{K=await Y.realpath(_)}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:I.size,type:"file",reason:re(R)?"changed-during-read":"unreadable"});return}if(!O(n)||!L(c,K)||Ye(u,K))return;if(p.length>=i.maxFiles){S({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){S({path:A,size:I.size,type:"file",reason:"file-size"});return}if(N+I.size>i.maxTotalBytes){S({path:A,size:I.size,type:"file",reason:"total-size"});return}let M,H,Z;try{if(M=await aP(K,I.size,I,n),M.status==="budget-exhausted"||!O(n))return;if(M.status==="changed"){S({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!O(n)||(Z=await Y.realpath(_),!O(n)))return;H=await Y.lstat(_)}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:I.size,type:"file",reason:re(R)?"changed-during-read":"unreadable"});return}if(O(n)){if(M.bytes!==I.size||Z!==K||!Yt(I,M.finalStat)||!Yt(M.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==I.size||H.mtimeMs!==I.mtimeMs||H.ctimeMs!==I.ctimeMs){S({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}O(n)&&await fe({path:A,hash:M.hash,size:H.size,type:"file",...B===void 0?{}:{gitObjectId:B}},{kind:"file",target:_,realTarget:K,stat:H})}},it=async(_,A,I)=>{if(!O(n))return;let B,K,M;try{if(B=await Y.readlink(_,{encoding:"buffer"}),!O(n)||(M=await Y.lstat(_),!O(n)))return;K=await Y.readlink(_,{encoding:"buffer"})}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:null,type:"other",reason:re(R)?"changed-during-read":"unreadable"});return}if(!O(n))return;if(!M.isSymbolicLink()||!Yt(I,M)||M.mtimeMs!==I.mtimeMs||M.ctimeMs!==I.ctimeMs||!B.equals(K)){S({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=B.byteLength;if(p.length>=i.maxFiles){S({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){S({path:A,size:H,type:"other",reason:"file-size"});return}if(N+H>i.maxTotalBytes){S({path:A,size:H,type:"other",reason:"total-size"});return}let Z=uo("sha256").update("symlink\0").update(B).digest("hex");O(n)&&await fe({path:A,hash:Z,size:H,type:"file"},{kind:"symlink",target:_,rawTarget:B,stat:M})},Fe=async()=>{for(let[_,A]of[...b]){if(!O(n))return;if(A.kind==="file"){let H,Z;try{if(H=await Y.realpath(A.target),!O(n))return;Z=await Y.lstat(A.target)}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;X(_,{path:_,size:null,type:"file",reason:ne(R)?"unreadable":"changed-during-read"});continue}if(!O(n))return;(H!==A.realTarget||!Z.isFile()||Z.isSymbolicLink()||!Yt(A.stat,Z)||Z.size!==A.stat.size||Z.mtimeMs!==A.stat.mtimeMs||Z.ctimeMs!==A.stat.ctimeMs)&&X(_,{path:_,size:Z.isFile()?Z.size:null,type:Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,Z;try{if(H=await Y.lstat(A.target),!O(n))return;Z=await Y.readlink(A.target,{encoding:"buffer"})}catch(R){if(!O(n))return;if(!ne(R)&&!re(R))throw R;X(_,{path:_,size:null,type:"other",reason:ne(R)?"unreadable":"changed-during-read"});continue}if(!O(n))return;(!H.isSymbolicLink()||!Yt(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Z))&&X(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,B;try{if(I=await Y.realpath(A.target),!O(n))return;B=await Y.lstat(A.target)}catch{if(!O(n))return;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!O(n))return;if(!(I===A.realTarget&&B.isDirectory()&&!B.isSymbolicLink()&&Yt(A.stat,B)&&L(c,I)&&!Ye(u,I))){X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!O(n))return;M=await Th(n,I)}catch(H){if(tr(H))throw H;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!O(n))return;M.dirty?X(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!O(n))return;try{let I=await Y.lstat(A);if(!O(n))return;S({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!O(n))return;if(re(I))continue;if(!ne(I))throw I;S({path:_,size:null,type:"file",reason:"unreadable"})}}},Se=await Vh(n,e,a,t.gitSelectionHooks);if(Se===null){let _=await _h({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let B of _.records){if(B.type!=="file"&&B.type!=="symlink"||b.has(B.path))continue;if(Ke(n)<1)break;if(!$h(r,B.path,n))continue;if(Ke(n)<1)break;let K=D.resolve(s,...B.path.split("/")),M;try{M=await Y.lstat(K)}catch(H){if(!O(n))break;if(!ne(H)&&!re(H))throw H;S({path:B.path,size:null,type:"file",reason:re(H)?"changed-during-read":"unreadable"});continue}if(Ke(n)<1)break;if(B.type==="symlink"&&M.isSymbolicLink()){if(await it(K,B.path,M),Ke(n)<1)break;continue}if(B.type!=="file"||!M.isFile()||M.isSymbolicLink()){S({path:B.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(K,B.path,M),Ke(n)<1)break}Ke(n)>=1&&await Fe();let A=await _h({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=ZE(_.evidence,A.evidence);w=I.evidence;for(let B of[..._.omissions,...A.omissions,...I.omissions])m.some(K=>K.path===B.path&&K.reason===B.reason)||S(B)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=wi(_);for(let Q of R.entries)Q.gitObjectId!==void 0&&A.set(Q.path,Q);I=A.size>0}let B=new Set,K=!0;try{let R=await hn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,K=!1,A.clear();else for(let Q of R.records){let ee=co(Q),ve=ee.indexOf(" "),pe=ve<0?null:ir(ee.slice(ve+1));if(ve!==1||pe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&B.add(pe)}}catch(R){if(tr(R))throw R;I=!1,K=!1,A.clear()}let M=new Set;try{let R=await so(n,s,["ls-files","--modified","-z"],El);for(let Q of R.toString("utf8").split("\0")){let ee=ir(Q);ee!==null&&M.add(ee)}}catch{I=!1,K=!1,A.clear()}let H=new Set,Z=new Set;for(let R of Jh(Se)){if(b.has(R)||!pn(e,R))continue;if(Ke(n)<1)break;if(!$h(r,R,n))continue;if(Ke(n)<1)break;let Q=D.resolve(s,...R.split("/"));if(Q===f||Q===h||Ye(d,Q)||v.some(Ee=>Ye(Ee,Q)))continue;if(Se.gitlinks.has(R)){if(p.length>=i.maxFiles){S({path:R,size:0,type:"file",reason:"file-count"});continue}let Ee,Vn;try{[Ee,Vn]=await Promise.all([Y.realpath(Q),Y.lstat(Q)])}catch{S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Vn.isSymbolicLink()||!Vn.isDirectory()||!L(c,Ee)||Ye(u,Ee)){S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ei=await Th(n,Ee);if(Ei.dirty){S({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await fe({path:R,hash:Ei.hash,size:0,type:"file"},{kind:"gitlink",target:Q,realTarget:Ee,stat:Vn,hash:Ei.hash})}catch(Ei){if(tr(Ei))throw Ei;S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await Y.lstat(Q)}catch(Ee){if(re(Ee)&&Se.tracked.has(R)){y.set(R,Q);continue}if(!ne(Ee)&&!re(Ee))throw Ee;S({path:R,size:null,type:"file",reason:re(Ee)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await it(Q,R,ee);continue}if(!ee.isFile()){Se.nestedRepositories.has(R)||S({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let ve=Se.trackedObjectIds.get(R),pe=ve?A.get(R):void 0;if(I&&pe?.gitObjectId!==void 0&&pe.gitObjectId===ve&&!B.has(R)&&!M.has(R)){if(p.length>=i.maxFiles){S({path:R,size:pe.size,type:"file",reason:"file-count"});continue}if(pe.size>i.maxFileBytes){S({path:R,size:pe.size,type:"file",reason:"file-size"});continue}if(N+pe.size>i.maxTotalBytes){S({path:R,size:pe.size,type:"file",reason:"total-size"});continue}p.push({...pe}),N+=pe.size,H.add(R);continue}let id=K&&!B.has(R)&&!M.has(R)?ve:void 0;await J(Q,R,ee,id),id!==void 0&&Z.add(R)}if(await Fe(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Wh(n,e,a,Se,t.gitSelectionHooks?.outputChunkBytes),H.size>0||I&&Z.size>0){let R=await so(n,s,["ls-files","--modified","-z"],El),Q=new Set;for(let ee of R.toString("utf8").split("\0")){let ve=ir(ee);ve!==null&&Q.add(ve)}for(let ee of H){if(!Q.has(ee))continue;let ve=p.find(pe=>pe.path===ee);X(ee,{path:ee,size:ve?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Z){if(!Q.has(ee))continue;let ve=p.find(pe=>pe.path===ee);ve&&delete ve.gitObjectId}}for(let R of Se.omissions)S(R);Se.overflow&&$(Se.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let ow=Se===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Se.evidence?{gitSelection:Se.evidence}:{}},td=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:ow,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:m,omittedCount:E,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${P}`,hash:P,count:k}}:{}}),ss=td();for(;Al(ss)>i.maxManifestBytes;){if(m.filter(A=>!Pl(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let B=lo(m);if(B===null)break;g(B)}}else if(p.length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I of p.splice(-A))E+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");ss=td()}return ss}async function _l(e,t,i={}){let n=(await Pe(e.projectRoot))?.native.snapshot??ol;return Yh(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 po(e,t){let i=uP(e,t),r=se(e,i);await z(r,i);try{let n=await Sh({root:r,file:i,maxBytes:kE,label:"Native baseline snapshot manifest"});return wi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as AP}from"crypto";import _P from"path";var Oe=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{constants as ho,promises as Xe}from"node:fs";import Qe from"node:path";import{TextDecoder as EP}from"node:util";import NP from"path";var vP=br(Bi(),1);var U$=4*1024*1024;var gP=null;function wP(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Xh(e,t){return(...i)=>{let r=gP;if(r===null)return t(...i);let n=wP(`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 Z$=Xh("hookWritePolicy",async e=>(await Xc(e))?.hook??{allow_paths:[]});var Qh=(e,t)=>{let i=e[t];return i==null?null:String(i)};function gn(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 vn(e,t){let i=gn(e,t);if(NP.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 bP(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 Zh(e){if(!e.run_id)return null;let t=gn(e,"run_id"),i=gn(e,"skill"),r=gn(e,"skill_version"),n=gn(e,"skill_hash"),a=vn(e,"pending_ref"),o=vn(e,"trajectory_ref"),s=vn(e,"context_ref"),c=vn(e,"artifacts_ref"),l=vn(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:Qh(e,"current_step"),iteration:u,pending:Qh(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:bP(e)}}var KO=256*1024;var kP=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function SP(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=Zh(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Il(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=>!kP.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 SP(t)}var nr={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 vo(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function PP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function mo(e,t){return 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 xP(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function go(e,t,i){let r=Oe[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Qe.resolve(e),a=Qe.resolve(n,...r.slice(8).split("/"));if(!vo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function em(e){let t=await Xe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Xe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function CP(e,t){let i=Qe.resolve(e),r=Qe.resolve(t);if(!vo(i,r))throw new Error("Native Run path is outside its change");let n=[await em(i)],a=i;for(let o of Qe.relative(i,r).split(Qe.sep).filter(Boolean)){a=Qe.join(a,o);let s;try{s=await em(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!vo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function tm(e){for(let t of e){let i=await Xe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xP(t,i)||await Xe.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function RP(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 wo(e,t,i,r,n){let a=await CP(e,Qe.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Xe.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=PP(o),c=await Xe.realpath(t);if(!vo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?ho.O_RDONLY:ho.O_RDONLY|ho.O_NOFOLLOW|ho.O_NONBLOCK,u;try{u=await Xe.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),Xe.lstat(t),Xe.realpath(t)]);if(await tm(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!mo(s,d)||!mo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await RP(u,i,r);await n?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([u.stat(),Xe.lstat(t),Xe.realpath(t)]);if(await tm(a),!m.isFile()||m.isSymbolicLink()||b!==c||!mo(s,p)||!mo(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new EP("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()}}function im(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Tl(e){return Il(e)}async function ar(e,t){let i=go(e,"stateRef"),r=await wo(e,i,nr.runStateBytes,"Native Run state",t);return r?Il(im(r.text,"Native Run state")):null}async function yi(e,t,i){let r=go(e,"trajectoryRef",t),n=await wo(e,r,nr.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>nr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${nr.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 rm(e,t,i){return(await wo(e,go(e,"trajectoryRef",t),nr.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function yo(e,t,i){let r=await wo(e,go(e,"checkpointRef",t),nr.checkpointBytes,"Native Run checkpoint",i);return r?im(r.text,"Native Run checkpoint"):null}var IP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function jl(e){return AP("sha256").update(e).digest("hex")}function TP(e,t){if(!IP.test(t))throw new Error(`Invalid Native change name: ${t}`);return _P.join(G(e,t),"trajectory.jsonl")}function jP(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function $P(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function OP(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=jP(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(`
|
|
156
|
+
`)])}catch(d){if(!$P(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:jl(t),targetHash:jl(l),tailHash:jl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function HP(e,t){let i=TP(e,t);await z(se(e,i),i);let r=G(e,t),n=await rm(r,Oe.trajectoryRef);return n===null?{status:"clean",file:i}:OP(i,Buffer.from(n))}async function nm(e,t){let i=await HP(e,t);return"inspection"in i?i.inspection:i}import{createHash as BP}from"node:crypto";import{promises as No}from"node:fs";import yt from"node:path";var wn=/^[a-f0-9]{64}$/u,am=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,LP=16*1024,Ol=process.platform,FP=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function or(e){return FP.has(e)}function cm(e,t){let i=yt.relative(e,t);return yt.isAbsolute(i)||i===".."||i.startsWith(`..${yt.sep}`)?null:i.replaceAll("\\","/")||"."}function lm(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function um(e,t){if(e.length===0||lm(e)||e.includes("\\")||yt.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=yt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Hl(e,t){return BP("sha256").update(`${e}
|
|
157
|
+
${t}`).digest("hex")}async function om(e,t){let i=await No.realpath(t),r=await No.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Ol==="win32"?yt.normalize(i).toLowerCase():i;return Hl(e,`${n}
|
|
158
158
|
${r.dev}
|
|
159
159
|
${r.ino}
|
|
160
|
-
${r.birthtimeMs}`)}async function sm(e,t){let i=await
|
|
160
|
+
${r.birthtimeMs}`)}async function sm(e,t){let i=await No.realpath(t),r=await No.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Ol==="win32"?yt.normalize(i).toLowerCase():i;return Hl(e,n)}function MP(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 $l(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||lm(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function dm(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if($l(e.changeBranch,"Native workspace change branch"),$l(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 qP(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"||!am.test(t.baseCommit)||typeof t.targetCommit!="string"||!am.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");$l(t.targetBranch,"Native workspace Git target branch")}function bo(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"||!wn.test(String(t.projectRootId))||!wn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");MP(t.capturedAt),um(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&&!wn.test(String(t.projectRootPathId))||a&&!wn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!wn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&qP(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(dm(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 VP(e,t){return yt.join(G(e,t),"workspace.json")}function WP(e,t){let i=VP(e,t),r=se(e,i),n=cm(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:um(n,"Native workspace file ref")}}async function zP(e,t){try{let i=WP(e,t),r=await oe({root:i.root,ref:i.ref,maxBytes:LP});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ko(e,t){let i=Me(e.projectRoot),r={projectRoot:yt.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await Nt(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 yn({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 JP(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=cm(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?cs(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:cs(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([om("comet.native.workspace-project-root.v2",e.paths.projectRoot),om("comet.native.workspace-native-root.v2",e.paths.nativeRoot),sm("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),sm("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&&dm(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:Hl("comet.native.workspace-session.v2",`${s}
|
|
161
161
|
${c}
|
|
162
|
-
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return
|
|
163
|
-
`);function kn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wm(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
|
|
164
|
-
`).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
|
|
165
|
-
`))}function px(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(_m))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(_m))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Tm(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Im(e.markdown)},markdown:e.markdown}}function hx(e,t){return jm(e.id,t.id)}function jm(e,t){return e<t?-1:e>t?1:0}function $m(e){let t=Tm(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(px).sort((d,f)=>jm(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=dl(e.briefMarkdown,t,En.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...fl(f,d.source,En.maxAcceptanceCriteria-a.length)),a.push(...pl(f,d.source,En.maxAcceptanceCriteria-a.length)));if(a.sort(hx),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>En.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${En.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:Im(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=j(fx,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(dx,u)}}var Ao={maxSpecs:64,maxFileBytes:en,maxTotalBytes:4*1024*1024};async function sr(e){if(e.specChanges.length>Ao.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await oe({root:e.changeDir,ref:e.briefRef,maxBytes:Ao.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 oe({root:e.changeDir,ref:n.source,maxBytes:Ao.maxFileBytes});if(i+=a.size,i>Ao.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:$m({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import mx from"path";var zl="comet.selection.v2",vx=16*1024;function Hm(e){return mx.join(e,".comet","current-change.json")}function gx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Om(e){return e===null||typeof e=="string"}function wx(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(!gx(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&&!Om(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:zl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==zl)throw new Error(`current change selection schema must be ${zl}`);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(!Om(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 Dm(e){let t;try{let r=Hm(e),{bytes:n}=await Mi(r,vx,{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",...wx(t)}}import{promises as Zx}from"node:fs";import eu from"node:path";var Yl=br(Bi(),1);import{promises as qm}from"node:fs";import He from"node:path";import{execFileSync as yx}from"node:child_process";var Nx=3e4,bx=8*1024*1024,Jl=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 kx(e,t){try{return yx("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Nx,maxBuffer:bx,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Jl(e,t,r)}}function Gl(e,t){return kx(e,t).trim()}var Bm="children.yaml",Ul="comet.native.children.v1",Pn="comet.native.children.v2",Sx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ex=new Set(["schema","children"]),Px=new Set(["schema","acceptance_index","children"]),xx=new Set(["name","depends_on","covers"]);function To(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _o(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 Lm(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 Kl(e,t){let i=He.normalize(He.resolve(e)),r=He.normalize(He.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Cx(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 Fm(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Vm(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function Rx(e){let t=To(e,"Native children acceptance_index"),i={};for(let[r,n]of Object.entries(t)){let a=To(n,`Native children acceptance_index.${r}`);if(_o(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function Ax(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text)throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog`)}}function _x(e,t,i={}){let r=(0,Yl.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=To(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a===Pn?_o(n,Px,"Native children contract"):_o(n,Ex,"Native children contract"),a!==Ul&&a!==Pn)throw new Error(`Native children schema must be ${Ul} or ${Pn}`);if(!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let o=n.children.map((l,u)=>{let d=To(l,`Native child ${u}`);if(_o(d,xx,`Native child ${u}`),typeof d.name!="string"||!Sx.test(d.name))throw new Error(`Native child ${u} name is invalid`);return{name:d.name,depends_on:Lm(d.depends_on,`Native child ${d.name} depends_on`),covers:Lm(d.covers,`Native child ${d.name} covers`)}}),s=o.map(({name:l})=>l);if(new Set(s).size!==s.length)throw new Error("Native child names must be unique");let c=new Set(s);for(let l of o){let u=l.depends_on.filter(d=>!c.has(d));if(u.length>0)throw new Error(`Native child ${l.name} depends on unknown child: ${u.join(", ")}`)}if(Cx(o),a===Pn){let l=Rx(n.acceptance_index);if(Ax(l,t,i),t){let u=Object.keys(l);Fm(o,u,u)}return{schema:Pn,acceptance_index:l,children:o}}return t&&Fm(o,t),{schema:Ul,children:o}}async function Wm(e){let t=He.join(e.changeDir,Bm);try{await qm.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await oe({root:e.changeDir,ref:Bm});return{contract:_x(i.text,e.acceptanceIds,e.validation),size:i.size}}function zm(e){return j("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 Tx(e){let t=xi(e.projectRoot);t.some(r=>Kl(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>He.resolve(n)))]){let n=await Pe(r);n&&i.push({projectRoot:r,paths:await vt(r,n.native.artifact_root),parent:Kl(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function Ix(e,t){let i=He.join(e.paths.changesDir,t,"comet-state.yaml");try{return await un(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function jx(e,t){let i;try{i=await qm.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=He.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await un(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function $x(e,t,i){let r=He.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${He.sep}`))return null;let n=r.split(He.sep).join("/");try{let a=(0,Yl.parseDocument)(Gl(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ln(a.toJS({mapAsMap:!1}))}catch{return null}}function Ox(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 Mm(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Xl(e){let t=He.join(e.paths.changesDir,e.state.name),i=await Wm({changeDir:t,validation:Vm(e.state),...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=zm({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await Tx(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 m=p.parent&&o?`refs/heads/${o}`:"HEAD";for(let b of await jx(p,s)){let y={...b,source:p,committedState:$x(p,b.file,m)};c.set(b.state.name,[...c.get(b.state.name)??[],y])}for(let b of s){let y=await Ix(p,b);y&&l.set(b,[...l.get(b)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let m=(c.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&Mm(k,o));if(m){u.set(p.name,{kind:"done",phase:m.state.phase,projectRoot:m.source.projectRoot,message:null});continue}let b=c.get(p.name)?.[0];if(b){u.set(p.name,{kind:"blocked",phase:b.state.phase,projectRoot:b.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,Ox(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 m=f.get(p);if(m)return m;let b=d.get(p),E=b.depends_on.map(h).every(({status:g})=>g==="done"),k=u.get(p),P=k?.kind==="active"&&E?b.depends_on.filter(g=>!(c.get(g)??[]).some(({source:S,committedState:$})=>Kl(S.projectRoot,k.projectRoot)&&$?.name===g&&Mm($,o))):[],N,x=k?.message??null;k?.kind==="done"?(N=E?"done":"blocked",E||(x=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(N=E&&P.length===0?"active":"blocked",E?P.length>0&&(x=`Native child ${p} does not include merged dependencies: ${P.join(", ")}`):x=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?N="blocked":(N=n&&E?"ready":"pending",n||(x="Parent Shape confirmation is required"));let w={name:p,dependsOn:[...b.depends_on],covers:[...b.covers],status:N,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:x};return f.set(p,w),w},v=i.contract.children.map(({name:p})=>h(p));return{contractHash:r,confirmed:n,parentBranch:o,children:v,readyChildren:v.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:v.every(({status:p})=>p==="done")}}var EH=["$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 Hx=/\b(Bearer|Basic)\s+[^\s"']+/giu,Dx=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Bx=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Lx=/\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,Fx=/("(?:[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,Mx=/(["'])((?:[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,qx=/\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 De(e){return e.replace(Hx,"$1 [REDACTED]").replace(Dx,"[REDACTED PRIVATE KEY]").replace(Bx,"$1[REDACTED]@").replace(Lx,"[REDACTED TOKEN]").replace(Fx,'$1"[REDACTED]"').replace(Mx,"$1$2$1$3$4[REDACTED]$4").replace(qx,"$1$2[REDACTED]")}import{promises as Ux}from"node:fs";import Jm from"node:path";function Io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jo(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 ut(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 Gm(e,t){return e===null?null:ut(e,t)}function Oo(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Kx(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function Yx(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function $o(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ql(e,t){if(e===null)return null;let i=ut(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Zl(e,t){let i=ut(e,t);if(!Jm.isAbsolute(i))throw new Error(`${t} must be absolute`);return Jm.resolve(i)}function Xx(e,t){let i=`Native local checks[${t}]`,r=Io(e,i);if(jo(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>ut(l,`${i}.argv[${u}]`,!0)),a=$o(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Ql(r.startedAt,`${i}.startedAt`),s=Ql(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=Oo(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:ut(r.id,`${i}.id`),name:ut(r.name,`${i}.name`),operationId:ut(r.operationId,`${i}.operationId`),status:a,repeatable:Yx(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Oo(r.executionCount,`${i}.executionCount`),argv:n,cwd:Zl(r.cwd,`${i}.cwd`),exitCode:Kx(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:ut(r.log,`${i}.log`)}}function Qx(e){let t="Native local execution state",i=Io(e,t);if(jo(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==eo)throw new Error(`Native local execution schema must be ${eo}`);let r=Io(i.workspace,"Native local workspace");jo(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Io(i.execution,"Native local execution");jo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Ql(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:ut(o.operationId,"Native local execution.operationId"),stage:$o(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:$o(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Gm(o.executionId,"Native local execution.executionId"),status:$o(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Oo(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(Xx);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:eo,change:ut(i.change,"Native local change"),basedOnStateVersion:Oo(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Zl(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zl(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Gm(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Um(e){let t;try{t=await Ux.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 Qx(i)}var eC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tC="comet-state.yaml",iC="state.json";function Km(e,t){if(!eC.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=eu.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}function Ym(e,t){return eu.join(Km(e,t),tC)}function rC(e,t){return eu.join(zi(e,t),iC)}async function tu(e,t){try{let i=await Zx.readFile(Ym(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Xm(e,t){return un(Ym(e,t))}async function Qm(e){let t=await Xm(e.paths,e.name),i=rC(e.paths,e.name);try{let r=await Um(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 tB=16*1024;async function Zm(e){let t=await Dm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(xo(t.selection.change),t.selection)}async function ev(e,t){let i=[],r=G(e,t.name),n=Wt(r,Oe.stateRef),a;try{a=await ar(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=Wt(r,a.trajectoryRef),s=await nm(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 yi(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=Wt(r,a.checkpointRef);try{let u=await wo(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}import KC from"path";import{isDeepStrictEqual as bu}from"util";var cr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var nC=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function aC(e,t){return e<t?-1:e>t?1:0}function oC(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"||!nC.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(aC)}function iu(e=[]){return oC(e,"Native repair failed check IDs",cr.maxFailedCheckIds,!0)}function tv(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function sC(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:tv(e.failedAcceptanceIds,t.failedAcceptanceIds)&&tv(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function ru(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(sC(r,a))break;i+=1,r=a}return i}import bv from"node:path";import{createHash as lv}from"node:crypto";import iv from"path";var nu="comet.native.implementation-scope.v2",uv="comet.native.content-snapshot-projection.v1",xn="comet.native.content-snapshot-projection.v1",dv="comet.native.implementation-scope.v2",cC="comet.native.unresolved-scope-id.v1",lC="comet.native.scope-detail-overflow.v1",uC="comet.native.snapshot-projection-overflow.v2",cu=/^[a-f0-9]{64}$/u,ki=1024*1024,dC=128,fC=128;function he(e,t){return e<t?-1:e>t?1:0}function au(e){if(!cu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function pC(e,t){return e===t?0:e===null?-1:t===null?1:he(e,t)}function ti(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=iv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||iv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function fv(e,t){return e==="."?e:ti(e,t)}function lr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function hC(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:ti(e.path,`${t} path`),hash:e.hash,size:lr(e.size,`${t} size`),type:"file"}}function mC(e,t){return{path:fv(e.path,`${t} path`),size:e.size===null?null:lr(e.size,`${t} size`),type:e.type,reason:e.reason}}function vC(e,t){return he(e.path,t.path)||he(e.hash,t.hash)||e.size-t.size}function gC(e,t){return he(e.path,t.path)||he(e.reason,t.reason)||he(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Rn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
162
|
+
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return bo(h),h}async function Nt(e,t){let i=await zP(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(bo(i),i)}async function So(e){bo(e.identity);let t=await JP({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")),Ol==="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 yn(e){if(bo(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 So(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 fm(e,t){let i=await Nt(e,t);if(i===null)return null;let r=await yn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var mm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],UP=new Set(mm),vm=new Set([...mm,"minimum_runtime_version","revision"]),KP=new Set([...vm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),YP=new Set(["capability","operation","source","base_hash"]),XP=new Set(["shape","build","verify","archive"]),QP=new Set(["implicit","confirmed"]),ZP=new Set(["pending","pass","fail"]),Zt="comet-state.yaml",Bl=/^[a-f0-9]{64}$/u,gm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ex=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Eo=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"},Ni=class extends Error{constructor(i,r){super(i!==zt||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"},Po=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"},Nn=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"},xo=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"},J0=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
163
|
+
`);function kn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wm(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 Co(e){if(!gm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function tx(e){if(!gm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function ym(e,t){if(e.length===0||bt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function ix(e,t){let i=kn(e,`spec_changes[${t}]`);if(wm(i,YP,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(tx(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"&&ym(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"||!Bl.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"||!Bl.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 rx(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 Fl(e,t){if(wm(e,t,Zt),typeof e.name!="string")throw new Error("Native change name is required");if(Co(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"||!XP.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&&!QP.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(ix),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"||!ZP.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"&&ym(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!rx(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 Xi(e){let t=kn(e,Zt);if(t.schema!==Gt)throw new Error(`Expected ${Gt}`);return{schema:Gt,...Fl(t,UP)}}function bn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Dl(e,t,i){if(e===null)return null;let r=typeof e=="string"?ex.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function nx(e){if(e==null)return null;if(typeof e!="string"||!Bl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function ax(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 Qi(e){let t=kn(e,Zt);if(t.schema!==Jt)throw new Error(`Expected ${Jt}`);if(bn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Jt} minimum_runtime_version must be 2`);return{schema:Jt,minimum_runtime_version:2,revision:bn(t.revision,"Native v2 revision"),...Fl(t,vm)}}function Ut(e){let t=kn(e,Zt);if(t.schema!==zt){if(t.schema===Gt||t.schema===Jt){let o=t.schema===Gt?Xi(t):Qi(t);throw new Eo(o.name,o.schema)}throw new Ni(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=bn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ni(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=bn(t.revision,"Native revision"),n=Fl(t,KP),a=nx(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:zt,minimum_runtime_version:3,revision:r,verification_protocol:ax(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Dl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Dl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Dl(t.partial_allowance,"Native partial_allowance","allowances")}}function Nm(e){let t=kn(e,Zt);if(t.schema===Gt){let n=Xi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${zt}`}}if(t.schema===Jt){let n=Qi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${zt}`}}if(t.schema!==zt){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 Ni(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=bn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ni(t.schema,i).message};let r=Ut(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function de(e,t){Co(t);let i=bt.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Ro(e,t){let i=G(e,t),r=bt.join(i,"schema-migration.json");await z(L(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await hm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function bm(e,t){let i=G(e,t),r=bt.join(i,"checkpoint-journal.json");await z(L(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await hm.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function km(e,t=bt.dirname(e)){let i=bt.relative(t,e).split(bt.sep).join("/"),r=await oe({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,Ll.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 Ml(e,t){let i=bt.join(de(e,t),Zt);await z(e.nativeRoot,i);let r=Nm(await km(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Ro(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 ox(e,r.state),r)}async function Sm(e,t){let i=bt.join(de(e,t),Zt);await z(e.nativeRoot,i);let r=Nm(await km(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function ox(e,t){if(await po(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function kt(e,t){let i=await Ml(e,t);if(i.status==="migration-required")throw new Eo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ni(i.schema,i.minimumRuntimeVersion);return await fm(e,t),i.state}import{promises as w_}from"fs";import{promises as ql}from"fs";import Em from"path";var Pm=["Outcome","Scope","Non-goals","Acceptance examples"],sx=[...Pm,"Constraints and invariants","Decisions","Open questions","Verification expectations"],cx=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],xm={maxFileBytes:en};function Cm(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
164
|
+
`).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 lx(e,t){let i=Em.resolve(e,...t.split(/[\\/]/u));if(!L(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await ql.realpath(e),n=await ql.realpath(i);if(!L(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ql.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Sn(e){return{valid:e.length===0,findings:e}}async function Vl(e,t){let i=[],r;try{r=(await oe({root:e,ref:t,maxBytes:xm.maxFileBytes})).text}catch(o){return Sn([{code:"brief-missing",message:o.message,path:t}])}let n=Cm(r);for(let o of sx)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Pm)(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}),Sn(i)}async function Wl(e,t){let i=[],r;try{r=(await oe({root:e,ref:t,maxBytes:xm.maxFileBytes})).text}catch(a){return Sn([{code:"verification-missing",message:a.message,path:t}])}let n=Cm(r);for(let a of cx)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 Sn(i)}function Ao(e,t){return Em.join(e.specsDir,t,"spec.md")}async function Rm(e,t){let i=[],r=de(e,t.name);for(let n of t.spec_changes){let a=Ao(e,n.capability),o=null;try{await z(e.nativeRoot,a),o=await Nl(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 lx(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Sn(i)}import Am from"node:path";var ux="comet.native.contract.v1",dx="comet.native.acceptance-set.v1",_m=/^[a-f0-9]{64}$/u,En={maxAcceptanceCriteria:sn.maxCriteria};function Im(e,t){let i=Am.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})||Am.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 Tm(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
165
|
+
`))}function fx(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(_m))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(_m))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Im(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Tm(e.markdown)},markdown:e.markdown}}function px(e,t){return jm(e.id,t.id)}function jm(e,t){return e<t?-1:e>t?1:0}function $m(e){let t=Im(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(fx).sort((d,f)=>jm(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=dl(e.briefMarkdown,t,En.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...fl(f,d.source,En.maxAcceptanceCriteria-a.length)),a.push(...pl(f,d.source,En.maxAcceptanceCriteria-a.length)));if(a.sort(px),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>En.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${En.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:Tm(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=j(dx,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(ux,u)}}var _o={maxSpecs:64,maxFileBytes:en,maxTotalBytes:4*1024*1024};async function sr(e){if(e.specChanges.length>_o.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await oe({root:e.changeDir,ref:e.briefRef,maxBytes:_o.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 oe({root:e.changeDir,ref:n.source,maxBytes:_o.maxFileBytes});if(i+=a.size,i>_o.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:$m({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import hx from"path";var zl="comet.selection.v2",mx=16*1024;function Hm(e){return hx.join(e,".comet","current-change.json")}function vx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Om(e){return e===null||typeof e=="string"}function gx(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(!vx(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&&!Om(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:zl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==zl)throw new Error(`current change selection schema must be ${zl}`);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(!Om(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 Dm(e){let t;try{let r=Hm(e),{bytes:n}=await Mi(r,mx,{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",...gx(t)}}import{promises as Qx}from"node:fs";import eu from"node:path";var Yl=br(Bi(),1);import{promises as qm}from"node:fs";import He from"node:path";import{execFileSync as wx}from"node:child_process";var yx=3e4,Nx=8*1024*1024,Jl=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 bx(e,t){try{return wx("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:yx,maxBuffer:Nx,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Jl(e,t,r)}}function Gl(e,t){return bx(e,t).trim()}var Bm="children.yaml",Ul="comet.native.children.v1",Pn="comet.native.children.v2",kx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Sx=new Set(["schema","children"]),Ex=new Set(["schema","acceptance_index","children"]),Px=new Set(["name","depends_on","covers"]);function To(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Io(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 Lm(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 Kl(e,t){let i=He.normalize(He.resolve(e)),r=He.normalize(He.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function xx(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 Fm(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Vm(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function Cx(e){let t=To(e,"Native children acceptance_index"),i={};for(let[r,n]of Object.entries(t)){let a=To(n,`Native children acceptance_index.${r}`);if(Io(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function Rx(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text)throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog`)}}function Ax(e,t,i={}){let r=(0,Yl.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=To(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a===Pn?Io(n,Ex,"Native children contract"):Io(n,Sx,"Native children contract"),a!==Ul&&a!==Pn)throw new Error(`Native children schema must be ${Ul} or ${Pn}`);if(!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let o=n.children.map((l,u)=>{let d=To(l,`Native child ${u}`);if(Io(d,Px,`Native child ${u}`),typeof d.name!="string"||!kx.test(d.name))throw new Error(`Native child ${u} name is invalid`);return{name:d.name,depends_on:Lm(d.depends_on,`Native child ${d.name} depends_on`),covers:Lm(d.covers,`Native child ${d.name} covers`)}}),s=o.map(({name:l})=>l);if(new Set(s).size!==s.length)throw new Error("Native child names must be unique");let c=new Set(s);for(let l of o){let u=l.depends_on.filter(d=>!c.has(d));if(u.length>0)throw new Error(`Native child ${l.name} depends on unknown child: ${u.join(", ")}`)}if(xx(o),a===Pn){let l=Cx(n.acceptance_index);if(Rx(l,t,i),t){let u=Object.keys(l);Fm(o,u,u)}return{schema:Pn,acceptance_index:l,children:o}}return t&&Fm(o,t),{schema:Ul,children:o}}async function Wm(e){let t=He.join(e.changeDir,Bm);try{await qm.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await oe({root:e.changeDir,ref:Bm});return{contract:Ax(i.text,e.acceptanceIds,e.validation),size:i.size}}function zm(e){return j("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 _x(e){let t=xi(e.projectRoot);t.some(r=>Kl(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>He.resolve(n)))]){let n=await Pe(r);n&&i.push({projectRoot:r,paths:await vt(r,n.native.artifact_root),parent:Kl(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function Ix(e,t){let i=He.join(e.paths.changesDir,t,"comet-state.yaml");try{return await un(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Tx(e,t){let i;try{i=await qm.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=He.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await un(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function jx(e,t,i){let r=He.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${He.sep}`))return null;let n=r.split(He.sep).join("/");try{let a=(0,Yl.parseDocument)(Gl(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ln(a.toJS({mapAsMap:!1}))}catch{return null}}function $x(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 Mm(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Xl(e){let t=He.join(e.paths.changesDir,e.state.name),i=await Wm({changeDir:t,validation:Vm(e.state),...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=zm({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await _x(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 m=p.parent&&o?`refs/heads/${o}`:"HEAD";for(let b of await Tx(p,s)){let y={...b,source:p,committedState:jx(p,b.file,m)};c.set(b.state.name,[...c.get(b.state.name)??[],y])}for(let b of s){let y=await Ix(p,b);y&&l.set(b,[...l.get(b)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let m=(c.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&Mm(k,o));if(m){u.set(p.name,{kind:"done",phase:m.state.phase,projectRoot:m.source.projectRoot,message:null});continue}let b=c.get(p.name)?.[0];if(b){u.set(p.name,{kind:"blocked",phase:b.state.phase,projectRoot:b.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,$x(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 m=f.get(p);if(m)return m;let b=d.get(p),E=b.depends_on.map(h).every(({status:g})=>g==="done"),k=u.get(p),P=k?.kind==="active"&&E?b.depends_on.filter(g=>!(c.get(g)??[]).some(({source:S,committedState:$})=>Kl(S.projectRoot,k.projectRoot)&&$?.name===g&&Mm($,o))):[],N,x=k?.message??null;k?.kind==="done"?(N=E?"done":"blocked",E||(x=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(N=E&&P.length===0?"active":"blocked",E?P.length>0&&(x=`Native child ${p} does not include merged dependencies: ${P.join(", ")}`):x=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?N="blocked":(N=n&&E?"ready":"pending",n||(x="Parent Shape confirmation is required"));let w={name:p,dependsOn:[...b.depends_on],covers:[...b.covers],status:N,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:x};return f.set(p,w),w},v=i.contract.children.map(({name:p})=>h(p));return{contractHash:r,confirmed:n,parentBranch:o,children:v,readyChildren:v.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:v.every(({status:p})=>p==="done")}}var 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("; ");var Ox=/\b(Bearer|Basic)\s+[^\s"']+/giu,Hx=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Dx=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Bx=/\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,Lx=/("(?:[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,Fx=/(["'])((?:[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,Mx=/\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 De(e){return e.replace(Ox,"$1 [REDACTED]").replace(Hx,"[REDACTED PRIVATE KEY]").replace(Dx,"$1[REDACTED]@").replace(Bx,"[REDACTED TOKEN]").replace(Lx,'$1"[REDACTED]"').replace(Fx,"$1$2$1$3$4[REDACTED]$4").replace(Mx,"$1$2[REDACTED]")}import{promises as Gx}from"node:fs";import Jm from"node:path";function jo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $o(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 ut(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 Gm(e,t){return e===null?null:ut(e,t)}function Ho(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Ux(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function Kx(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Oo(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ql(e,t){if(e===null)return null;let i=ut(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Zl(e,t){let i=ut(e,t);if(!Jm.isAbsolute(i))throw new Error(`${t} must be absolute`);return Jm.resolve(i)}function Yx(e,t){let i=`Native local checks[${t}]`,r=jo(e,i);if($o(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>ut(l,`${i}.argv[${u}]`,!0)),a=Oo(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Ql(r.startedAt,`${i}.startedAt`),s=Ql(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=Ho(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:ut(r.id,`${i}.id`),name:ut(r.name,`${i}.name`),operationId:ut(r.operationId,`${i}.operationId`),status:a,repeatable:Kx(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Ho(r.executionCount,`${i}.executionCount`),argv:n,cwd:Zl(r.cwd,`${i}.cwd`),exitCode:Ux(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:ut(r.log,`${i}.log`)}}function Xx(e){let t="Native local execution state",i=jo(e,t);if($o(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==to)throw new Error(`Native local execution schema must be ${to}`);let r=jo(i.workspace,"Native local workspace");$o(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=jo(i.execution,"Native local execution");$o(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Ql(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:ut(o.operationId,"Native local execution.operationId"),stage:Oo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Oo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Gm(o.executionId,"Native local execution.executionId"),status:Oo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Ho(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(Yx);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:to,change:ut(i.change,"Native local change"),basedOnStateVersion:Ho(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Zl(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zl(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Gm(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Um(e){let t;try{t=await Gx.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 Xx(i)}var Zx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eC="comet-state.yaml",tC="state.json";function Km(e,t){if(!Zx.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=eu.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}function Ym(e,t){return eu.join(Km(e,t),eC)}function iC(e,t){return eu.join(zi(e,t),tC)}async function tu(e,t){try{let i=await Qx.readFile(Ym(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Xm(e,t){return un(Ym(e,t))}async function Qm(e){let t=await Xm(e.paths,e.name),i=iC(e.paths,e.name);try{let r=await Um(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 eB=16*1024;async function Zm(e){let t=await Dm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Co(t.selection.change),t.selection)}async function ev(e,t){let i=[],r=G(e,t.name),n=Wt(r,Oe.stateRef),a;try{a=await ar(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=Wt(r,a.trajectoryRef),s=await nm(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 yi(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=Wt(r,a.checkpointRef);try{let u=await yo(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}import UC from"path";import{isDeepStrictEqual as bu}from"util";var cr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var rC=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function nC(e,t){return e<t?-1:e>t?1:0}function aC(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"||!rC.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(nC)}function iu(e=[]){return aC(e,"Native repair failed check IDs",cr.maxFailedCheckIds,!0)}function tv(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function oC(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:tv(e.failedAcceptanceIds,t.failedAcceptanceIds)&&tv(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function ru(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(oC(r,a))break;i+=1,r=a}return i}import bv from"node:path";import{createHash as lv}from"node:crypto";import iv from"path";var nu="comet.native.implementation-scope.v2",uv="comet.native.content-snapshot-projection.v1",xn="comet.native.content-snapshot-projection.v1",dv="comet.native.implementation-scope.v2",sC="comet.native.unresolved-scope-id.v1",cC="comet.native.scope-detail-overflow.v1",lC="comet.native.snapshot-projection-overflow.v2",cu=/^[a-f0-9]{64}$/u,ki=1024*1024,uC=128,dC=128;function he(e,t){return e<t?-1:e>t?1:0}function au(e){if(!cu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function fC(e,t){return e===t?0:e===null?-1:t===null?1:he(e,t)}function ti(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=iv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||iv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function fv(e,t){return e==="."?e:ti(e,t)}function lr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function pC(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:ti(e.path,`${t} path`),hash:e.hash,size:lr(e.size,`${t} size`),type:"file"}}function hC(e,t){return{path:fv(e.path,`${t} path`),size:e.size===null?null:lr(e.size,`${t} size`),type:e.type,reason:e.reason}}function mC(e,t){return he(e.path,t.path)||he(e.hash,t.hash)||e.size-t.size}function vC(e,t){return he(e.path,t.path)||he(e.reason,t.reason)||he(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Rn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
166
166
|
`,"utf8")}function ei(e,t,i){let r=`${t}
|
|
167
|
-
${Sr(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function
|
|
168
|
-
`),e.omissionOverflow&&ei(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,ei(a,"omission",f)},s=f=>{r+=1,n+=1,ei(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(;Rn(u)>ki;){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 v=0;v<h;v+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))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 ou(e){let t=wi(e),i=t.entries.map((n,a)=>
|
|
169
|
-
`);let i=0;lu(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ei(t,"change",n);let a=0;for(let o of e.declaredArtifacts)_n(o,n.path)&&(a+=1,ei(t,"change-attribution",o));ei(t,"change-end",{attributionCount:a}),a===0&&ei(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&&ei(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function wv(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=kC(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(S=>!w.has(S)||n.some($=>_n($,S)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(xn,e),c=j(xn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=fC)break;l.push(St({kind:"snapshot-omission",source:x,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${x} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...nv("baseline",e),...nv("current",t),...o.totalChanges===0&&a===null?[St({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 x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>x.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!x.has(w))}},v=x=>{let w=o.candidates.slice(0,x.detailedChangeCount),g=w.filter(Fe=>Fe.attributedTo.length===0&&!u.has(Fe.path)),S=o.totalChanges-w.length,$=o.totalUnattributed-g.length,I=d-x.detailedOmissionCount,fe=$+I,X=[...g.map(Fe=>St({kind:"unattributed-change",source:"implementation-scope",path:Fe.path,evidence:{after:Fe.after,before:Fe.before,changeKind:Fe.kind}},`Changed path is not covered by a declared artifact: ${Fe.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...fe>0?[gv(x.overflowHash,{changes:S,unattributed:$,unresolved:fe})]:[]],J=NC(X),it=x.includeGitAdvisory?h():void 0;return{schema:nu,contractHash:r,baselineProjectionRef:au(s),baselineProjectionHash:s,currentProjectionRef:au(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:J,noCodeReason:a,...it?{gitAdvisory:it}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,m=l.length,b=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:y});if(Rn({...x,scopeHash:y})<=ki)break;if(b){b=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/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 k=o.totalChanges>p||d>m?EC({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:m}):y,P=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:k}),N={...P,scopeHash:j(dv,P)};if(Rn(N)>ki)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return N}function du(e){let t=ou(e.baseline),i=ou(e.current),r=vv(e);return{authority:r,baseline:t,current:i,scope:wv(t,i,r)}}var PC=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ft(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 bi(e,t){if(typeof e!="string"||!cu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ov(e,t,i){let r=au(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Ho(e,t){let i=dt(e,"Native snapshot projection");if(ft(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==uv)throw new Error("Native snapshot projection schema is invalid");let r=wi({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=ou(r);if(j(xn,i)!==j(xn,n))throw new Error("Native snapshot projection is not canonical");let a=j(xn,n);if(t!==void 0&&bi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function fu(e,t){let i=dt(e,`Declared artifact ${t}`);if(ft(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ti(i.path,`Declared artifact ${t} path`),kind:i.kind}}function sv(e,t){if(e===null)return null;let i=dt(e,t);return ft(i,["hash","size"],[],t),{hash:bi(i.hash,`${t} hash`),size:lr(i.size,`${t} size`)}}function cv(e,t){let i=dt(e,`Implementation change ${t}`);if(ft(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(fu),n=An(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=sv(i.before,`Implementation change ${t} before`),o=sv(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:ti(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function xC(e,t){let i=dt(e,`Unresolved scope ${t}`);ft(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"?fv(i.path,`Unresolved scope ${t} path`):ti(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Cn(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)=>ti(n,`${t} ${a}`)),r=[...new Set(i)].sort(he);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function yv(e){let t=dt(e,"Native implementation external drift");if(ft(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=Cn(t.paths,"Native external drift paths");return mv({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Do(e){let t=dt(e,"Native implementation scope"),i=[...PC].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(ft(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==nu)throw new Error("Native implementation scope schema is invalid");let r=bi(t.contractHash,"Implementation scope contractHash"),n=bi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=ov(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=bi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=ov(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(fu);if(JSON.stringify(c)!==JSON.stringify(An(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(cv),u=[...l].sort((g,S)=>he(g.path,S.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(S=>!d.has(`${S.kind}:${S.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(S=>_n(S,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(cv),h=t.externalDrift===void 0?void 0:yv(t.externalDrift),v=new Set(h?.paths??[]),p=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(xC),b=m.filter(g=>g.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=b[0]===void 0?null:SC(b[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,k=[...p.map(g=>St({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?[St({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")]:[]],P=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(su))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(P)!==JSON.stringify(k.sort(su))||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 N;if(t.gitAdvisory!==void 0){let g=dt(t.gitAdvisory,"Implementation scope Git advisory");if(ft(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let S=Cn(g.changedPaths,"Git changed paths"),$=Cn(g.pathsPresentInSnapshotChanges,"Git present paths"),I=Cn(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),fe=[...$,...I].sort(he);if(JSON.stringify(fe)!==JSON.stringify(S)||I.some(X=>l.some(J=>J.path===X)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:S,pathsPresentInSnapshotChanges:$,pathsAbsentFromSnapshotChanges:I}}let x={schema:nu,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:E,...N?{gitAdvisory:N}:{},...h?{externalDrift:h}:{}},w=bi(t.scopeHash,"Implementation scope scopeHash");if(j(dv,x)!==w)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:w}}function CC(e){let t=dt(e,"Native implementation scope authority");if(ft(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(fu);if(JSON.stringify(i)!==JSON.stringify(An(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=Cn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:yv(t.externalDrift),a=vv({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 Tn(e){let t=dt(e,"Native implementation scope bundle");ft(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=CC(t.authority),r=Ho(t.baseline),n=Ho(t.current),a=Do(t.scope),o=wv(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 Nv(e){let t=Do(e.scope);return Tn({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})}var Sv=/^[a-f0-9]{64}$/u;var RC="comet.native.acceptance-trace.v2",AC="comet.native.partial-allowance.v1",_C="comet.native.verification-evidence.v2";function Et(e,t){if(!Sv.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ev(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Pv(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 pu(e,t,i=2e3){let r=De(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function In(e,t){let i=bv.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})||bv.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 TC(e,t,i){let r=In(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=at(r),a=r.toLowerCase(),o=i?In(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 hu(e){let t=In(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 ur(e,t){return e<t?-1:e>t?1:0}function Bo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Lo(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 xv(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 kv(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 IC(e){let t=Bo(e,"Native acceptance trace");if(Lo(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"||!Sv.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=In(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Bo(o,`Native acceptance trace entry ${s}`);if(Lo(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=>hu(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ur))||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:In(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:pu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>ur(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=Et(t.traceHash,"Native acceptance trace hash");if(j(RC,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Cv(e){let t=Bo(e,"Native partial allowance");if(Lo(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(ur))||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:Pv(t.change),scopeHash:Et(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:pu(t.reason,"Partial allowance reason"),confirmedSummary:pu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ev(t.sourceRevision),confirmedAt:xv(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=Et(t.allowanceHash,"Native partial allowance hash");if(j(AC,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function mu(e){let t=Bo(e,"Native verification evidence");if(Lo(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=Et(t.implementationScopeHash,"Native verification implementation scope hash"),r=IC(t.acceptanceTrace),n=Et(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:Et(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>hu(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ur)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(ur);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=>hu(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ur)))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:Pv(t.change),sourceRevision:Ev(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Et(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:kv(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:TC(t.reportRef,"Native verification report ref"),reportHash:Et(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:kv(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:xv(t.createdAt,"Native verification timestamp")},d=Et(t.envelopeHash,"Native verification envelope hash");if(j(_C,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function vu(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 Rv="repairStagnation",Re={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},$C=/^[a-f0-9]{64}$/u;var OC=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),HC=["data","runId","sequence","timestamp","type"],Av=["disposition","overrideSummaryHash","signatureHash"],DC=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],_v=12;function wu(e,t){return e<t?-1:e>t?1:0}function Tv(e,t,i){let r=Object.keys(e).sort(wu);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Fo(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 jn(e,t){if(typeof e!="string"||!$C.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function BC(e){if(!Array.isArray(e)||e.length>cr.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(wu)}function Iv(e){if(typeof e!="string"||e.length===0||e.length>Re.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 gu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Re.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Re.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>Re.maxTextCharacters&&(!n||e.length>Re.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Re.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>Re.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>gu(s,t+1,i,`${r}[${c}]`));return}let a=Fo(e,r),o=Object.keys(a);if(o.length>Re.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Re.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Re.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");gu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function LC(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 FC(e,t,i){let r=Fo(e,`Native repair trajectory event ${t+1}`);if(Tv(r,HC,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(LC(r.timestamp),typeof r.type!="string"||!OC.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Iv(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 gu(r.data,0,n,"Native trajectory event data"),Fo(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function yu(e){let t=Fo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(wu),r=i.length===Av.length&&i.every((l,u)=>l===Av[u]);r||Tv(t,DC,"Native repair trajectory projection");let n=jn(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:jn(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=jn(t.contractHash,"Native repair trajectory contract hash"),s=BC(t.failedAcceptanceIds),c=iu(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 MC(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 qC(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??_v;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=ru({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<cr.warningAtConsecutiveFailures?"continue":a<cr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function VC(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??_v;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 jv(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Re.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Iv(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;l<e.committedTrajectoryOffset;l+=1){let u=FC(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Re.maxTotalDataNodes||c>Re.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?jn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?jn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Rv)){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 v=yu(f[Rv]);if(MC(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&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),qC(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&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");VC(v,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:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>cr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function $v(e){return jv(e).history}function Ov(e){let t=jv(e).latestProjection;return t?{...t}:null}var dr={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:[]},Nu=U("comet-native-runtime:v3:scope-reopen"),WC=[{skillVersion:"3",skillHash:U("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:U("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:U("comet-native-runtime:v1")}];function Hv(e){return e.skillVersion===dr.definition.metadata.version&&e.skillHash===Nu||WC.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Dv(e){return U(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 qv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],YC=new Set(qv),Vv=new Set([...qv,"minimum_runtime_version","revision"]),XC=new Set([...Vv,"operation"]),QC=512*1024,ku=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),ZC=new Set([...ku,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Su=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 Pu(e,t){return KC.join(G(e,t),"transition.json")}function qo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function xu(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 Mo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Eu(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=>!ZC.has(u)),a=[...ku].find(u=>!Object.hasOwn(i,u)),o=ku.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(vu(i.summary,"Native transition journal event summary"),De(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&&(vu(i.noCodeReason,"Native transition journal event no-code reason"),De(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")?yu(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 eR(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 Eu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Eu(e,t)}function Cu(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?eR(e.eventData,e.evidenceHash):Eu(e.eventData,e.evidenceHash),n=Il(e.nextRun),a=e.previousRun===null?null:Il(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Bv(e,t,i=!1){if(e.skill!==dr.definition.metadata.name||(i?!Hv(e):e.skillVersion!==dr.definition.metadata.version||e.skillHash!==Nu)||e.orchestration!==dr.definition.orchestration.mode||e.pendingRef!==Oe.pendingRef||e.trajectoryRef!==Oe.trajectoryRef||e.contextRef!==Oe.contextRef||e.artifactsRef!==Oe.artifactsRef||e.checkpointRef!==Oe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Lv(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 Fv(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 Ru(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Bv(o,"next Run",r||a!==null),Fv(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(Bv(a,"previous Run",!0),Fv(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(!bu(Lv(a),Lv(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function tR(e,t,i){return U(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Wv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Mv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Au(e,t,i,r,n=!1){let a=i.eventData,o=Mv(e),s=Mv(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&&bu(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&&bu(e.spec_changes,t.spec_changes),l=Dv({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=tR(e.name,a.summary,t.spec_changes),l=U(`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 iR(e,t){let i=qo(e);if(xu(i,XC),i.schema!==Ki)throw new Error(`Expected Native transition schema ${Ki}`);let r=Mo(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 ${Ki} minimum_runtime_version must be ${3}`);let n=Mo(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=Cu(i,t),o=Ut(i.previousState),s=Ut(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Au(o,s,a,i.operation),Ru(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:Ki,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 rR(e,t){let i=qo(e);if(xu(i,YC),i.schema!==dn)throw new Error(`Expected Native transition schema ${dn}`);let r=Cu(i,t,!0),n=Xi(i.previousState),a=Xi(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Au(n,a,r,Wv(n,a,r.eventData),!0),Ru(n,a,r,!0),{schema:dn,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 nR(e,t){let i=qo(e);if(xu(i,Vv),i.schema!==Yi)throw new Error(`Expected Native transition schema ${Yi}`);if(Mo(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Yi} minimum_runtime_version must be 2`);let n=Mo(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Cu(i,t,!0),o=Qi(i.previousState),s=Qi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Au(o,s,a,Wv(o,s,a.eventData),!0),Ru(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Yi,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 aR(e,t){let i=qo(e);if(i.schema===Ki)return{status:"current",journal:iR(i,t)};if(i.schema===dn)return{status:"migration-required",journal:rR(i,t)};if(i.schema===Yi)return{status:"migration-required",journal:nR(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function oR(e,t){let i=Pu(e,t),r=se(e,i);await z(r,i);try{let n=await wt({root:r,file:i,maxBytes:QC,label:`Native transition journal ${t}`});return aR(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function zv(e,t){let i=await oR(e,t);if(!i)return null;if(i.status==="migration-required")throw new Su(t);return i.journal}var sR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function cR(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function lR(e){return e?e.map(cR).join(" "):null}function uR(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 Be(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 dR(e){return e.map(t=>Be(t,[],null))}function fR(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Be("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Be("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Be("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Be("artifact-or-no-code-reason",["--no-code-reason"],"<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(Be("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Be("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Be("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function me(e,t){let i=t.commandArgs===void 0?uR(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?lR(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??dR(t.requiredInputs??[])}}function Vo(e){let i=(e.findings??[]).filter(d=>!or(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||sR.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 me(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return me(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Be("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return me(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return me(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return me(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Be("summary",["--summary"],"<summary>")]});if(n)return me(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Be("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return me(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?me(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?me(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):me(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"),me(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Be("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):me(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return me(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=fR(e.state);return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import $n from"path";var Jv=8,pR={"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 hR(e){let t=pR[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"}:or(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 mR(e,t,i){if(!i.path)return null;let r;if($n.isAbsolute(i.path)?r=$n.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=$n.resolve(de(e,t.name),...i.path.split(/[\\/]/u)):r=$n.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!L(e.projectRoot,r))return null;let n=$n.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function vR(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<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 _u(e){return e.findings.map(t=>{let i=hR(t.code);return{code:t.code,message:t.message,severity:i.severity,path:mR(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:vR(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 Tu(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,Jv),truncated:t.length>Jv}}import fr from"path";var ri={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},pr=/^[a-f0-9]{64}$/u;function Wo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zo(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 ii(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 Gv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Iu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function gR(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||fr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=fr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Uv(e,t){return fr.join(G(e,t),"checkpoints","progress.json")}function On(e,t){return fr.join(G(e,t),"checkpoint-journal.json")}function Kv(e,t,i){if(!pr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return fr.join(G(e,t),"checkpoints","manifests",`${i}.json`)}function wR(e){if(!pr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function ju(e,t,i){let r=await wt({root:e,file:t,maxBytes:ri.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function yR(e,t){let i=Wo(e,`checkpoint manifest artifact ${t}`);zo(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=gR(ii(i.path,`checkpoint artifact ${t} path`,4096)),n=at(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!pr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Iu(i.size,`checkpoint artifact ${t} size`)}}function $u(e,t){let i=Wo(e,"Native checkpoint manifest");if(zo(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>ri.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(yR),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=Iu(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>ri.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 Yv(e){return U(JSON.stringify($u(e,e.change)))}function Xv(e,t){let i=Wo(e,"Native progress checkpoint");if(zo(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=Gv(i.previousRevision,"Native checkpoint previousRevision"),a=Gv(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ii(i.manifestHash,"Native checkpoint manifestHash",64);if(!pr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=wR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ii(i.inputHash,"Native checkpoint inputHash",64);if(!pr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ii(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Iu(i.artifactCount,"Native checkpoint artifactCount");if(u>ri.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ii(i.summary,"Native checkpoint summary"),f=ii(i.nextAction,"Native checkpoint nextAction");if(De(d)!==d||De(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ii(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 NR(e,t){let i=Wo(e,"Native checkpoint journal");if(zo(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=Ut(i.previousState),n=Ut(i.nextState),a=Xv(i.checkpoint,t),o=$u(i.manifest,t),s=ii(i.inputHash,"Native checkpoint journal inputHash",64),c=U(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!pr.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!==Yv(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 bR(e,t,i){let r=fr.resolve(e.projectRoot,...t.split("/"));if(!L(e.projectRoot,r)||L(e.nativeRoot,r)||L(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=zc(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await wt({root:e.projectRoot,file:r,maxBytes:ri.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 kR(e,t){let i=Uv(e,t),r=se(e,i);await z(r,i);try{return Xv(await ju(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function SR(e,t,i){let r=Kv(e,t,i),n=se(e,r);await z(n,r);let a=await ju(n,r,"Native checkpoint manifest"),o=$u(a,t);if(Qv(e,o),Yv(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Ou(e,t){let i=On(e,t),r=se(e,i);await z(r,i);try{let n=NR(await ju(r,i,"Native checkpoint journal"),t);return Qv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Qv(e,t){for(let i of t.artifacts){let r=zc(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Zv(e){let t;try{t=await kR(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:Uv(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 SR(e.paths,e.name,t.manifestHash);let a=U(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 bR(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}}var eg=240,tg=8,Jo=50;function ig(e){let t=Array.from(e);return t.length<=eg?e:`${t.slice(0,eg-1).join("")}…`}function ER(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function PR(e){let t=[...new Set(e.map(ER))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,tg),reasonCount:e.length,codesTruncated:t.length>tg};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Jo),reasonsTruncated:e.length>Jo}}}async function rg(e){let t=null;try{let s=await Ou(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:On(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:On(e.paths,e.state.name)}}let i=await Zv({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=PR(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ri.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:ig(i.checkpoint.summary),nextAction:ig(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:ri.maxArtifacts}}import{promises as f_}from"node:fs";import Dg from"node:path";import ng from"node:path";var xR="comet.native.archive-preflight.v1",CR="comet.native.archive-preflight.v1",RR="comet.native.archive-operation.v1",AR=/^[a-f0-9]{64}$/u,ag=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_R=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Go(e,t){return e<t?-1:e>t?1:0}function TR(e,t){if(typeof e!="string"||!AR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pt(e,t){return e===null?null:TR(e,t)}function IR(e,t){let i=ng.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||ng.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 jR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function $R(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 OR(e,t){if(!ag.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=Pt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Pt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Pt(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 HR(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:Pt(e.contractHash,"Native archive contract hash"),acceptanceHash:Pt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Pt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Pt(e.reportHash,"Native archive report hash"),envelopeHash:Pt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Pt(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 DR(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!_R.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(Go);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function BR(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(Go)}function og(e){if(!ag.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(OR).sort((l,u)=>Go(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:j(RR,l)})),r=HR(e.evidence),n=$R(e.workspace),a=[...new Set([...DR(e.findingCodes??[]),...BR({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(Go),o=jR(e.revision),s=IR(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:xR,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:j(CR,c)}}import{createHash as LR}from"node:crypto";import sg from"node:path";var FR="comet.native.conflict-radar.v1",be=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}),MR="comet.native.conflict-radar.v1",qR="comet.native.conflict-radar-signals.v1",VR=/^[a-f0-9]{64}$/u,ug=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WR=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),zR=new Set(["capability","operation","baseHash"]),JR=new Set(["path","kind"]);function hr(e,t){return e<t?-1:e>t?1:0}function Hu(e){return Buffer.byteLength(e,"utf8")}function Du(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 Bu(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(Hu(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function GR(e,t){let i=Bu(e,t,be.maxArtifactPathBytes),r=sg.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)||sg.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 dg(e,t){if(typeof e!="string"||!VR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function UR(e,t){let i=Du(e,zR,t),r=Bu(i.capability,`${t} capability`,be.maxCapabilityBytes);if(!ug.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:dg(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 KR(e,t){let i=Du(e,JR,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:GR(i.path,`${t} path`),kind:i.kind}}function YR(e,t){let i=Du(e,WR,`Conflict radar change ${t}`),r=Bu(i.name,`Conflict radar change ${t} name`,be.maxNameBytes);if(!ug.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>be.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>be.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>UR(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>hr(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)=>KR(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>hr(c.path,l.path)||hr(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:dg(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function XR(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>be.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(YR).sort((n,a)=>hr(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)>be.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>be.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function QR(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 ZR(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 eA(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function tA(e,t){let i=[],r=LR("sha256").update(`${qR}
|
|
170
|
-
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Sr(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<be.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(QR(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=ZR(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:eA(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function cg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function iA(e,t){return cg(e.classification)-cg(t.classification)||hr(e.left,t.left)||hr(e.right,t.right)}function lg(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:FR,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 fg(e){let t=XR(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(tA(t[s],t[c]));i.sort(iA);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(MR,{changes:t,relationships:r}),a=i.slice(0,be.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=lg(t,i,a,n);for(;a.length>0&&Hu(JSON.stringify(o))>be.maxSerializedBytes;)a=a.slice(0,-1),o=lg(t,i,a,n);if(Hu(JSON.stringify(o))>be.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as OA}from"node:crypto";import{promises as et}from"node:fs";import pt from"node:path";import pg from"node:path";var hg="comet.native.check-receipt.v1",rA="comet.native.check-receipt.v1",mr="scoped-text-safety",Lu=1,ke=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),nA=/^[a-f0-9]{64}$/u,aA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oA="comet.native.checker-policy.v1",sA="comet.native.check-input.v1",cA=2048,mg=j(oA,{policy:mr,version:Lu,limits:ke,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),lA=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),vg=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],wg=["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"],uA=new Set(wg);function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(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 xt(e,t){if(typeof e!="string"||!nA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ae(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function yg(e,t){let i=Ae(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function gg(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 dA(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>cA||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=pg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||pg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function fA(e){let t=ni(e,"Native check receipt checker");ai(t,["policy","version","hash","limits"],"Native check receipt checker");let i=ni(t.limits,"Native check receipt limits");if(ai(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==mr||t.version!==Lu||t.hash!==mg||i.maxFiles!==ke.maxFiles||i.maxFileBytes!==ke.maxFileBytes||i.maxTotalBytes!==ke.maxTotalBytes||i.maxIssues!==ke.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:mr,version:Lu,hash:mg,limits:{...ke}}}function pA(e){let t=ni(e,"Native check receipt contract");return ai(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:xt(t.expectedHash,"Native check expected contract hash"),beforeHash:xt(t.beforeHash,"Native check before contract hash"),afterHash:xt(t.afterHash,"Native check after contract hash")}}function hA(e){let t=ni(e,"Native check receipt implementation");return ai(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:xt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:xt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:xt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:xt(t.afterSnapshotHash,"Native check after snapshot hash")}}function mA(e,t){let i=ni(e,`Native check batch ${t}`);ai(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Ae(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ae(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ae(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ae(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ae(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ae(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>ke.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>ke.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function vA(e){let t=ni(e,"Native check receipt counts");ai(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Ae(t.filesSelected,"Native check filesSelected"),filesScanned:Ae(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ae(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ae(t.bytesScanned,"Native check bytesScanned"),issueCount:Ae(t.issueCount,"Native check issueCount"),recordedIssueCount:Ae(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(mA):(()=>{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>ke.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>ke.maxFiles||i.bytesScanned>ke.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function gA(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||vg.indexOf(e.kind)-vg.indexOf(t.kind)}function wA(e){if(!Array.isArray(e)||e.length>ke.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=ni(r,`Native check issue ${n}`);if(ai(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!lA.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:dA(a.path,`Native check issue ${n} path`),line:yg(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(gA);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function yA(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!uA.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=wg.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 NA(e){return j(sA,e)}function Ng(e){let t=ni(e,"Native check receipt");if(ai(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==hg)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!aA.test(t.change))throw new Error("Native check receipt change name is invalid");let i=yg(t.sourceRevision,"Native check source revision"),r=fA(t.checker),n=pA(t.contract),a=hA(t.implementation),o=NA({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(xt(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=gg(t.startedAt,"Native check receipt startedAt"),c=gg(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=vA(t.counts),u=wA(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=yA(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>ke.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>ke.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:hg,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=xt(t.receiptHash,"Native check receipt content hash");if(j(rA,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var Mu="comet.native.verification-receipt.v3",bA=Mu,kA="comet.native.declared-artifacts.v1",SA=/^[a-f0-9]{64}$/u,EA=/^acceptance-[a-f0-9]{64}$/u,PA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,CA=4096,RA=256,AA=1024;function vr(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 oi(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 Ct(e,t){if(typeof e!="string"||!SA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ze(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=De(e).trim();if(!i||i.length>CA||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Fu(e,t){let i=Ze(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 Hn(e,t,i=Ze,r=!1,n=RA){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 _A(e,t){if(typeof e!="string"||!EA.test(e))throw new Error(`${t} is invalid`);return e}function TA(e){let t=vr(e,"Native verification receipt bindings");if(oi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!PA.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:Ct(t.contractHash,"Native verification receipt contract hash"),scopeHash:Ct(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Ct(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Ct(t.artifactHash,"Native verification receipt artifact hash")}}function IA(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=xA.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function jA(e,t,i,r){let n=vr(t,`Native ${e} evidence`);if(e==="automated-check"){if(oi(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=Fu(n.startedAt,"Native automated-check start time"),o=Fu(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=vr(n.worktree,"Native automated-check worktree");if(oi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=vr(n.afterFence,"Native automated-check after fence");if(oi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ze(n.executable,"Native automated-check executable"),args:Hn(n.args,"Native automated-check arguments",Ze,!0),cwd:Ze(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ze(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Ct(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Ct(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Ct(n.outputHash,"Native automated-check output hash"),outputSummary:Ze(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){oi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=IA(n.checkReceiptRef);if(Ct(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Hn(n.subjects,"Native static inspection subjects",Ze,r==="required-check"),rule:Ze(n.rule,"Native static inspection rule"),resultSummary:Ze(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return oi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Hn(n.steps,"Native manual evidence steps"),observations:Hn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function $A(e){let t=vr(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=Ze(t.actor,"Native verification receipt actor"),o=Hn(t.acceptanceIds,"Native receipt acceptance IDs",_A,r==="required-check",AA).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Mu,kind:i,role:r,status:n,bindings:TA(t.bindings),acceptanceIds:o,actor:a,issuedAt:Fu(t.issuedAt,"Native verification receipt issue time"),evidence:jA(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==mr||s.actor!==`native-runtime:${mr}`))throw new Error("Native required check policy identity is invalid");return s}function bg(e){let t=vr(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Mu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=$A(r),a=Ct(t.receiptHash,"Native verification receipt hash");if(j(bA,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function qu(e){return j(kA,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Pg=/^[a-f0-9]{64}$/u,gr=ki,UL=3*gr;function Vu(e,t){let i=pt.relative(e,t);return i===""||!pt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${pt.sep}`)}function HA(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Uo(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Te(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kg(e){let t=await et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await et.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function DA(e,t){let i=pt.resolve(e),r=pt.resolve(t);if(!Vu(i,r))throw new Error("Native evidence path is outside its change");let n=[await kg(i)],a=i;for(let o of pt.relative(i,r).split(pt.sep).filter(Boolean)){a=pt.join(a,o);let s=await kg(a);if(!Vu(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Sg(e){for(let t of e){let i=await et.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!HA(t,i)||await et.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function BA(e,t,i={}){let r=await DA(t,pt.dirname(e));await i.afterParentChainCaptured?.();let n=await et.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await et.realpath(e);if(!Vu(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await et.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),et.lstat(e),et.realpath(e)]);if(await Sg(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Uo(s,n)||!Uo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>gr)throw new Error(`Native evidence document exceeds ${gr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=gr+1-d,b=await o.read(f,0,Math.min(f.length,m),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>gr)throw new Error(`Native evidence document exceeds ${gr} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,p]=await Promise.all([o.stat(),et.lstat(e),et.realpath(e)]);if(await Sg(r),!v.isFile()||v.isSymbolicLink()||p!==a||!Uo(s,h)||!Uo(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 xg(e,t){if(!Pg.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function LA(e,t,i,r,n){if(!Pg.test(i))throw new Error("Native report evidence hash is invalid");let a=await Si({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"||OA("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 wr(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 FA(e,t,i,r,n){let a=xg(i,r);return n?pt.join(n,...a.split("/")):Wt(G(e,t),a)}async function Si(e){let t=FA(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??se(e.paths,t);return await z(i,t),BA(t,i,e.hooks)}function Eg(e,t){return Ho(e,t)}function MA(e,t){let i=Do(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function qA(e,t,i){let r=Cv(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function VA(e,t,i){let r=mu(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function WA(e,t,i,r=!1,n){let a=await Ko(e,t,i.implementationScopeRef,void 0,n);if(r&&await LA(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 Cg(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 Dn(e,t,i,r,n){let a=wr(i,"scopes"),o=MA(await Si({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=wr(o.baselineProjectionRef,"snapshots"),c=wr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Si({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Eg(d,s)),Si({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Eg(d,c))]);return Nv({baseline:l,current:u,scope:o})}async function Ko(e,t,i,r,n){return(await Dn(e,t,i,r,n)).scope}async function Cg(e,t,i,r,n){let a=wr(i,"allowances");return qA(await Si({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Bn(e,t,i,r,n){let a=wr(i,"receipts"),o=bg(await Si({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 yr(e,t,i,r,n){let a=wr(i,"verifications"),o=VA(await Si({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await WA(e,t,o,!1,n),o}var zA=4096;async function JA(e,t=be.maxChanges){try{let i=await fn({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 Rg(e,t){let i=await kt(e,t),[r,n]=await Promise.all([i.implementation_scope?Ko(e,t,i.implementation_scope):null,Nt(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 Yo(e,t,i={}){let n=(await JA(e,zA)).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 Rg(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await Rg(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=fg([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{execFile as r_}from"node:child_process";import{promisify as n_}from"node:util";import{constants as Wu,promises as Le}from"node:fs";import Nr from"node:path";var UA=/^[a-f0-9]{64}$/u,KA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ln=512*1024;function YA(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xo(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Te(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function XA(e,t){let i=Nr.resolve(e),r=Nr.resolve(t);if(!L(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Nr.relative(i,r).split(Nr.sep).filter(Boolean)]){o&&(a=Nr.join(a,o));let s=await Le.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Le.realpath(a);if(n.length>0&&!L(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 _g(e){for(let t of e){let i=await Le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!YA(t,i)||await Le.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function QA(e){if(!UA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function ZA(e){let t=KA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function e_(e,t,i){return Wt(G(e,t),QA(i))}async function t_(e,t,i){let r=await XA(i,Nr.dirname(e)),n=await Le.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Ln)throw new Error(`Native check receipt exceeds ${Ln} bytes`);let[a,o]=await Promise.all([Le.realpath(t),Le.realpath(e)]);if(!L(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Wu.O_RDONLY|Wu.O_NOFOLLOW|Wu.O_NONBLOCK,c=await Le.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(),Le.lstat(e),Le.realpath(e)]);if(await _g(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Xo(n,l)||!Xo(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Ln+1-h,E=await c.read(v,0,Math.min(v.length,y),null);if(E.bytesRead===0)break;if(h+=E.bytesRead,h>Ln)throw new Error(`Native check receipt exceeds ${Ln} bytes`);f.push(Buffer.from(v.subarray(0,E.bytesRead)))}let[p,m,b]=await Promise.all([c.stat(),Le.lstat(e),Le.realpath(e)]);if(await _g(r),!m.isFile()||m.isSymbolicLink()||b!==o||!L(a,b)||!Xo(l,p)||!Xo(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Tg(e,t,i){let r=ZA(i),n=G(e,t),a=e_(e,t,r),o=se(e,a);await z(o,a);let s=Ng(await t_(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Fn=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var MF=64*1024;var qF=3600*1e3;var VF=n_(r_);var a_=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Ig(e,t){let i=[];for(let r of a_){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 jg(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Tg(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 si=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 o_(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 s_(e){let t=o_(e.bundle.baseline),i=await _l(e.paths,t,{origin:"explicit",now:e.now});return du({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 Og(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Dn(e.paths,e.state.name,e.state.implementation_scope),i=await sr({changeDir:de(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await s_({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 Hg(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Og(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 c_(e){let t=await oe({root:de(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:wh(t.text)}}function l_(e){let{receipt:t,implementationScope:i}=e,r=[],n=uu({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 u_(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:qu(e.implementationScope.scope.declaredArtifacts)}}async function $g(e){let t=await Bn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Ig(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 si([{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 jg({paths:e.paths,state:e.state,receipt:t});if(n){let a=l_({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 d_(e){let t=u_({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await $g({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof si)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 $g({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof si)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 si(i)}function zu(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ju(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:zu(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Og(e),yr(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:zu(e.state.verification_result,"stale"),envelope:null};let r=await c_({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 d_({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:zu(e.state.verification_result,"invalid"),envelope:null}}}function p_(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Bg(e){try{return await f_.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function h_(e,t){try{return(await oe({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function m_(e,t,i){let r=Ro(e,i.capability);if(!L(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Dg.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await h_(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await oe({root:de(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 v_(e,t){return Bg(Pu(e,t))}async function Gu(e){let t=e.now??new Date,i=await kt(e.paths,e.name),r=await Nt(e.paths,e.name),n=await Pe(e.paths.projectRoot),a=p_(i.name,t),o=Dg.resolve(e.paths.nativeRoot,...a.split("/"));if(!L(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(v=>m_(e.paths,i.name,v))),Ju({paths:e.paths,state:i,now:t}),Yo(e.paths,i.name),Co(e.paths,i.name),bm(e.paths,i.name),v_(e.paths,i.name),Bg(o)]);return og({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]})}async function g_(e,t){let i=G(e,t.name),r=await ar(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 wo(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 yi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function w_(e,t){let i=await g_(e,t);return{committed:i,latest:Ov(i),history:$v(i)}}async function Lg(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await w_(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 Rt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function N_(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function b_(e){return(await Zm(e))?.change??null}function k_(e,t,i=!1,r){return Vo({state:e,archiveReady:t,evidenceRetreat:i}).command}async function S_(e,t){let i=de(e,t.name),r=[...(await Vl(i,t.brief)).findings,...(await Rm(e,t)).findings,...await ev(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await fo(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 Kh(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 sr({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 zv(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 Wl(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 Uu(e,t,i){let r=await b_(e)===t,n=await al(e,t),a=await bo(e,t),o;try{let g=await Ml(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},S=_u({paths:e,state:o,findings:[g]}),$=Vo({state:o,findings:S});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:$.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Tu(S),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:$,workspace:a,runtime:n,...i?.details?{findings:S}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await rg({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Lg(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 sr({changeDir:de(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),S=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let fe=await yr(e,o.name,o.verification_evidence);for(let X of fe.acceptanceTrace.entries)S.set(X.acceptanceId,X.status==="failed"?"failed":X.status==="missing"?"missing":"satisfied")}let $=vh({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:S,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),I=$.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",$.nextCursor,"--project-root",e.projectRoot]:null;u={...$,...I?{nextPageCommand:N_(I),nextPageArgs:I}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Yo(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(S=>({code:S,message:`Native change overlap is visible in the current root: ${S}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await Nt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let S=await yn({paths:e,identity:g});S.state==="drifted"&&S.code&&f.push({code:S.code,message:S.message??"Native workspace binding is no longer valid"})}else{let S=await ko({paths:e,identity:g});f.push(...S.findingCodes.map($=>({code:$,message:`Native workspace advisory changed: ${$} (${S.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let g=await Hg({paths:e,state:o});v=g.freshness!=="fresh",h.push(...g.findingCodes.map(S=>({code:S,message:`Native Verify implementation scope is not current: ${S}`})))}let p=null,m=[];if(o.phase==="archive")try{p=await Gu({paths:e,name:o.name}),m.push(...p.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 b=[...await S_(e,o),...s.findings,...d,...f,...h,...l,...m].filter((g,S,$)=>$.findIndex(I=>I.code===g.code&&I.path===g.path)===S),y=_u({paths:e,state:o,findings:b}),E=y.filter(g=>!or(g.code)),k=o.phase==="archive"&&p?.ready===!0&&E.length===0,P=v||o.phase==="archive"&&(p?.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)),N=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),x=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:N||x?null:k_(o,k,P,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:Tu(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Vo({state:o,findings:y,archiveReady:k,evidenceRetreat:P,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:Jo,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 Fg(e){let t;try{t=await yl({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await y_.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Rt.maxChanges))throw new Error(`Native status exceeds ${Rt.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Qo(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Zo(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function E_(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function es(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Qo({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Zo("summary","--summary"),E_(e.name,e.flag)]}}function Ku(e){return[es({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),es({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Mg(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Zo("summary","--summary")],commandAlternatives:[es({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Ku({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Qo({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Zo("summary","--summary")],commandAlternatives:[es({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ku({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Zo("summary","--summary")],commandAlternatives:Ku({change:e.name,stateVersion:e.state_version}),runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?Qo({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:Qo({change:e.name,stateVersion:e.state_version,action:"confirm-shape",flag:"--confirmed"}),requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}function P_(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 x_(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 Yu(e){let t=await Qm(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=x_(e.paths,t.state),n=await Xl({paths:e.paths,state:t.state}),a=Mg(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:P_(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}}:{}}}var R_=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function ts(e,t){let i=ci.normalize(Xu(e)),r=ci.normalize(Xu(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Xu(e){let t=ci.resolve(e);try{return C_.native(t)}catch{return t}}function A_(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function qg(e){let t=[];for(let i of await Fg(e))t.push({name:i,kind:await tu(e,i)?"portable":"legacy"});return t}async function Jg(e){let t=ci.resolve(e),i=xi(e),r=i.length>0?i:[t];r.some(o=>ts(o,t))||r.push(t);let n=[],a=new Set;for(let o of r.map(s=>ci.resolve(s)).sort()){let s=ts(o,t)?t:o,c=Xu(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Pe(s);if(!u)continue;let d=await vt(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await qg(d)})}if(n.length===0){let o=await Pe(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await vt(e,o.native.artifact_root);n.push({projectRoot:ci.resolve(e),config:o,paths:s,changes:await qg(s)})}return n}function Vg(e,t){return e.workspace.bindingState==="aligned"?0:ts(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Gg(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 Yu({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 bo(c.paths,n),portableStatus:null}}));o.sort((c,l)=>Vg(c,e)-Vg(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>Rt.maxChanges)throw new Error(`Native status discovery exceeds ${Rt.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function Wg(e,t){let i=t.toString(36),r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function __(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=R_.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=j("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 zg(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?A_(i):null,nextPageArgs:i}}async function T_(e,t,i){let r=null;try{r=await Sm(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}}}:Uu(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 Ug(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:Yu({paths:e.source.paths,name:e.name,details:t})}return T_(e,t,i)}async function Kg(e){let t=await Jg(e.projectRoot),i=(await Gg(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>ts(n.projectRoot,e.projectRoot))??t[0];return Uu(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 Ug(i[0],e.details??!1,e.acceptanceCursor)}async function Yg(e){let t=await Jg(e.projectRoot),i=await Gg(e.projectRoot,t),r=j("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=__({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Rt.maxItems).map(u=>Ug(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=f<i.length?Wg(r,f):null,v={schema:s,total:i.length,offset:n,items:d,nextCursor:h,...zg(ci.resolve(e.projectRoot),h),limits:{...Rt}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Rt.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<i.length?Wg(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...zg(ci.resolve(e.projectRoot),l),limits:{...Rt}}}import Mn from"path";import{realpathSync as B_}from"fs";var AM={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var FM=16*1024*1024,MM=256*1024,qM=16*1024;var GM=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var jq=16*1024*1024,is=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"},rs=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 ns=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Xg=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Zu=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Xg,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker]
|
|
171
|
-
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
167
|
+
${Sr(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function gC(e){if(Rn(e)<=ki)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=lv("sha256");a.update(`${lC}
|
|
168
|
+
`),e.omissionOverflow&&ei(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,ei(a,"omission",f)},s=f=>{r+=1,n+=1,ei(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(;Rn(u)>ki;){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 v=0;v<h;v+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))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 ou(e){let t=wi(e),i=t.entries.map((n,a)=>pC(n,`Snapshot entry ${a}`));if(i.sort(mC),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)=>hC(n,`Snapshot omission ${a}`));return r.sort(vC),gC({schema:uv,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 An(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:ti(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)=>he(i.path,r.path)||he(i.kind,r.kind))}function _n(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function rv(e){return e?{hash:e.hash,size:e.size}:null}function lu(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:he(a.path,o.path),c=s<=0?a:void 0,l=s>=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:rv(c),after:rv(l)})}}function pv(e,t){return{...e,attributedTo:t.filter(i=>_n(i,e.path))}}function uu(e){let t=An(e.declaredArtifacts),i=[];return lu(e.baseline,e.current,r=>{i.push(pv(r,t))}),i}function St(e,t){return{id:`scope:${j(sC,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function wC(e,t){let i=t.omitted.map(r=>St({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(St({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(St({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 nv(e,t){return wC(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function su(e,t){return he(e.kind,t.kind)||he(e.source,t.source)||fC(e.path,t.path)||he(e.id,t.id)}function yC(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(su)}function hv(e){return[...new Set(e.map((t,i)=>ti(t,`Git path ${i}`)))].sort(he)}function av(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 NC(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 mv(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=hv(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:av(e.baseCommit,"Native external drift base commit"),targetBranch:NC(e.targetBranch,"Native external drift target branch"),targetCommit:av(e.targetCommit,"Native external drift target commit"),paths:t}}function vv(e){if(typeof e.contractHash!="string"||!cu.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:An(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:hv(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:mv(e.externalDrift)}}}function bC(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 lu(e,t,h=>{let v=i.some(p=>_n(p,h.path));if(d+=1,c.push(h.path),!v&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<uC){let p=pv(h,i),m=Rn(p);l+m<=ki?(a.push(p),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function gv(e,t){return St({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function kC(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:lr(Number(t[1]),"Scope overflow change count"),unresolved:lr(Number(t[2]),"Scope overflow unresolved count"),unattributed:lr(Number(t[3]),"Scope overflow unattributed count")},r=bi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(gv(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function SC(e){let t=lv("sha256");t.update(`${cC}
|
|
169
|
+
`);let i=0;lu(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ei(t,"change",n);let a=0;for(let o of e.declaredArtifacts)_n(o,n.path)&&(a+=1,ei(t,"change-attribution",o));ei(t,"change-end",{attributionCount:a}),a===0&&ei(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&&ei(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function wv(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=bC(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(S=>!w.has(S)||n.some($=>_n($,S)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(xn,e),c=j(xn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=dC)break;l.push(St({kind:"snapshot-omission",source:x,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${x} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...nv("baseline",e),...nv("current",t),...o.totalChanges===0&&a===null?[St({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 x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>x.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!x.has(w))}},v=x=>{let w=o.candidates.slice(0,x.detailedChangeCount),g=w.filter(Fe=>Fe.attributedTo.length===0&&!u.has(Fe.path)),S=o.totalChanges-w.length,$=o.totalUnattributed-g.length,T=d-x.detailedOmissionCount,fe=$+T,X=[...g.map(Fe=>St({kind:"unattributed-change",source:"implementation-scope",path:Fe.path,evidence:{after:Fe.after,before:Fe.before,changeKind:Fe.kind}},`Changed path is not covered by a declared artifact: ${Fe.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...fe>0?[gv(x.overflowHash,{changes:S,unattributed:$,unresolved:fe})]:[]],J=yC(X),it=x.includeGitAdvisory?h():void 0;return{schema:nu,contractHash:r,baselineProjectionRef:au(s),baselineProjectionHash:s,currentProjectionRef:au(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:J,noCodeReason:a,...it?{gitAdvisory:it}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,m=l.length,b=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:y});if(Rn({...x,scopeHash:y})<=ki)break;if(b){b=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/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 k=o.totalChanges>p||d>m?SC({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:m}):y,P=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:k}),N={...P,scopeHash:j(dv,P)};if(Rn(N)>ki)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return N}function du(e){let t=ou(e.baseline),i=ou(e.current),r=vv(e);return{authority:r,baseline:t,current:i,scope:wv(t,i,r)}}var EC=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ft(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 bi(e,t){if(typeof e!="string"||!cu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ov(e,t,i){let r=au(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Do(e,t){let i=dt(e,"Native snapshot projection");if(ft(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==uv)throw new Error("Native snapshot projection schema is invalid");let r=wi({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=ou(r);if(j(xn,i)!==j(xn,n))throw new Error("Native snapshot projection is not canonical");let a=j(xn,n);if(t!==void 0&&bi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function fu(e,t){let i=dt(e,`Declared artifact ${t}`);if(ft(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ti(i.path,`Declared artifact ${t} path`),kind:i.kind}}function sv(e,t){if(e===null)return null;let i=dt(e,t);return ft(i,["hash","size"],[],t),{hash:bi(i.hash,`${t} hash`),size:lr(i.size,`${t} size`)}}function cv(e,t){let i=dt(e,`Implementation change ${t}`);if(ft(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(fu),n=An(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=sv(i.before,`Implementation change ${t} before`),o=sv(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:ti(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function PC(e,t){let i=dt(e,`Unresolved scope ${t}`);ft(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"?fv(i.path,`Unresolved scope ${t} path`):ti(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Cn(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)=>ti(n,`${t} ${a}`)),r=[...new Set(i)].sort(he);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function yv(e){let t=dt(e,"Native implementation external drift");if(ft(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=Cn(t.paths,"Native external drift paths");return mv({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Bo(e){let t=dt(e,"Native implementation scope"),i=[...EC].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(ft(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==nu)throw new Error("Native implementation scope schema is invalid");let r=bi(t.contractHash,"Implementation scope contractHash"),n=bi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=ov(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=bi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=ov(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(fu);if(JSON.stringify(c)!==JSON.stringify(An(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(cv),u=[...l].sort((g,S)=>he(g.path,S.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(S=>!d.has(`${S.kind}:${S.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(S=>_n(S,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(cv),h=t.externalDrift===void 0?void 0:yv(t.externalDrift),v=new Set(h?.paths??[]),p=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(PC),b=m.filter(g=>g.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=b[0]===void 0?null:kC(b[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,k=[...p.map(g=>St({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?[St({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")]:[]],P=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(su))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(P)!==JSON.stringify(k.sort(su))||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 N;if(t.gitAdvisory!==void 0){let g=dt(t.gitAdvisory,"Implementation scope Git advisory");if(ft(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let S=Cn(g.changedPaths,"Git changed paths"),$=Cn(g.pathsPresentInSnapshotChanges,"Git present paths"),T=Cn(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),fe=[...$,...T].sort(he);if(JSON.stringify(fe)!==JSON.stringify(S)||T.some(X=>l.some(J=>J.path===X)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:S,pathsPresentInSnapshotChanges:$,pathsAbsentFromSnapshotChanges:T}}let x={schema:nu,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:E,...N?{gitAdvisory:N}:{},...h?{externalDrift:h}:{}},w=bi(t.scopeHash,"Implementation scope scopeHash");if(j(dv,x)!==w)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:w}}function xC(e){let t=dt(e,"Native implementation scope authority");if(ft(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(fu);if(JSON.stringify(i)!==JSON.stringify(An(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=Cn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:yv(t.externalDrift),a=vv({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 In(e){let t=dt(e,"Native implementation scope bundle");ft(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=xC(t.authority),r=Do(t.baseline),n=Do(t.current),a=Bo(t.scope),o=wv(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 Nv(e){let t=Bo(e.scope);return In({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})}var Sv=/^[a-f0-9]{64}$/u;var CC="comet.native.acceptance-trace.v2",RC="comet.native.partial-allowance.v1",AC="comet.native.verification-evidence.v2";function Et(e,t){if(!Sv.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ev(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Pv(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 pu(e,t,i=2e3){let r=De(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Tn(e,t){let i=bv.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})||bv.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 _C(e,t,i){let r=Tn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=at(r),a=r.toLowerCase(),o=i?Tn(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 hu(e){let t=Tn(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 ur(e,t){return e<t?-1:e>t?1:0}function Lo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fo(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 xv(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 kv(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 IC(e){let t=Lo(e,"Native acceptance trace");if(Fo(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"||!Sv.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=Tn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Lo(o,`Native acceptance trace entry ${s}`);if(Fo(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=>hu(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ur))||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:Tn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:pu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>ur(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=Et(t.traceHash,"Native acceptance trace hash");if(j(CC,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Cv(e){let t=Lo(e,"Native partial allowance");if(Fo(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(ur))||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:Pv(t.change),scopeHash:Et(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:pu(t.reason,"Partial allowance reason"),confirmedSummary:pu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ev(t.sourceRevision),confirmedAt:xv(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=Et(t.allowanceHash,"Native partial allowance hash");if(j(RC,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function mu(e){let t=Lo(e,"Native verification evidence");if(Fo(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=Et(t.implementationScopeHash,"Native verification implementation scope hash"),r=IC(t.acceptanceTrace),n=Et(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:Et(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>hu(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ur)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(ur);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=>hu(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ur)))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:Pv(t.change),sourceRevision:Ev(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Et(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:kv(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:_C(t.reportRef,"Native verification report ref"),reportHash:Et(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:kv(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:xv(t.createdAt,"Native verification timestamp")},d=Et(t.envelopeHash,"Native verification envelope hash");if(j(AC,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function vu(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 Rv="repairStagnation",Re={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},jC=/^[a-f0-9]{64}$/u;var $C=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),OC=["data","runId","sequence","timestamp","type"],Av=["disposition","overrideSummaryHash","signatureHash"],HC=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],_v=12;function wu(e,t){return e<t?-1:e>t?1:0}function Iv(e,t,i){let r=Object.keys(e).sort(wu);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Mo(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 jn(e,t){if(typeof e!="string"||!jC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function DC(e){if(!Array.isArray(e)||e.length>cr.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(wu)}function Tv(e){if(typeof e!="string"||e.length===0||e.length>Re.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 gu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Re.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Re.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>Re.maxTextCharacters&&(!n||e.length>Re.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Re.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>Re.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>gu(s,t+1,i,`${r}[${c}]`));return}let a=Mo(e,r),o=Object.keys(a);if(o.length>Re.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Re.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Re.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");gu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function BC(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 LC(e,t,i){let r=Mo(e,`Native repair trajectory event ${t+1}`);if(Iv(r,OC,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(BC(r.timestamp),typeof r.type!="string"||!$C.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Tv(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 gu(r.data,0,n,"Native trajectory event data"),Mo(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function yu(e){let t=Mo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(wu),r=i.length===Av.length&&i.every((l,u)=>l===Av[u]);r||Iv(t,HC,"Native repair trajectory projection");let n=jn(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:jn(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=jn(t.contractHash,"Native repair trajectory contract hash"),s=DC(t.failedAcceptanceIds),c=iu(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 FC(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 MC(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??_v;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=ru({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<cr.warningAtConsecutiveFailures?"continue":a<cr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function qC(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??_v;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 jv(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Re.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Tv(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;l<e.committedTrajectoryOffset;l+=1){let u=LC(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Re.maxTotalDataNodes||c>Re.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?jn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?jn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Rv)){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 v=yu(f[Rv]);if(FC(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&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),MC(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&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");qC(v,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:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>cr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function $v(e){return jv(e).history}function Ov(e){let t=jv(e).latestProjection;return t?{...t}:null}var dr={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:[]},Nu=U("comet-native-runtime:v3:scope-reopen"),VC=[{skillVersion:"3",skillHash:U("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:U("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:U("comet-native-runtime:v1")}];function Hv(e){return e.skillVersion===dr.definition.metadata.version&&e.skillHash===Nu||VC.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Dv(e){return U(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 qv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],KC=new Set(qv),Vv=new Set([...qv,"minimum_runtime_version","revision"]),YC=new Set([...Vv,"operation"]),XC=512*1024,ku=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),QC=new Set([...ku,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Su=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 Pu(e,t){return UC.join(G(e,t),"transition.json")}function Vo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function xu(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 qo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Eu(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=>!QC.has(u)),a=[...ku].find(u=>!Object.hasOwn(i,u)),o=ku.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(vu(i.summary,"Native transition journal event summary"),De(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&&(vu(i.noCodeReason,"Native transition journal event no-code reason"),De(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")?yu(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 ZC(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 Eu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Eu(e,t)}function Cu(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?ZC(e.eventData,e.evidenceHash):Eu(e.eventData,e.evidenceHash),n=Tl(e.nextRun),a=e.previousRun===null?null:Tl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Bv(e,t,i=!1){if(e.skill!==dr.definition.metadata.name||(i?!Hv(e):e.skillVersion!==dr.definition.metadata.version||e.skillHash!==Nu)||e.orchestration!==dr.definition.orchestration.mode||e.pendingRef!==Oe.pendingRef||e.trajectoryRef!==Oe.trajectoryRef||e.contextRef!==Oe.contextRef||e.artifactsRef!==Oe.artifactsRef||e.checkpointRef!==Oe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Lv(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 Fv(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 Ru(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Bv(o,"next Run",r||a!==null),Fv(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(Bv(a,"previous Run",!0),Fv(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(!bu(Lv(a),Lv(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function eR(e,t,i){return U(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Wv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Mv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Au(e,t,i,r,n=!1){let a=i.eventData,o=Mv(e),s=Mv(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&&bu(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&&bu(e.spec_changes,t.spec_changes),l=Dv({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=eR(e.name,a.summary,t.spec_changes),l=U(`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 tR(e,t){let i=Vo(e);if(xu(i,YC),i.schema!==Ki)throw new Error(`Expected Native transition schema ${Ki}`);let r=qo(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 ${Ki} minimum_runtime_version must be ${3}`);let n=qo(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=Cu(i,t),o=Ut(i.previousState),s=Ut(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Au(o,s,a,i.operation),Ru(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:Ki,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 iR(e,t){let i=Vo(e);if(xu(i,KC),i.schema!==dn)throw new Error(`Expected Native transition schema ${dn}`);let r=Cu(i,t,!0),n=Xi(i.previousState),a=Xi(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Au(n,a,r,Wv(n,a,r.eventData),!0),Ru(n,a,r,!0),{schema:dn,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 rR(e,t){let i=Vo(e);if(xu(i,Vv),i.schema!==Yi)throw new Error(`Expected Native transition schema ${Yi}`);if(qo(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Yi} minimum_runtime_version must be 2`);let n=qo(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Cu(i,t,!0),o=Qi(i.previousState),s=Qi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Au(o,s,a,Wv(o,s,a.eventData),!0),Ru(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Yi,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 nR(e,t){let i=Vo(e);if(i.schema===Ki)return{status:"current",journal:tR(i,t)};if(i.schema===dn)return{status:"migration-required",journal:iR(i,t)};if(i.schema===Yi)return{status:"migration-required",journal:rR(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function aR(e,t){let i=Pu(e,t),r=se(e,i);await z(r,i);try{let n=await wt({root:r,file:i,maxBytes:XC,label:`Native transition journal ${t}`});return nR(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function zv(e,t){let i=await aR(e,t);if(!i)return null;if(i.status==="migration-required")throw new Su(t);return i.journal}var oR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function sR(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function cR(e){return e?e.map(sR).join(" "):null}function lR(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 Be(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 uR(e){return e.map(t=>Be(t,[],null))}function dR(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Be("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Be("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Be("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Be("artifact-or-no-code-reason",["--no-code-reason"],"<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(Be("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Be("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Be("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function me(e,t){let i=t.commandArgs===void 0?lR(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?cR(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??uR(t.requiredInputs??[])}}function Wo(e){let i=(e.findings??[]).filter(d=>!or(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||oR.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 me(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return me(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Be("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return me(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return me(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return me(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Be("summary",["--summary"],"<summary>")]});if(n)return me(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Be("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return me(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?me(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?me(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):me(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"),me(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Be("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):me(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return me(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=dR(e.state);return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import $n from"path";var Jv=8,fR={"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 pR(e){let t=fR[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"}:or(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 hR(e,t,i){if(!i.path)return null;let r;if($n.isAbsolute(i.path)?r=$n.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=$n.resolve(de(e,t.name),...i.path.split(/[\\/]/u)):r=$n.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!L(e.projectRoot,r))return null;let n=$n.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function mR(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<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 _u(e){return e.findings.map(t=>{let i=pR(t.code);return{code:t.code,message:t.message,severity:i.severity,path:hR(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:mR(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 Iu(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,Jv),truncated:t.length>Jv}}import fr from"path";var ri={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},pr=/^[a-f0-9]{64}$/u;function zo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jo(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 ii(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 Gv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Tu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function vR(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||fr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=fr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Uv(e,t){return fr.join(G(e,t),"checkpoints","progress.json")}function On(e,t){return fr.join(G(e,t),"checkpoint-journal.json")}function Kv(e,t,i){if(!pr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return fr.join(G(e,t),"checkpoints","manifests",`${i}.json`)}function gR(e){if(!pr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function ju(e,t,i){let r=await wt({root:e,file:t,maxBytes:ri.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function wR(e,t){let i=zo(e,`checkpoint manifest artifact ${t}`);Jo(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=vR(ii(i.path,`checkpoint artifact ${t} path`,4096)),n=at(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!pr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Tu(i.size,`checkpoint artifact ${t} size`)}}function $u(e,t){let i=zo(e,"Native checkpoint manifest");if(Jo(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>ri.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(wR),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=Tu(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>ri.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 Yv(e){return U(JSON.stringify($u(e,e.change)))}function Xv(e,t){let i=zo(e,"Native progress checkpoint");if(Jo(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=Gv(i.previousRevision,"Native checkpoint previousRevision"),a=Gv(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ii(i.manifestHash,"Native checkpoint manifestHash",64);if(!pr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=gR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ii(i.inputHash,"Native checkpoint inputHash",64);if(!pr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ii(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Tu(i.artifactCount,"Native checkpoint artifactCount");if(u>ri.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ii(i.summary,"Native checkpoint summary"),f=ii(i.nextAction,"Native checkpoint nextAction");if(De(d)!==d||De(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ii(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 yR(e,t){let i=zo(e,"Native checkpoint journal");if(Jo(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=Ut(i.previousState),n=Ut(i.nextState),a=Xv(i.checkpoint,t),o=$u(i.manifest,t),s=ii(i.inputHash,"Native checkpoint journal inputHash",64),c=U(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!pr.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!==Yv(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 NR(e,t,i){let r=fr.resolve(e.projectRoot,...t.split("/"));if(!L(e.projectRoot,r)||L(e.nativeRoot,r)||L(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=zc(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await wt({root:e.projectRoot,file:r,maxBytes:ri.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 bR(e,t){let i=Uv(e,t),r=se(e,i);await z(r,i);try{return Xv(await ju(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function kR(e,t,i){let r=Kv(e,t,i),n=se(e,r);await z(n,r);let a=await ju(n,r,"Native checkpoint manifest"),o=$u(a,t);if(Qv(e,o),Yv(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Ou(e,t){let i=On(e,t),r=se(e,i);await z(r,i);try{let n=yR(await ju(r,i,"Native checkpoint journal"),t);return Qv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Qv(e,t){for(let i of t.artifacts){let r=zc(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Zv(e){let t;try{t=await bR(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:Uv(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 kR(e.paths,e.name,t.manifestHash);let a=U(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 NR(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}}var eg=240,tg=8,Go=50;function ig(e){let t=Array.from(e);return t.length<=eg?e:`${t.slice(0,eg-1).join("")}…`}function SR(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function ER(e){let t=[...new Set(e.map(SR))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,tg),reasonCount:e.length,codesTruncated:t.length>tg};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Go),reasonsTruncated:e.length>Go}}}async function rg(e){let t=null;try{let s=await Ou(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:On(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:On(e.paths,e.state.name)}}let i=await Zv({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=ER(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ri.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:ig(i.checkpoint.summary),nextAction:ig(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:ri.maxArtifacts}}import{promises as d_}from"node:fs";import Dg from"node:path";import ng from"node:path";var PR="comet.native.archive-preflight.v1",xR="comet.native.archive-preflight.v1",CR="comet.native.archive-operation.v1",RR=/^[a-f0-9]{64}$/u,ag=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Uo(e,t){return e<t?-1:e>t?1:0}function _R(e,t){if(typeof e!="string"||!RR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pt(e,t){return e===null?null:_R(e,t)}function IR(e,t){let i=ng.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||ng.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 TR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function jR(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 $R(e,t){if(!ag.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=Pt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Pt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Pt(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 OR(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:Pt(e.contractHash,"Native archive contract hash"),acceptanceHash:Pt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Pt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Pt(e.reportHash,"Native archive report hash"),envelopeHash:Pt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Pt(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 HR(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!AR.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(Uo);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function DR(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(Uo)}function og(e){if(!ag.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($R).sort((l,u)=>Uo(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:j(CR,l)})),r=OR(e.evidence),n=jR(e.workspace),a=[...new Set([...HR(e.findingCodes??[]),...DR({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(Uo),o=TR(e.revision),s=IR(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:PR,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:j(xR,c)}}import{createHash as BR}from"node:crypto";import sg from"node:path";var LR="comet.native.conflict-radar.v1",be=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}),FR="comet.native.conflict-radar.v1",MR="comet.native.conflict-radar-signals.v1",qR=/^[a-f0-9]{64}$/u,ug=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VR=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),WR=new Set(["capability","operation","baseHash"]),zR=new Set(["path","kind"]);function hr(e,t){return e<t?-1:e>t?1:0}function Hu(e){return Buffer.byteLength(e,"utf8")}function Du(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 Bu(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(Hu(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function JR(e,t){let i=Bu(e,t,be.maxArtifactPathBytes),r=sg.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)||sg.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 dg(e,t){if(typeof e!="string"||!qR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function GR(e,t){let i=Du(e,WR,t),r=Bu(i.capability,`${t} capability`,be.maxCapabilityBytes);if(!ug.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:dg(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 UR(e,t){let i=Du(e,zR,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:JR(i.path,`${t} path`),kind:i.kind}}function KR(e,t){let i=Du(e,VR,`Conflict radar change ${t}`),r=Bu(i.name,`Conflict radar change ${t} name`,be.maxNameBytes);if(!ug.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>be.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>be.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>GR(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>hr(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)=>UR(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>hr(c.path,l.path)||hr(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:dg(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function YR(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>be.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(KR).sort((n,a)=>hr(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)>be.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>be.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function XR(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 QR(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 ZR(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function eA(e,t){let i=[],r=BR("sha256").update(`${MR}
|
|
170
|
+
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Sr(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<be.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(XR(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=QR(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:ZR(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function cg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function tA(e,t){return cg(e.classification)-cg(t.classification)||hr(e.left,t.left)||hr(e.right,t.right)}function lg(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:LR,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 fg(e){let t=YR(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(eA(t[s],t[c]));i.sort(tA);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(FR,{changes:t,relationships:r}),a=i.slice(0,be.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=lg(t,i,a,n);for(;a.length>0&&Hu(JSON.stringify(o))>be.maxSerializedBytes;)a=a.slice(0,-1),o=lg(t,i,a,n);if(Hu(JSON.stringify(o))>be.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as $A}from"node:crypto";import{promises as et}from"node:fs";import pt from"node:path";import pg from"node:path";var hg="comet.native.check-receipt.v1",iA="comet.native.check-receipt.v1",mr="scoped-text-safety",Lu=1,ke=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),rA=/^[a-f0-9]{64}$/u,nA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aA="comet.native.checker-policy.v1",oA="comet.native.check-input.v1",sA=2048,mg=j(aA,{policy:mr,version:Lu,limits:ke,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),cA=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),vg=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],wg=["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"],lA=new Set(wg);function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(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 xt(e,t){if(typeof e!="string"||!rA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ae(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function yg(e,t){let i=Ae(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function gg(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 uA(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>sA||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=pg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||pg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function dA(e){let t=ni(e,"Native check receipt checker");ai(t,["policy","version","hash","limits"],"Native check receipt checker");let i=ni(t.limits,"Native check receipt limits");if(ai(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==mr||t.version!==Lu||t.hash!==mg||i.maxFiles!==ke.maxFiles||i.maxFileBytes!==ke.maxFileBytes||i.maxTotalBytes!==ke.maxTotalBytes||i.maxIssues!==ke.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:mr,version:Lu,hash:mg,limits:{...ke}}}function fA(e){let t=ni(e,"Native check receipt contract");return ai(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:xt(t.expectedHash,"Native check expected contract hash"),beforeHash:xt(t.beforeHash,"Native check before contract hash"),afterHash:xt(t.afterHash,"Native check after contract hash")}}function pA(e){let t=ni(e,"Native check receipt implementation");return ai(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:xt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:xt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:xt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:xt(t.afterSnapshotHash,"Native check after snapshot hash")}}function hA(e,t){let i=ni(e,`Native check batch ${t}`);ai(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Ae(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ae(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ae(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ae(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ae(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ae(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>ke.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>ke.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function mA(e){let t=ni(e,"Native check receipt counts");ai(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Ae(t.filesSelected,"Native check filesSelected"),filesScanned:Ae(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ae(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ae(t.bytesScanned,"Native check bytesScanned"),issueCount:Ae(t.issueCount,"Native check issueCount"),recordedIssueCount:Ae(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(hA):(()=>{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>ke.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>ke.maxFiles||i.bytesScanned>ke.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function vA(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||vg.indexOf(e.kind)-vg.indexOf(t.kind)}function gA(e){if(!Array.isArray(e)||e.length>ke.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=ni(r,`Native check issue ${n}`);if(ai(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!cA.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:uA(a.path,`Native check issue ${n} path`),line:yg(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(vA);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function wA(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!lA.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=wg.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 yA(e){return j(oA,e)}function Ng(e){let t=ni(e,"Native check receipt");if(ai(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==hg)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!nA.test(t.change))throw new Error("Native check receipt change name is invalid");let i=yg(t.sourceRevision,"Native check source revision"),r=dA(t.checker),n=fA(t.contract),a=pA(t.implementation),o=yA({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(xt(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=gg(t.startedAt,"Native check receipt startedAt"),c=gg(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=mA(t.counts),u=gA(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=wA(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>ke.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>ke.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:hg,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=xt(t.receiptHash,"Native check receipt content hash");if(j(iA,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var Mu="comet.native.verification-receipt.v3",NA=Mu,bA="comet.native.declared-artifacts.v1",kA=/^[a-f0-9]{64}$/u,SA=/^acceptance-[a-f0-9]{64}$/u,EA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,xA=4096,CA=256,RA=1024;function vr(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 oi(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 Ct(e,t){if(typeof e!="string"||!kA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ze(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=De(e).trim();if(!i||i.length>xA||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Fu(e,t){let i=Ze(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 Hn(e,t,i=Ze,r=!1,n=CA){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 AA(e,t){if(typeof e!="string"||!SA.test(e))throw new Error(`${t} is invalid`);return e}function _A(e){let t=vr(e,"Native verification receipt bindings");if(oi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!EA.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:Ct(t.contractHash,"Native verification receipt contract hash"),scopeHash:Ct(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Ct(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Ct(t.artifactHash,"Native verification receipt artifact hash")}}function IA(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=PA.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function TA(e,t,i,r){let n=vr(t,`Native ${e} evidence`);if(e==="automated-check"){if(oi(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=Fu(n.startedAt,"Native automated-check start time"),o=Fu(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=vr(n.worktree,"Native automated-check worktree");if(oi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=vr(n.afterFence,"Native automated-check after fence");if(oi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ze(n.executable,"Native automated-check executable"),args:Hn(n.args,"Native automated-check arguments",Ze,!0),cwd:Ze(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ze(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Ct(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Ct(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Ct(n.outputHash,"Native automated-check output hash"),outputSummary:Ze(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){oi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=IA(n.checkReceiptRef);if(Ct(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Hn(n.subjects,"Native static inspection subjects",Ze,r==="required-check"),rule:Ze(n.rule,"Native static inspection rule"),resultSummary:Ze(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return oi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Hn(n.steps,"Native manual evidence steps"),observations:Hn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function jA(e){let t=vr(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=Ze(t.actor,"Native verification receipt actor"),o=Hn(t.acceptanceIds,"Native receipt acceptance IDs",AA,r==="required-check",RA).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Mu,kind:i,role:r,status:n,bindings:_A(t.bindings),acceptanceIds:o,actor:a,issuedAt:Fu(t.issuedAt,"Native verification receipt issue time"),evidence:TA(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==mr||s.actor!==`native-runtime:${mr}`))throw new Error("Native required check policy identity is invalid");return s}function bg(e){let t=vr(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Mu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=jA(r),a=Ct(t.receiptHash,"Native verification receipt hash");if(j(NA,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function qu(e){return j(bA,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Pg=/^[a-f0-9]{64}$/u,gr=ki,GL=3*gr;function Vu(e,t){let i=pt.relative(e,t);return i===""||!pt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${pt.sep}`)}function OA(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ko(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ie(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kg(e){let t=await et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await et.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function HA(e,t){let i=pt.resolve(e),r=pt.resolve(t);if(!Vu(i,r))throw new Error("Native evidence path is outside its change");let n=[await kg(i)],a=i;for(let o of pt.relative(i,r).split(pt.sep).filter(Boolean)){a=pt.join(a,o);let s=await kg(a);if(!Vu(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Sg(e){for(let t of e){let i=await et.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!OA(t,i)||await et.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function DA(e,t,i={}){let r=await HA(t,pt.dirname(e));await i.afterParentChainCaptured?.();let n=await et.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await et.realpath(e);if(!Vu(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await et.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),et.lstat(e),et.realpath(e)]);if(await Sg(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Ko(s,n)||!Ko(s,c))throw new Error("Native evidence document changed while opening");if(s.size>gr)throw new Error(`Native evidence document exceeds ${gr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=gr+1-d,b=await o.read(f,0,Math.min(f.length,m),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>gr)throw new Error(`Native evidence document exceeds ${gr} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,p]=await Promise.all([o.stat(),et.lstat(e),et.realpath(e)]);if(await Sg(r),!v.isFile()||v.isSymbolicLink()||p!==a||!Ko(s,h)||!Ko(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 xg(e,t){if(!Pg.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function BA(e,t,i,r,n){if(!Pg.test(i))throw new Error("Native report evidence hash is invalid");let a=await Si({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"||$A("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 wr(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 LA(e,t,i,r,n){let a=xg(i,r);return n?pt.join(n,...a.split("/")):Wt(G(e,t),a)}async function Si(e){let t=LA(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??se(e.paths,t);return await z(i,t),DA(t,i,e.hooks)}function Eg(e,t){return Do(e,t)}function FA(e,t){let i=Bo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function MA(e,t,i){let r=Cv(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function qA(e,t,i){let r=mu(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function VA(e,t,i,r=!1,n){let a=await Yo(e,t,i.implementationScopeRef,void 0,n);if(r&&await BA(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 Cg(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 Dn(e,t,i,r,n){let a=wr(i,"scopes"),o=FA(await Si({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=wr(o.baselineProjectionRef,"snapshots"),c=wr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Si({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Eg(d,s)),Si({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Eg(d,c))]);return Nv({baseline:l,current:u,scope:o})}async function Yo(e,t,i,r,n){return(await Dn(e,t,i,r,n)).scope}async function Cg(e,t,i,r,n){let a=wr(i,"allowances");return MA(await Si({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Bn(e,t,i,r,n){let a=wr(i,"receipts"),o=bg(await Si({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 yr(e,t,i,r,n){let a=wr(i,"verifications"),o=qA(await Si({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await VA(e,t,o,!1,n),o}var WA=4096;async function zA(e,t=be.maxChanges){try{let i=await fn({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 Rg(e,t){let i=await kt(e,t),[r,n]=await Promise.all([i.implementation_scope?Yo(e,t,i.implementation_scope):null,Nt(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 Xo(e,t,i={}){let n=(await zA(e,WA)).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 Rg(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await Rg(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=fg([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{execFile as i_}from"node:child_process";import{promisify as r_}from"node:util";import{constants as Wu,promises as Le}from"node:fs";import Nr from"node:path";var GA=/^[a-f0-9]{64}$/u,UA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ln=512*1024;function KA(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Qo(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ie(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function YA(e,t){let i=Nr.resolve(e),r=Nr.resolve(t);if(!L(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Nr.relative(i,r).split(Nr.sep).filter(Boolean)]){o&&(a=Nr.join(a,o));let s=await Le.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Le.realpath(a);if(n.length>0&&!L(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 _g(e){for(let t of e){let i=await Le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!KA(t,i)||await Le.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function XA(e){if(!GA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function QA(e){let t=UA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function ZA(e,t,i){return Wt(G(e,t),XA(i))}async function e_(e,t,i){let r=await YA(i,Nr.dirname(e)),n=await Le.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Ln)throw new Error(`Native check receipt exceeds ${Ln} bytes`);let[a,o]=await Promise.all([Le.realpath(t),Le.realpath(e)]);if(!L(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Wu.O_RDONLY|Wu.O_NOFOLLOW|Wu.O_NONBLOCK,c=await Le.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(),Le.lstat(e),Le.realpath(e)]);if(await _g(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Qo(n,l)||!Qo(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Ln+1-h,E=await c.read(v,0,Math.min(v.length,y),null);if(E.bytesRead===0)break;if(h+=E.bytesRead,h>Ln)throw new Error(`Native check receipt exceeds ${Ln} bytes`);f.push(Buffer.from(v.subarray(0,E.bytesRead)))}let[p,m,b]=await Promise.all([c.stat(),Le.lstat(e),Le.realpath(e)]);if(await _g(r),!m.isFile()||m.isSymbolicLink()||b!==o||!L(a,b)||!Qo(l,p)||!Qo(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Ig(e,t,i){let r=QA(i),n=G(e,t),a=ZA(e,t,r),o=se(e,a);await z(o,a);let s=Ng(await e_(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Fn=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var FF=64*1024;var MF=3600*1e3;var qF=r_(i_);var n_=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Tg(e,t){let i=[];for(let r of n_){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 jg(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Ig(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 si=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 a_(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 o_(e){let t=a_(e.bundle.baseline),i=await _l(e.paths,t,{origin:"explicit",now:e.now});return du({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 Og(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Dn(e.paths,e.state.name,e.state.implementation_scope),i=await sr({changeDir:de(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await o_({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 Hg(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Og(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 s_(e){let t=await oe({root:de(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:wh(t.text)}}function c_(e){let{receipt:t,implementationScope:i}=e,r=[],n=uu({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 l_(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:qu(e.implementationScope.scope.declaredArtifacts)}}async function $g(e){let t=await Bn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Tg(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 si([{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 jg({paths:e.paths,state:e.state,receipt:t});if(n){let a=c_({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 u_(e){let t=l_({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await $g({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof si)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 $g({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof si)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 si(i)}function zu(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ju(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:zu(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Og(e),yr(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:zu(e.state.verification_result,"stale"),envelope:null};let r=await s_({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 u_({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:zu(e.state.verification_result,"invalid"),envelope:null}}}function f_(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Bg(e){try{return await d_.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function p_(e,t){try{return(await oe({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function h_(e,t,i){let r=Ao(e,i.capability);if(!L(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Dg.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await p_(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await oe({root:de(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 m_(e,t){return Bg(Pu(e,t))}async function Gu(e){let t=e.now??new Date,i=await kt(e.paths,e.name),r=await Nt(e.paths,e.name),n=await Pe(e.paths.projectRoot),a=f_(i.name,t),o=Dg.resolve(e.paths.nativeRoot,...a.split("/"));if(!L(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(v=>h_(e.paths,i.name,v))),Ju({paths:e.paths,state:i,now:t}),Xo(e.paths,i.name),Ro(e.paths,i.name),bm(e.paths,i.name),m_(e.paths,i.name),Bg(o)]);return og({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]})}async function v_(e,t){let i=G(e,t.name),r=await ar(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 yo(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 yi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function g_(e,t){let i=await v_(e,t);return{committed:i,latest:Ov(i),history:$v(i)}}async function Lg(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await g_(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 Rt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function y_(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function N_(e){return(await Zm(e))?.change??null}function b_(e,t,i=!1,r){return Wo({state:e,archiveReady:t,evidenceRetreat:i}).command}async function k_(e,t){let i=de(e,t.name),r=[...(await Vl(i,t.brief)).findings,...(await Rm(e,t)).findings,...await ev(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await po(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 Kh(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 sr({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 zv(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 Wl(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 Uu(e,t,i){let r=await N_(e)===t,n=await al(e,t),a=await ko(e,t),o;try{let g=await Ml(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},S=_u({paths:e,state:o,findings:[g]}),$=Wo({state:o,findings:S});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:$.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Iu(S),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:$,workspace:a,runtime:n,...i?.details?{findings:S}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await rg({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Lg(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 sr({changeDir:de(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),S=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let fe=await yr(e,o.name,o.verification_evidence);for(let X of fe.acceptanceTrace.entries)S.set(X.acceptanceId,X.status==="failed"?"failed":X.status==="missing"?"missing":"satisfied")}let $=vh({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:S,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=$.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",$.nextCursor,"--project-root",e.projectRoot]:null;u={...$,...T?{nextPageCommand:y_(T),nextPageArgs:T}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Xo(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(S=>({code:S,message:`Native change overlap is visible in the current root: ${S}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await Nt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let S=await yn({paths:e,identity:g});S.state==="drifted"&&S.code&&f.push({code:S.code,message:S.message??"Native workspace binding is no longer valid"})}else{let S=await So({paths:e,identity:g});f.push(...S.findingCodes.map($=>({code:$,message:`Native workspace advisory changed: ${$} (${S.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let g=await Hg({paths:e,state:o});v=g.freshness!=="fresh",h.push(...g.findingCodes.map(S=>({code:S,message:`Native Verify implementation scope is not current: ${S}`})))}let p=null,m=[];if(o.phase==="archive")try{p=await Gu({paths:e,name:o.name}),m.push(...p.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 b=[...await k_(e,o),...s.findings,...d,...f,...h,...l,...m].filter((g,S,$)=>$.findIndex(T=>T.code===g.code&&T.path===g.path)===S),y=_u({paths:e,state:o,findings:b}),E=y.filter(g=>!or(g.code)),k=o.phase==="archive"&&p?.ready===!0&&E.length===0,P=v||o.phase==="archive"&&(p?.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)),N=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),x=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:N||x?null:b_(o,k,P,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:Iu(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Wo({state:o,findings:y,archiveReady:k,evidenceRetreat:P,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:Go,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 Fg(e){let t;try{t=await yl({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await w_.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Rt.maxChanges))throw new Error(`Native status exceeds ${Rt.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Zo(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function es(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function S_(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Mn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Zo({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[es("summary","--summary"),S_(e.name,e.flag)]}}function Ku(e){return[Mn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Mn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Mg(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[es("summary","--summary")],commandAlternatives:[Mn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Ku({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Zo({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[es("summary","--summary")],commandAlternatives:[Mn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ku({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[es("summary","--summary")],commandAlternatives:Ku({change:e.name,stateVersion:e.state_version}),runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?Zo({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:Zo({change:e.name,stateVersion:e.state_version,action:"confirm-shape",flag:"--confirmed"}),requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Mn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:r("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}function E_(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 P_(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 Yu(e){let t=await Qm(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=P_(e.paths,t.state),n=await Xl({paths:e.paths,state:t.state}),a=Mg(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:E_(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}}:{}}}var C_=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function ts(e,t){let i=ci.normalize(Xu(e)),r=ci.normalize(Xu(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Xu(e){let t=ci.resolve(e);try{return x_.native(t)}catch{return t}}function R_(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function qg(e){let t=[];for(let i of await Fg(e))t.push({name:i,kind:await tu(e,i)?"portable":"legacy"});return t}async function Jg(e){let t=ci.resolve(e),i=xi(e),r=i.length>0?i:[t];r.some(o=>ts(o,t))||r.push(t);let n=[],a=new Set;for(let o of r.map(s=>ci.resolve(s)).sort()){let s=ts(o,t)?t:o,c=Xu(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Pe(s);if(!u)continue;let d=await vt(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await qg(d)})}if(n.length===0){let o=await Pe(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await vt(e,o.native.artifact_root);n.push({projectRoot:ci.resolve(e),config:o,paths:s,changes:await qg(s)})}return n}function Vg(e,t){return e.workspace.bindingState==="aligned"?0:ts(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Gg(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 Yu({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 ko(c.paths,n),portableStatus:null}}));o.sort((c,l)=>Vg(c,e)-Vg(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>Rt.maxChanges)throw new Error(`Native status discovery exceeds ${Rt.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function Wg(e,t){let i=t.toString(36),r=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function A_(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=C_.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=j("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 zg(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?R_(i):null,nextPageArgs:i}}async function __(e,t,i){let r=null;try{r=await Sm(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}}}:Uu(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 Ug(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:Yu({paths:e.source.paths,name:e.name,details:t})}return __(e,t,i)}async function Kg(e){let t=await Jg(e.projectRoot),i=(await Gg(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>ts(n.projectRoot,e.projectRoot))??t[0];return Uu(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 Ug(i[0],e.details??!1,e.acceptanceCursor)}async function Yg(e){let t=await Jg(e.projectRoot),i=await Gg(e.projectRoot,t),r=j("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=A_({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Rt.maxItems).map(u=>Ug(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=f<i.length?Wg(r,f):null,v={schema:s,total:i.length,offset:n,items:d,nextCursor:h,...zg(ci.resolve(e.projectRoot),h),limits:{...Rt}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Rt.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<i.length?Wg(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...zg(ci.resolve(e.projectRoot),l),limits:{...Rt}}}import qn from"path";import{realpathSync as D_}from"fs";var RM={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var LM=16*1024*1024,FM=256*1024,MM=16*1024;var JM=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var Tq=16*1024*1024,is=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"},rs=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 ns=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Xg=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Zu=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Xg,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker]
|
|
171
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
172
172
|
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Qu(e,t){return`${e}:
|
|
173
173
|
${t.map(i=>` ${i}`).join(`
|
|
174
|
-
`)}`}function
|
|
174
|
+
`)}`}function $_(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Zu[i]||t.length>1&&Zu[t[0]]?.subcommands?i:t[0]}function O_(e=[]){let t=$_(e),i=Zu[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Qu("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Xg];return n&&n.length>0&&r.push("",Qu("Options",n)),r.push("",`Output:
|
|
175
175
|
${i.output}`),i.examples&&r.push("",Qu("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
176
176
|
`)}
|
|
177
|
-
`}}var
|
|
178
|
-
`}}function iw(e,t){if(t instanceof tt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof is)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 rs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof
|
|
179
|
-
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function nw(e,t){let i=as(e,"--details"),r=os(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!n)throw new tt("status --details requires a change name");if(r&&n)throw new tt("--cursor is only valid for status lists");if(r&&i)throw new tt("--cursor cannot be combined with --details");Zg(e);let a=n?await Kg({projectRoot:t,name:n,details:i}):await Yg({projectRoot:t,...r?{cursor:r}:{}});return tw("status",a)}function
|
|
180
|
-
`}}async function aw(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{as(n,"--json"),s=os(n,"--project-root");let u=[...n,...a],d=await ew(s);c=await t(u,d)}catch(u){c=iw(e,u)}let l=o?
|
|
177
|
+
`}}var H_=O_().usage;var nV=10*1024*1024,tt=class extends Error{};function as(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new tt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function os(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new tt(`${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 tt(`${t} requires a value`);return e.splice(r,2),n}function Zg(e){if(e.length>0)throw new tt(`Unexpected argument: ${e[0]}`)}function ed(e,t){let i=qn.normalize(Qg(e)),r=qn.normalize(Qg(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Qg(e){let t=qn.resolve(e);try{return D_.native(t)}catch{return t}}function B_(e){let t=qn.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||!ed(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||ed(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:ed(process.cwd(),i.currentWorktreeRoot)?qn.resolve(process.cwd()):i.currentWorktreeRoot}async function ew(e){return e?B_(e):rl(process.cwd())}function tw(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
178
|
+
`}}function iw(e,t){if(t instanceof tt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof is)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 rs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Po)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 Nn)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 ns)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof xo)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 si)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Fn)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 rw(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}})+`
|
|
179
|
+
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function nw(e,t){let i=as(e,"--details"),r=os(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!n)throw new tt("status --details requires a change name");if(r&&n)throw new tt("--cursor is only valid for status lists");if(r&&i)throw new tt("--cursor cannot be combined with --details");Zg(e);let a=n?await Kg({projectRoot:t,name:n,details:i}):await Yg({projectRoot:t,...r?{cursor:r}:{}});return tw("status",a)}function L_(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}})+`
|
|
180
|
+
`}}async function aw(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{as(n,"--json"),s=os(n,"--project-root");let u=[...n,...a],d=await ew(s);c=await t(u,d)}catch(u){c=iw(e,u)}let l=o?L_(c):rw(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
181
181
|
`)?"":`
|
|
182
182
|
`)),l.exitCode}process.exitCode=await aw("status",nw);
|