@rpamis/comet 0.4.2 → 0.4.3

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.
Files changed (72) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +332 -332
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-check.mjs +89 -89
  5. package/assets/skills/comet/scripts/comet-guard.mjs +102 -102
  6. package/assets/skills/comet/scripts/comet-hook-router.mjs +106 -106
  7. package/assets/skills/comet/scripts/comet-runtime.mjs +227 -227
  8. package/assets/skills/comet/scripts/comet-state.mjs +124 -124
  9. package/assets/skills/comet-classic/SKILL.md +2 -0
  10. package/assets/skills/comet-classic/reference/scripts.md +8 -0
  11. package/assets/skills/comet-hotfix/SKILL.md +1 -0
  12. package/assets/skills/comet-native/SKILL.md +3 -1
  13. package/assets/skills/comet-native/reference/commands.md +10 -0
  14. package/assets/skills/comet-native/scripts/comet-native-next.mjs +13 -13
  15. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +31 -31
  16. package/assets/skills/comet-native/scripts/comet-native-show.mjs +26 -26
  17. package/assets/skills/comet-tweak/SKILL.md +1 -0
  18. package/assets/skills-zh/comet-classic/SKILL.md +2 -0
  19. package/assets/skills-zh/comet-classic/reference/scripts.md +2 -0
  20. package/assets/skills-zh/comet-hotfix/SKILL.md +1 -0
  21. package/assets/skills-zh/comet-native/SKILL.md +3 -1
  22. package/assets/skills-zh/comet-native/reference/commands.md +10 -0
  23. package/assets/skills-zh/comet-tweak/SKILL.md +1 -0
  24. package/bin/comet-daemon-router.js +35 -7
  25. package/dist/app/commands/daemon-server.d.ts.map +1 -1
  26. package/dist/app/commands/daemon-server.js +1 -0
  27. package/dist/app/commands/daemon-server.js.map +1 -1
  28. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  29. package/dist/app/commands/project-knowledge.js +0 -1
  30. package/dist/app/commands/project-knowledge.js.map +1 -1
  31. package/dist/domains/comet-classic/classic-check-snapshot.d.ts +2 -0
  32. package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
  33. package/dist/domains/comet-classic/classic-check-snapshot.js +22 -1
  34. package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
  35. package/dist/domains/comet-native/native-portable-checks.d.ts +1 -0
  36. package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
  37. package/dist/domains/comet-native/native-portable-checks.js +8 -6
  38. package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
  39. package/dist/domains/project-knowledge/corpus.d.ts +5 -0
  40. package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
  41. package/dist/domains/project-knowledge/corpus.js +34 -9
  42. package/dist/domains/project-knowledge/corpus.js.map +1 -1
  43. package/dist/domains/project-knowledge/index-store.d.ts +5 -2
  44. package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
  45. package/dist/domains/project-knowledge/index-store.js +95 -52
  46. package/dist/domains/project-knowledge/index-store.js.map +1 -1
  47. package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
  48. package/dist/domains/project-knowledge/local-provider.js +14 -3
  49. package/dist/domains/project-knowledge/local-provider.js.map +1 -1
  50. package/dist/domains/project-knowledge/local-store.d.ts +2 -2
  51. package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
  52. package/dist/domains/project-knowledge/local-store.js +2 -2
  53. package/dist/domains/project-knowledge/local-store.js.map +1 -1
  54. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  55. package/dist/domains/project-knowledge/plugin.js +5 -4
  56. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  57. package/dist/domains/project-knowledge/provider-factory.d.ts.map +1 -1
  58. package/dist/domains/project-knowledge/provider-factory.js +7 -5
  59. package/dist/domains/project-knowledge/provider-factory.js.map +1 -1
  60. package/dist/domains/project-knowledge/types.d.ts +1 -0
  61. package/dist/domains/project-knowledge/types.d.ts.map +1 -1
  62. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  63. package/dist/domains/skill/platform-install.js +31 -3
  64. package/dist/domains/skill/platform-install.js.map +1 -1
  65. package/dist/platform/process/comet-daemon.d.ts.map +1 -1
  66. package/dist/platform/process/comet-daemon.js +1 -0
  67. package/dist/platform/process/comet-daemon.js.map +1 -1
  68. package/dist/platform/process/windows-process-broker.d.ts +12 -0
  69. package/dist/platform/process/windows-process-broker.d.ts.map +1 -0
  70. package/dist/platform/process/windows-process-broker.js +91 -0
  71. package/dist/platform/process/windows-process-broker.js.map +1 -0
  72. package/package.json +1 -1
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var fm=Object.create;var yo=Object.defineProperty;var pm=Object.getOwnPropertyDescriptor;var hm=Object.getOwnPropertyNames;var mm=Object.getPrototypeOf,vm=Object.prototype.hasOwnProperty;var nn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):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,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var k=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},gm=(e,t)=>{for(var r in t)yo(e,r,{get:t[r],enumerable:!0})},wm=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hm(t))!vm.call(e,n)&&n!==r&&yo(e,n,{get:()=>t[n],enumerable:!(i=pm(t,n))||i.enumerable});return e};var Je=(e,t,r)=>(r=e!=null?fm(mm(e)):{},wm(t||!e||!e.__esModule?yo(r,"default",{value:e,enumerable:!0}):r,e));var _=k(U=>{"use strict";var No=Symbol.for("yaml.alias"),Ol=Symbol.for("yaml.document"),an=Symbol.for("yaml.map"),Hl=Symbol.for("yaml.pair"),bo=Symbol.for("yaml.scalar"),on=Symbol.for("yaml.seq"),Ge=Symbol.for("yaml.node.type"),ym=e=>!!e&&typeof e=="object"&&e[Ge]===No,Nm=e=>!!e&&typeof e=="object"&&e[Ge]===Ol,bm=e=>!!e&&typeof e=="object"&&e[Ge]===an,km=e=>!!e&&typeof e=="object"&&e[Ge]===Hl,Dl=e=>!!e&&typeof e=="object"&&e[Ge]===bo,Sm=e=>!!e&&typeof e=="object"&&e[Ge]===on;function ql(e){if(e&&typeof e=="object")switch(e[Ge]){case an:case on:return!0}return!1}function Em(e){if(e&&typeof e=="object")switch(e[Ge]){case No:case an:case bo:case on:return!0}return!1}var Cm=e=>(Dl(e)||ql(e))&&!!e.anchor;U.ALIAS=No;U.DOC=Ol;U.MAP=an;U.NODE_TYPE=Ge;U.PAIR=Hl;U.SCALAR=bo;U.SEQ=on;U.hasAnchor=Cm;U.isAlias=ym;U.isCollection=ql;U.isDocument=Nm;U.isMap=bm;U.isNode=Em;U.isPair=km;U.isScalar=Dl;U.isSeq=Sm});var Fr=k(ko=>{"use strict";var M=_(),ne=Symbol("break visit"),Fl=Symbol("skip children"),Oe=Symbol("remove node");function sn(e,t){let r=Ll(t);M.isDocument(e)?nr(null,e.contents,r,Object.freeze([e]))===Oe&&(e.contents=null):nr(null,e,r,Object.freeze([]))}sn.BREAK=ne;sn.SKIP=Fl;sn.REMOVE=Oe;function nr(e,t,r,i){let n=Bl(e,t,r,i);if(M.isNode(n)||M.isPair(n))return Vl(e,i,n),nr(e,n,r,i);if(typeof n!="symbol"){if(M.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=nr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ne)return ne;o===Oe&&(t.items.splice(a,1),a-=1)}}}else if(M.isPair(t)){i=Object.freeze(i.concat(t));let a=nr("key",t.key,r,i);if(a===ne)return ne;a===Oe&&(t.key=null);let o=nr("value",t.value,r,i);if(o===ne)return ne;o===Oe&&(t.value=null)}}return n}async function cn(e,t){let r=Ll(t);M.isDocument(e)?await ar(null,e.contents,r,Object.freeze([e]))===Oe&&(e.contents=null):await ar(null,e,r,Object.freeze([]))}cn.BREAK=ne;cn.SKIP=Fl;cn.REMOVE=Oe;async function ar(e,t,r,i){let n=await Bl(e,t,r,i);if(M.isNode(n)||M.isPair(n))return Vl(e,i,n),ar(e,n,r,i);if(typeof n!="symbol"){if(M.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ar(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ne)return ne;o===Oe&&(t.items.splice(a,1),a-=1)}}}else if(M.isPair(t)){i=Object.freeze(i.concat(t));let a=await ar("key",t.key,r,i);if(a===ne)return ne;a===Oe&&(t.key=null);let o=await ar("value",t.value,r,i);if(o===ne)return ne;o===Oe&&(t.value=null)}}return n}function Ll(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 Bl(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(M.isMap(t))return r.Map?.(e,t,i);if(M.isSeq(t))return r.Seq?.(e,t,i);if(M.isPair(t))return r.Pair?.(e,t,i);if(M.isScalar(t))return r.Scalar?.(e,t,i);if(M.isAlias(t))return r.Alias?.(e,t,i)}function Vl(e,t,r){let i=t[t.length-1];if(M.isCollection(i))i.items[e]=r;else if(M.isPair(i))e==="key"?i.key=r:i.value=r;else if(M.isDocument(i))i.contents=r;else{let n=M.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}ko.visit=sn;ko.visitAsync=cn});var So=k(Wl=>{"use strict";var Ml=_(),xm=Fr(),Pm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rm=e=>e.replace(/[!,[\]{}]/g,t=>Pm[t]),Lr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}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,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Rm(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Ml.isNode(t.contents)){let a={};xm.visit(t.contents,(o,s)=>{Ml.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};Lr.defaultYaml={explicit:!1,version:"1.2"};Lr.defaultTags={"!!":"tag:yaml.org,2002:"};Wl.Directives=Lr});var ln=k(Br=>{"use strict";var zl=_(),_m=Fr();function Am(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Jl(e){let t=new Set;return _m.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Gl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Im(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Jl(e));let o=Gl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(zl.isScalar(o.node)||zl.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:i}}Br.anchorIsValid=Am;Br.anchorNames=Jl;Br.createNodeAnchors=Im;Br.findNewAnchor=Gl});var Eo=k(Ul=>{"use strict";function Vr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Vr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Vr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Vr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Vr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Ul.applyReviver=Vr});var st=k(Yl=>{"use strict";var jm=_();function Kl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Kl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!jm.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}Yl.toJS=Kl});var un=k(Ql=>{"use strict";var Tm=Eo(),Xl=_(),$m=st(),Co=class{constructor(t){Object.defineProperty(this,Xl.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:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Xl.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=$m.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Tm.applyReviver(a,{"":s},"",s):s}};Ql.NodeBase=Co});var Mr=k(Zl=>{"use strict";var Om=ln(),Hm=Fr(),or=_(),Dm=un(),qm=st(),xo=class extends Dm.NodeBase{constructor(t){super(or.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Hm.visit(t,{Node:(a,o)=>{(or.isAlias(o)||or.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(qm.toJS(o,null,r),s=i.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=dn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Om.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 dn(e,t,r){if(or.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(or.isCollection(t)){let i=0;for(let n of t.items){let a=dn(e,n,r);a>i&&(i=a)}return i}else if(or.isPair(t)){let i=dn(e,t.key,r),n=dn(e,t.value,r);return Math.max(i,n)}return 1}Zl.Alias=xo});var B=k(Po=>{"use strict";var Fm=_(),Lm=un(),Bm=st(),Vm=e=>!e||typeof e!="function"&&typeof e!="object",ct=class extends Lm.NodeBase{constructor(t){super(Fm.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Bm.toJS(this.value,t,r)}toString(){return String(this.value)}};ct.BLOCK_FOLDED="BLOCK_FOLDED";ct.BLOCK_LITERAL="BLOCK_LITERAL";ct.PLAIN="PLAIN";ct.QUOTE_DOUBLE="QUOTE_DOUBLE";ct.QUOTE_SINGLE="QUOTE_SINGLE";Po.Scalar=ct;Po.isScalarValue=Vm});var Wr=k(tu=>{"use strict";var Mm=Mr(),Dt=_(),eu=B(),Wm="tag:yaml.org,2002:";function zm(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Jm(e,t,r){if(Dt.isDocument(e)&&(e=e.contents),Dt.isNode(e))return e;if(Dt.isPair(e)){let u=r.schema[Dt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Mm.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Wm+t.slice(2));let l=zm(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new eu.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[Dt.MAP]:Symbol.iterator in Object(e)?o[Dt.SEQ]:o[Dt.MAP]}a&&(a(l),delete r.onTagObj);let d=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new eu.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}tu.createNode=Jm});var pn=k(fn=>{"use strict";var Gm=Wr(),He=_(),Um=un();function Ro(e,t,r){let i=r;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]=i,i=o}else i=new Map([[a,i]])}return Gm.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var ru=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,_o=class extends Um.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>He.isNode(i)||He.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(ru(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(He.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ro(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(He.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&He.isScalar(a)?a.value:a:He.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!He.isPair(r))return!1;let i=r.value;return i==null||t&&He.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return He.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(He.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ro(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};fn.Collection=_o;fn.collectionFromPath=Ro;fn.isEmptyPath=ru});var zr=k(hn=>{"use strict";var Km=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ao(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ym=(e,t,r)=>e.endsWith(`
4
+ var fm=Object.create;var yo=Object.defineProperty;var pm=Object.getOwnPropertyDescriptor;var hm=Object.getOwnPropertyNames;var mm=Object.getPrototypeOf,vm=Object.prototype.hasOwnProperty;var nn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var k=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},gm=(e,t)=>{for(var r in t)yo(e,r,{get:t[r],enumerable:!0})},wm=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hm(t))!vm.call(e,n)&&n!==r&&yo(e,n,{get:()=>t[n],enumerable:!(i=pm(t,n))||i.enumerable});return e};var Je=(e,t,r)=>(r=e!=null?fm(mm(e)):{},wm(t||!e||!e.__esModule?yo(r,"default",{value:e,enumerable:!0}):r,e));var _=k(U=>{"use strict";var No=Symbol.for("yaml.alias"),Ol=Symbol.for("yaml.document"),an=Symbol.for("yaml.map"),Hl=Symbol.for("yaml.pair"),bo=Symbol.for("yaml.scalar"),on=Symbol.for("yaml.seq"),Ge=Symbol.for("yaml.node.type"),ym=e=>!!e&&typeof e=="object"&&e[Ge]===No,Nm=e=>!!e&&typeof e=="object"&&e[Ge]===Ol,bm=e=>!!e&&typeof e=="object"&&e[Ge]===an,km=e=>!!e&&typeof e=="object"&&e[Ge]===Hl,Dl=e=>!!e&&typeof e=="object"&&e[Ge]===bo,Sm=e=>!!e&&typeof e=="object"&&e[Ge]===on;function ql(e){if(e&&typeof e=="object")switch(e[Ge]){case an:case on:return!0}return!1}function Em(e){if(e&&typeof e=="object")switch(e[Ge]){case No:case an:case bo:case on:return!0}return!1}var xm=e=>(Dl(e)||ql(e))&&!!e.anchor;U.ALIAS=No;U.DOC=Ol;U.MAP=an;U.NODE_TYPE=Ge;U.PAIR=Hl;U.SCALAR=bo;U.SEQ=on;U.hasAnchor=xm;U.isAlias=ym;U.isCollection=ql;U.isDocument=Nm;U.isMap=bm;U.isNode=Em;U.isPair=km;U.isScalar=Dl;U.isSeq=Sm});var Fr=k(ko=>{"use strict";var M=_(),ne=Symbol("break visit"),Fl=Symbol("skip children"),Oe=Symbol("remove node");function sn(e,t){let r=Ll(t);M.isDocument(e)?nr(null,e.contents,r,Object.freeze([e]))===Oe&&(e.contents=null):nr(null,e,r,Object.freeze([]))}sn.BREAK=ne;sn.SKIP=Fl;sn.REMOVE=Oe;function nr(e,t,r,i){let n=Bl(e,t,r,i);if(M.isNode(n)||M.isPair(n))return Vl(e,i,n),nr(e,n,r,i);if(typeof n!="symbol"){if(M.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=nr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ne)return ne;o===Oe&&(t.items.splice(a,1),a-=1)}}}else if(M.isPair(t)){i=Object.freeze(i.concat(t));let a=nr("key",t.key,r,i);if(a===ne)return ne;a===Oe&&(t.key=null);let o=nr("value",t.value,r,i);if(o===ne)return ne;o===Oe&&(t.value=null)}}return n}async function cn(e,t){let r=Ll(t);M.isDocument(e)?await ar(null,e.contents,r,Object.freeze([e]))===Oe&&(e.contents=null):await ar(null,e,r,Object.freeze([]))}cn.BREAK=ne;cn.SKIP=Fl;cn.REMOVE=Oe;async function ar(e,t,r,i){let n=await Bl(e,t,r,i);if(M.isNode(n)||M.isPair(n))return Vl(e,i,n),ar(e,n,r,i);if(typeof n!="symbol"){if(M.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ar(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ne)return ne;o===Oe&&(t.items.splice(a,1),a-=1)}}}else if(M.isPair(t)){i=Object.freeze(i.concat(t));let a=await ar("key",t.key,r,i);if(a===ne)return ne;a===Oe&&(t.key=null);let o=await ar("value",t.value,r,i);if(o===ne)return ne;o===Oe&&(t.value=null)}}return n}function Ll(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 Bl(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(M.isMap(t))return r.Map?.(e,t,i);if(M.isSeq(t))return r.Seq?.(e,t,i);if(M.isPair(t))return r.Pair?.(e,t,i);if(M.isScalar(t))return r.Scalar?.(e,t,i);if(M.isAlias(t))return r.Alias?.(e,t,i)}function Vl(e,t,r){let i=t[t.length-1];if(M.isCollection(i))i.items[e]=r;else if(M.isPair(i))e==="key"?i.key=r:i.value=r;else if(M.isDocument(i))i.contents=r;else{let n=M.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}ko.visit=sn;ko.visitAsync=cn});var So=k(Wl=>{"use strict";var Ml=_(),Cm=Fr(),Pm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rm=e=>e.replace(/[!,[\]{}]/g,t=>Pm[t]),Lr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}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,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Rm(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Ml.isNode(t.contents)){let a={};Cm.visit(t.contents,(o,s)=>{Ml.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};Lr.defaultYaml={explicit:!1,version:"1.2"};Lr.defaultTags={"!!":"tag:yaml.org,2002:"};Wl.Directives=Lr});var ln=k(Br=>{"use strict";var zl=_(),_m=Fr();function Am(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Jl(e){let t=new Set;return _m.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Gl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Im(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Jl(e));let o=Gl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(zl.isScalar(o.node)||zl.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:i}}Br.anchorIsValid=Am;Br.anchorNames=Jl;Br.createNodeAnchors=Im;Br.findNewAnchor=Gl});var Eo=k(Ul=>{"use strict";function Vr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Vr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Vr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Vr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Vr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Ul.applyReviver=Vr});var st=k(Yl=>{"use strict";var jm=_();function Kl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Kl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!jm.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}Yl.toJS=Kl});var un=k(Ql=>{"use strict";var Tm=Eo(),Xl=_(),$m=st(),xo=class{constructor(t){Object.defineProperty(this,Xl.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:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Xl.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=$m.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Tm.applyReviver(a,{"":s},"",s):s}};Ql.NodeBase=xo});var Mr=k(Zl=>{"use strict";var Om=ln(),Hm=Fr(),or=_(),Dm=un(),qm=st(),Co=class extends Dm.NodeBase{constructor(t){super(or.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Hm.visit(t,{Node:(a,o)=>{(or.isAlias(o)||or.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(qm.toJS(o,null,r),s=i.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=dn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Om.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 dn(e,t,r){if(or.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(or.isCollection(t)){let i=0;for(let n of t.items){let a=dn(e,n,r);a>i&&(i=a)}return i}else if(or.isPair(t)){let i=dn(e,t.key,r),n=dn(e,t.value,r);return Math.max(i,n)}return 1}Zl.Alias=Co});var B=k(Po=>{"use strict";var Fm=_(),Lm=un(),Bm=st(),Vm=e=>!e||typeof e!="function"&&typeof e!="object",ct=class extends Lm.NodeBase{constructor(t){super(Fm.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Bm.toJS(this.value,t,r)}toString(){return String(this.value)}};ct.BLOCK_FOLDED="BLOCK_FOLDED";ct.BLOCK_LITERAL="BLOCK_LITERAL";ct.PLAIN="PLAIN";ct.QUOTE_DOUBLE="QUOTE_DOUBLE";ct.QUOTE_SINGLE="QUOTE_SINGLE";Po.Scalar=ct;Po.isScalarValue=Vm});var Wr=k(tu=>{"use strict";var Mm=Mr(),Dt=_(),eu=B(),Wm="tag:yaml.org,2002:";function zm(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Jm(e,t,r){if(Dt.isDocument(e)&&(e=e.contents),Dt.isNode(e))return e;if(Dt.isPair(e)){let u=r.schema[Dt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Mm.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Wm+t.slice(2));let l=zm(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new eu.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[Dt.MAP]:Symbol.iterator in Object(e)?o[Dt.SEQ]:o[Dt.MAP]}a&&(a(l),delete r.onTagObj);let d=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new eu.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}tu.createNode=Jm});var pn=k(fn=>{"use strict";var Gm=Wr(),He=_(),Um=un();function Ro(e,t,r){let i=r;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]=i,i=o}else i=new Map([[a,i]])}return Gm.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var ru=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,_o=class extends Um.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>He.isNode(i)||He.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(ru(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(He.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ro(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(He.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&He.isScalar(a)?a.value:a:He.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!He.isPair(r))return!1;let i=r.value;return i==null||t&&He.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return He.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(He.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ro(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};fn.Collection=_o;fn.collectionFromPath=Ro;fn.isEmptyPath=ru});var zr=k(hn=>{"use strict";var Km=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ao(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ym=(e,t,r)=>e.endsWith(`
6
6
  `)?Ao(r,t):r.includes(`
7
7
  `)?`
8
8
  `+Ao(r,t):(e.endsWith(" ")?"":" ")+r;hn.indentComment=Ao;hn.lineComment=Ym;hn.stringifyComment=Km});var nu=k(Jr=>{"use strict";var Xm="flow",Io="block",mn="quoted";function Qm(e,t,r="flow",{indentAtStart:i,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=[],d={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let f,h,m=!1,p=-1,g=-1,v=-1;r===Io&&(p=iu(e,p,t.length),p!==-1&&(u=p+c));for(let N;N=e[p+=1];){if(r===mn&&N==="\\"){switch(g=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}v=p}if(N===`
@@ -44,17 +44,17 @@ ${Yr.indentComment(R,r.indent)}`}E===""&&!r.inFlow?w===`
44
44
  ${r.indent}`}else if(!h&&Ue.isCollection(t)){let R=E[0],S=E.indexOf(`
45
45
  `),I=S!==-1,K=r.inFlow??t.flow??t.items.length===0;if(I||!K){let Ne=!1;if(I&&(R==="&"||R==="!")){let F=E.indexOf(" ");R==="&"&&F!==-1&&F<S&&E[F+1]==="!"&&(F=E.indexOf(" ",F+1)),(F===-1||S<F)&&(Ne=!0)}Ne||(w=`
46
46
  ${r.indent}`)}}else(E===""||E[0]===`
47
- `)&&(w="");return g+=w+E,r.inFlow?y&&i&&i():N&&!y?g+=Yr.lineComment(g,r.indent,l(N)):p&&n&&n(),g}cu.stringifyPair=lv});var Ho=k(Oo=>{"use strict";var uu=nn("process");function uv(e,...t){e==="debug"&&console.log(...t)}function dv(e,t){(e==="debug"||e==="warn")&&(typeof uu.emitWarning=="function"?uu.emitWarning(t):console.warn(t))}Oo.debug=uv;Oo.warn=dv});var Sn=k(kn=>{"use strict";var bn=_(),du=B(),yn="<<",Nn={identify:e=>e===yn||typeof e=="symbol"&&e.description===yn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new du.Scalar(Symbol(yn)),{addToJSMap:fu}),stringify:()=>yn},fv=(e,t)=>(Nn.identify(t)||bn.isScalar(t)&&(!t.type||t.type===du.Scalar.PLAIN)&&Nn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Nn.tag&&r.default);function fu(e,t,r){let i=pu(e,r);if(bn.isSeq(i))for(let n of i.items)Do(e,t,n);else if(Array.isArray(i))for(let n of i)Do(e,t,n);else Do(e,t,i)}function Do(e,t,r){let i=pu(e,r);if(!bn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.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 pu(e,t){return e&&bn.isAlias(t)?t.resolve(e.doc,e):t}kn.addMergeToJSMap=fu;kn.isMergeKey=fv;kn.merge=Nn});var Fo=k(vu=>{"use strict";var pv=Ho(),hu=Sn(),hv=Kr(),mu=_(),qo=st();function mv(e,t,{key:r,value:i}){if(mu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(hu.isMergeKey(e,r))hu.addMergeToJSMap(e,t,i);else{let n=qo.toJS(r,"",e);if(t instanceof Map)t.set(n,qo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=vv(r,n,e),o=qo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function vv(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(mu.isNode(e)&&r?.doc){let i=hv.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),pv.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}vu.addPairToJSMap=mv});var dt=k(Lo=>{"use strict";var gu=Wr(),gv=lu(),wv=Fo(),En=_();function yv(e,t,r){let i=gu.createNode(e,void 0,r),n=gu.createNode(t,void 0,r);return new Cn(i,n)}var Cn=class e{constructor(t,r=null){Object.defineProperty(this,En.NODE_TYPE,{value:En.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return En.isNode(r)&&(r=r.clone(t)),En.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return wv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?gv.stringifyPair(this,t,r,i):JSON.stringify(this)}};Lo.Pair=Cn;Lo.createPair=yv});var Bo=k(yu=>{"use strict";var qt=_(),wu=Kr(),xn=zr();function Nv(e,t,r){return(t.inFlow??e.flow?kv:bv)(e,t,r)}function bv({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,d=Object.assign({},r,{indent:a,type:null}),u=!1,f=[];for(let m=0;m<t.length;++m){let p=t[m],g=null;if(qt.isNode(p))!u&&p.spaceBefore&&f.push(""),Pn(r,f,p.commentBefore,u),p.comment&&(g=p.comment);else if(qt.isPair(p)){let b=qt.isNode(p.key)?p.key:null;b&&(!u&&b.spaceBefore&&f.push(""),Pn(r,f,b.commentBefore,u))}u=!1;let v=wu.stringify(p,d,()=>g=null,()=>u=!0);g&&(v+=xn.lineComment(v,a,l(g))),u&&g&&(u=!1),f.push(i+v)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let m=1;m<f.length;++m){let p=f[m];h+=p?`
47
+ `)&&(w="");return g+=w+E,r.inFlow?y&&i&&i():N&&!y?g+=Yr.lineComment(g,r.indent,l(N)):p&&n&&n(),g}cu.stringifyPair=lv});var Ho=k(Oo=>{"use strict";var uu=nn("process");function uv(e,...t){e==="debug"&&console.log(...t)}function dv(e,t){(e==="debug"||e==="warn")&&(typeof uu.emitWarning=="function"?uu.emitWarning(t):console.warn(t))}Oo.debug=uv;Oo.warn=dv});var Sn=k(kn=>{"use strict";var bn=_(),du=B(),yn="<<",Nn={identify:e=>e===yn||typeof e=="symbol"&&e.description===yn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new du.Scalar(Symbol(yn)),{addToJSMap:fu}),stringify:()=>yn},fv=(e,t)=>(Nn.identify(t)||bn.isScalar(t)&&(!t.type||t.type===du.Scalar.PLAIN)&&Nn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Nn.tag&&r.default);function fu(e,t,r){let i=pu(e,r);if(bn.isSeq(i))for(let n of i.items)Do(e,t,n);else if(Array.isArray(i))for(let n of i)Do(e,t,n);else Do(e,t,i)}function Do(e,t,r){let i=pu(e,r);if(!bn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.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 pu(e,t){return e&&bn.isAlias(t)?t.resolve(e.doc,e):t}kn.addMergeToJSMap=fu;kn.isMergeKey=fv;kn.merge=Nn});var Fo=k(vu=>{"use strict";var pv=Ho(),hu=Sn(),hv=Kr(),mu=_(),qo=st();function mv(e,t,{key:r,value:i}){if(mu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(hu.isMergeKey(e,r))hu.addMergeToJSMap(e,t,i);else{let n=qo.toJS(r,"",e);if(t instanceof Map)t.set(n,qo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=vv(r,n,e),o=qo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function vv(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(mu.isNode(e)&&r?.doc){let i=hv.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),pv.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}vu.addPairToJSMap=mv});var dt=k(Lo=>{"use strict";var gu=Wr(),gv=lu(),wv=Fo(),En=_();function yv(e,t,r){let i=gu.createNode(e,void 0,r),n=gu.createNode(t,void 0,r);return new xn(i,n)}var xn=class e{constructor(t,r=null){Object.defineProperty(this,En.NODE_TYPE,{value:En.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return En.isNode(r)&&(r=r.clone(t)),En.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return wv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?gv.stringifyPair(this,t,r,i):JSON.stringify(this)}};Lo.Pair=xn;Lo.createPair=yv});var Bo=k(yu=>{"use strict";var qt=_(),wu=Kr(),Cn=zr();function Nv(e,t,r){return(t.inFlow??e.flow?kv:bv)(e,t,r)}function bv({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,d=Object.assign({},r,{indent:a,type:null}),u=!1,f=[];for(let m=0;m<t.length;++m){let p=t[m],g=null;if(qt.isNode(p))!u&&p.spaceBefore&&f.push(""),Pn(r,f,p.commentBefore,u),p.comment&&(g=p.comment);else if(qt.isPair(p)){let b=qt.isNode(p.key)?p.key:null;b&&(!u&&b.spaceBefore&&f.push(""),Pn(r,f,b.commentBefore,u))}u=!1;let v=wu.stringify(p,d,()=>g=null,()=>u=!0);g&&(v+=Cn.lineComment(v,a,l(g))),u&&g&&(u=!1),f.push(i+v)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let m=1;m<f.length;++m){let p=f[m];h+=p?`
48
48
  ${c}${p}`:`
49
49
  `}}return e?(h+=`
50
- `+xn.indentComment(l(e),c),s&&s()):u&&o&&o(),h}function kv({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let m=0;m<e.length;++m){let p=e[m],g=null;if(qt.isNode(p))p.spaceBefore&&u.push(""),Pn(t,u,p.commentBefore,!1),p.comment&&(g=p.comment);else if(qt.isPair(p)){let b=qt.isNode(p.key)?p.key:null;b&&(b.spaceBefore&&u.push(""),Pn(t,u,b.commentBefore,!1),b.comment&&(l=!0));let N=qt.isNode(p.value)?p.value:null;N?(N.comment&&(g=N.comment),N.commentBefore&&(l=!0)):p.value==null&&b?.comment&&(g=b.comment)}g&&(l=!0);let v=wu.stringify(p,c,()=>g=null);l||(l=u.length>d||v.includes(`
51
- `)),m<e.length-1?v+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((b,N)=>b+N.length+2,2)+(v.length+2)>t.options.lineWidth)),l&&(v+=",")),g&&(v+=xn.lineComment(v,i,s(g))),u.push(v),d=u.length}let{start:f,end:h}=r;if(u.length===0)return f+h;if(!l){let m=u.reduce((p,g)=>p+g.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let p of u)m+=p?`
50
+ `+Cn.indentComment(l(e),c),s&&s()):u&&o&&o(),h}function kv({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,d=0,u=[];for(let m=0;m<e.length;++m){let p=e[m],g=null;if(qt.isNode(p))p.spaceBefore&&u.push(""),Pn(t,u,p.commentBefore,!1),p.comment&&(g=p.comment);else if(qt.isPair(p)){let b=qt.isNode(p.key)?p.key:null;b&&(b.spaceBefore&&u.push(""),Pn(t,u,b.commentBefore,!1),b.comment&&(l=!0));let N=qt.isNode(p.value)?p.value:null;N?(N.comment&&(g=N.comment),N.commentBefore&&(l=!0)):p.value==null&&b?.comment&&(g=b.comment)}g&&(l=!0);let v=wu.stringify(p,c,()=>g=null);l||(l=u.length>d||v.includes(`
51
+ `)),m<e.length-1?v+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((b,N)=>b+N.length+2,2)+(v.length+2)>t.options.lineWidth)),l&&(v+=",")),g&&(v+=Cn.lineComment(v,i,s(g))),u.push(v),d=u.length}let{start:f,end:h}=r;if(u.length===0)return f+h;if(!l){let m=u.reduce((p,g)=>p+g.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let p of u)m+=p?`
52
52
  ${a}${n}${p}`:`
53
53
  `;return`${m}
54
- ${n}${h}`}else return`${f}${o}${u.join(" ")}${o}${h}`}function Pn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=xn.indentComment(t(i),e);r.push(a.trimStart())}}yu.stringifyCollection=Nv});var pt=k(Mo=>{"use strict";var Sv=Bo(),Ev=Fo(),Cv=pn(),ft=_(),Rn=dt(),xv=B();function Xr(e,t){let r=ft.isScalar(t)?t.value:t;for(let i of e)if(ft.isPair(i)&&(i.key===t||i.key===r||ft.isScalar(i.key)&&i.key.value===r))return i}var Vo=class extends Cv.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ft.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Rn.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;ft.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Rn.Pair(t,t?.value):i=new Rn.Pair(t.key,t.value);let n=Xr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);ft.isScalar(n.value)&&xv.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=Xr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Xr(this.items,t)?.value;return(!r&&ft.isScalar(n)?n.value:n)??void 0}has(t){return!!Xr(this.items,t)}set(t,r){this.add(new Rn.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Ev.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!ft.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})),Sv.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Mo.YAMLMap=Vo;Mo.findPair=Xr});var cr=k(bu=>{"use strict";var Pv=_(),Nu=pt(),Rv={collection:"map",default:!0,nodeClass:Nu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Pv.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Nu.YAMLMap.from(e,t,r)};bu.map=Rv});var ht=k(ku=>{"use strict";var _v=Wr(),Av=Bo(),Iv=pn(),An=_(),jv=B(),Tv=st(),Wo=class extends Iv.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(An.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=_n(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=_n(t);if(typeof i!="number")return;let n=this.items[i];return!r&&An.isScalar(n)?n.value:n}has(t){let r=_n(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=_n(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];An.isScalar(n)&&jv.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Tv.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Av.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(_v.createNode(s,void 0,i))}}return a}};function _n(e){let t=An.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}ku.YAMLSeq=Wo});var lr=k(Eu=>{"use strict";var $v=_(),Su=ht(),Ov={collection:"seq",default:!0,nodeClass:Su.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return $v.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Su.YAMLSeq.from(e,t,r)};Eu.seq=Ov});var Qr=k(Cu=>{"use strict";var Hv=Ur(),Dv={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),Hv.stringifyString(e,t,r,i)}};Cu.string=Dv});var In=k(Ru=>{"use strict";var xu=B(),Pu={identify:e=>e==null,createNode:()=>new xu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new xu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Pu.test.test(e)?e:t.options.nullStr};Ru.nullTag=Pu});var zo=k(Au=>{"use strict";var qv=B(),_u={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new qv.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&_u.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Au.boolTag=_u});var ur=k(Iu=>{"use strict";function Fv({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="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}Iu.stringifyNumber=Fv});var Go=k(jn=>{"use strict";var Lv=B(),Jo=ur(),Bv={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:Jo.stringifyNumber},Vv={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():Jo.stringifyNumber(e)}},Mv={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 Lv.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Jo.stringifyNumber};jn.float=Mv;jn.floatExp=Vv;jn.floatNaN=Bv});var Ko=k($n=>{"use strict";var ju=ur(),Tn=e=>typeof e=="bigint"||Number.isInteger(e),Uo=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Tu(e,t,r){let{value:i}=e;return Tn(i)&&i>=0?r+i.toString(t):ju.stringifyNumber(e)}var Wv={identify:e=>Tn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Uo(e,2,8,r),stringify:e=>Tu(e,8,"0o")},zv={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Uo(e,0,10,r),stringify:ju.stringifyNumber},Jv={identify:e=>Tn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Uo(e,2,16,r),stringify:e=>Tu(e,16,"0x")};$n.int=zv;$n.intHex=Jv;$n.intOct=Wv});var Ou=k($u=>{"use strict";var Gv=cr(),Uv=In(),Kv=lr(),Yv=Qr(),Xv=zo(),Yo=Go(),Xo=Ko(),Qv=[Gv.map,Kv.seq,Yv.string,Uv.nullTag,Xv.boolTag,Xo.intOct,Xo.int,Xo.intHex,Yo.floatNaN,Yo.floatExp,Yo.float];$u.schema=Qv});var qu=k(Du=>{"use strict";var Zv=B(),eg=cr(),tg=lr();function Hu(e){return typeof e=="bigint"||Number.isInteger(e)}var On=({value:e})=>JSON.stringify(e),rg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:On},{identify:e=>e==null,createNode:()=>new Zv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:On},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:On},{identify:Hu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Hu(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:On}],ig={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ng=[eg.map,tg.seq].concat(rg,ig);Du.schema=ng});var Zo=k(Fu=>{"use strict";var Zr=nn("buffer"),Qo=B(),ag=Ur(),og={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Zr.Buffer=="function")return Zr.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Zr.Buffer=="function")s=o instanceof Zr.Buffer?o.toString("base64"):Zr.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=Qo.Scalar.BLOCK_LITERAL),t!==Qo.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=s.substr(f,c);s=d.join(t===Qo.Scalar.BLOCK_LITERAL?`
54
+ ${n}${h}`}else return`${f}${o}${u.join(" ")}${o}${h}`}function Pn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Cn.indentComment(t(i),e);r.push(a.trimStart())}}yu.stringifyCollection=Nv});var pt=k(Mo=>{"use strict";var Sv=Bo(),Ev=Fo(),xv=pn(),ft=_(),Rn=dt(),Cv=B();function Xr(e,t){let r=ft.isScalar(t)?t.value:t;for(let i of e)if(ft.isPair(i)&&(i.key===t||i.key===r||ft.isScalar(i.key)&&i.key.value===r))return i}var Vo=class extends xv.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ft.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Rn.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;ft.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Rn.Pair(t,t?.value):i=new Rn.Pair(t.key,t.value);let n=Xr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);ft.isScalar(n.value)&&Cv.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=Xr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Xr(this.items,t)?.value;return(!r&&ft.isScalar(n)?n.value:n)??void 0}has(t){return!!Xr(this.items,t)}set(t,r){this.add(new Rn.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Ev.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!ft.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})),Sv.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Mo.YAMLMap=Vo;Mo.findPair=Xr});var cr=k(bu=>{"use strict";var Pv=_(),Nu=pt(),Rv={collection:"map",default:!0,nodeClass:Nu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Pv.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Nu.YAMLMap.from(e,t,r)};bu.map=Rv});var ht=k(ku=>{"use strict";var _v=Wr(),Av=Bo(),Iv=pn(),An=_(),jv=B(),Tv=st(),Wo=class extends Iv.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(An.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=_n(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=_n(t);if(typeof i!="number")return;let n=this.items[i];return!r&&An.isScalar(n)?n.value:n}has(t){let r=_n(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=_n(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];An.isScalar(n)&&jv.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Tv.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Av.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(_v.createNode(s,void 0,i))}}return a}};function _n(e){let t=An.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}ku.YAMLSeq=Wo});var lr=k(Eu=>{"use strict";var $v=_(),Su=ht(),Ov={collection:"seq",default:!0,nodeClass:Su.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return $v.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Su.YAMLSeq.from(e,t,r)};Eu.seq=Ov});var Qr=k(xu=>{"use strict";var Hv=Ur(),Dv={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),Hv.stringifyString(e,t,r,i)}};xu.string=Dv});var In=k(Ru=>{"use strict";var Cu=B(),Pu={identify:e=>e==null,createNode:()=>new Cu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Cu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Pu.test.test(e)?e:t.options.nullStr};Ru.nullTag=Pu});var zo=k(Au=>{"use strict";var qv=B(),_u={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new qv.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&_u.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Au.boolTag=_u});var ur=k(Iu=>{"use strict";function Fv({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="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}Iu.stringifyNumber=Fv});var Go=k(jn=>{"use strict";var Lv=B(),Jo=ur(),Bv={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:Jo.stringifyNumber},Vv={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():Jo.stringifyNumber(e)}},Mv={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 Lv.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Jo.stringifyNumber};jn.float=Mv;jn.floatExp=Vv;jn.floatNaN=Bv});var Ko=k($n=>{"use strict";var ju=ur(),Tn=e=>typeof e=="bigint"||Number.isInteger(e),Uo=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Tu(e,t,r){let{value:i}=e;return Tn(i)&&i>=0?r+i.toString(t):ju.stringifyNumber(e)}var Wv={identify:e=>Tn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Uo(e,2,8,r),stringify:e=>Tu(e,8,"0o")},zv={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Uo(e,0,10,r),stringify:ju.stringifyNumber},Jv={identify:e=>Tn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Uo(e,2,16,r),stringify:e=>Tu(e,16,"0x")};$n.int=zv;$n.intHex=Jv;$n.intOct=Wv});var Ou=k($u=>{"use strict";var Gv=cr(),Uv=In(),Kv=lr(),Yv=Qr(),Xv=zo(),Yo=Go(),Xo=Ko(),Qv=[Gv.map,Kv.seq,Yv.string,Uv.nullTag,Xv.boolTag,Xo.intOct,Xo.int,Xo.intHex,Yo.floatNaN,Yo.floatExp,Yo.float];$u.schema=Qv});var qu=k(Du=>{"use strict";var Zv=B(),eg=cr(),tg=lr();function Hu(e){return typeof e=="bigint"||Number.isInteger(e)}var On=({value:e})=>JSON.stringify(e),rg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:On},{identify:e=>e==null,createNode:()=>new Zv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:On},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:On},{identify:Hu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Hu(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:On}],ig={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ng=[eg.map,tg.seq].concat(rg,ig);Du.schema=ng});var Zo=k(Fu=>{"use strict";var Zr=nn("buffer"),Qo=B(),ag=Ur(),og={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Zr.Buffer=="function")return Zr.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Zr.Buffer=="function")s=o instanceof Zr.Buffer?o.toString("base64"):Zr.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=Qo.Scalar.BLOCK_LITERAL),t!==Qo.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=s.substr(f,c);s=d.join(t===Qo.Scalar.BLOCK_LITERAL?`
55
55
  `:" ")}return ag.stringifyString({comment:e,type:t,value:s},i,n,a)}};Fu.binary=og});var qn=k(Dn=>{"use strict";var Hn=_(),es=dt(),sg=B(),cg=ht();function Lu(e,t){if(Hn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Hn.isPair(i)){if(Hn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new es.Pair(new sg.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
56
56
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
57
- ${a.comment}`:i.comment}i=n}e.items[r]=Hn.isPair(i)?i:new es.Pair(i)}}else t("Expected a sequence for this tag");return e}function Bu(e,t,r){let{replacer:i}=r,n=new cg.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 i=="function"&&(o=i.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(es.createPair(s,c,r))}return n}var lg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Lu,createNode:Bu};Dn.createPairs=Bu;Dn.pairs=lg;Dn.resolvePairs=Lu});var is=k(rs=>{"use strict";var Vu=_(),ts=st(),ei=pt(),ug=ht(),Mu=qn(),Ft=class e extends ug.YAMLSeq{constructor(){super(),this.add=ei.YAMLMap.prototype.add.bind(this),this.delete=ei.YAMLMap.prototype.delete.bind(this),this.get=ei.YAMLMap.prototype.get.bind(this),this.has=ei.YAMLMap.prototype.has.bind(this),this.set=ei.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Vu.isPair(n)?(a=ts.toJS(n.key,"",r),o=ts.toJS(n.value,a,r)):a=ts.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Mu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Ft.tag="tag:yaml.org,2002:omap";var dg={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ft,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Mu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Vu.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Ft,r)},createNode:(e,t,r)=>Ft.from(e,t,r)};rs.YAMLOMap=Ft;rs.omap=dg});var Uu=k(ns=>{"use strict";var Wu=B();function zu({value:e,source:t},r){return t&&(e?Ju:Gu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Ju={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 Wu.Scalar(!0),stringify:zu},Gu={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 Wu.Scalar(!1),stringify:zu};ns.falseTag=Gu;ns.trueTag=Ju});var Ku=k(Fn=>{"use strict";var fg=B(),as=ur(),pg={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:as.stringifyNumber},hg={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():as.stringifyNumber(e)}},mg={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 fg.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:as.stringifyNumber};Fn.float=mg;Fn.floatExp=hg;Fn.floatNaN=pg});var Xu=k(ri=>{"use strict";var Yu=ur(),ti=e=>typeof e=="bigint"||Number.isInteger(e);function Ln(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){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,r);return n==="-"?-1*a:a}function os(e,t,r){let{value:i}=e;if(ti(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Yu.stringifyNumber(e)}var vg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Ln(e,2,2,r),stringify:e=>os(e,2,"0b")},gg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Ln(e,1,8,r),stringify:e=>os(e,8,"0")},wg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Ln(e,0,10,r),stringify:Yu.stringifyNumber},yg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Ln(e,2,16,r),stringify:e=>os(e,16,"0x")};ri.int=wg;ri.intBin=vg;ri.intHex=yg;ri.intOct=gg});var cs=k(ss=>{"use strict";var Mn=_(),Bn=dt(),Vn=pt(),Lt=class e extends Vn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Mn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Bn.Pair(t.key,null):r=new Bn.Pair(t,null),Vn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Vn.findPair(this.items,t);return!r&&Mn.isPair(i)?Mn.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Vn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Bn.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Bn.createPair(o,null,i));return a}};Lt.tag="tag:yaml.org,2002:set";var Ng={collection:"map",identify:e=>e instanceof Set,nodeClass:Lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Lt.from(e,t,r),resolve(e,t){if(Mn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Lt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ss.YAMLSet=Lt;ss.set=Ng});var us=k(Wn=>{"use strict";var bg=ur();function ls(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function Qu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return bg.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(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))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var kg={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:r})=>ls(e,r),stringify:Qu},Sg={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=>ls(e,!1),stringify:Qu},Zu={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(Zu.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),d=t[8];if(d&&d!=="Z"){let u=ls(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Wn.floatTime=Sg;Wn.intTime=kg;Wn.timestamp=Zu});var rd=k(td=>{"use strict";var Eg=cr(),Cg=In(),xg=lr(),Pg=Qr(),Rg=Zo(),ed=Uu(),ds=Ku(),zn=Xu(),_g=Sn(),Ag=is(),Ig=qn(),jg=cs(),fs=us(),Tg=[Eg.map,xg.seq,Pg.string,Cg.nullTag,ed.trueTag,ed.falseTag,zn.intBin,zn.intOct,zn.int,zn.intHex,ds.floatNaN,ds.floatExp,ds.float,Rg.binary,_g.merge,Ag.omap,Ig.pairs,jg.set,fs.intTime,fs.floatTime,fs.timestamp];td.schema=Tg});var fd=k(ms=>{"use strict";var od=cr(),$g=In(),sd=lr(),Og=Qr(),Hg=zo(),ps=Go(),hs=Ko(),Dg=Ou(),qg=qu(),cd=Zo(),ii=Sn(),ld=is(),ud=qn(),id=rd(),dd=cs(),Jn=us(),nd=new Map([["core",Dg.schema],["failsafe",[od.map,sd.seq,Og.string]],["json",qg.schema],["yaml11",id.schema],["yaml-1.1",id.schema]]),ad={binary:cd.binary,bool:Hg.boolTag,float:ps.float,floatExp:ps.floatExp,floatNaN:ps.floatNaN,floatTime:Jn.floatTime,int:hs.int,intHex:hs.intHex,intOct:hs.intOct,intTime:Jn.intTime,map:od.map,merge:ii.merge,null:$g.nullTag,omap:ld.omap,pairs:ud.pairs,seq:sd.seq,set:dd.set,timestamp:Jn.timestamp},Fg={"tag:yaml.org,2002:binary":cd.binary,"tag:yaml.org,2002:merge":ii.merge,"tag:yaml.org,2002:omap":ld.omap,"tag:yaml.org,2002:pairs":ud.pairs,"tag:yaml.org,2002:set":dd.set,"tag:yaml.org,2002:timestamp":Jn.timestamp};function Lg(e,t,r){let i=nd.get(t);if(i&&!e)return r&&!i.includes(ii.merge)?i.concat(ii.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(nd.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 r&&(n=n.concat(ii.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?ad[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(ad).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}ms.coreKnownTags=Fg;ms.getTags=Lg});var ws=k(pd=>{"use strict";var vs=_(),Bg=cr(),Vg=lr(),Mg=Qr(),Gn=fd(),Wg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,gs=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Gn.getTags(t,"compat"):t?Gn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Gn.coreKnownTags:{},this.tags=Gn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,vs.MAP,{value:Bg.map}),Object.defineProperty(this,vs.SCALAR,{value:Mg.string}),Object.defineProperty(this,vs.SEQ,{value:Vg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Wg:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};pd.Schema=gs});var md=k(hd=>{"use strict";var zg=_(),ys=Kr(),ni=zr();function Jg(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=ys.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ni.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(zg.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);r.push(ni.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ys.stringify(e.contents,n,()=>s=null,c);s&&(l+=ni.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(ys.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
57
+ ${a.comment}`:i.comment}i=n}e.items[r]=Hn.isPair(i)?i:new es.Pair(i)}}else t("Expected a sequence for this tag");return e}function Bu(e,t,r){let{replacer:i}=r,n=new cg.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 i=="function"&&(o=i.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(es.createPair(s,c,r))}return n}var lg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Lu,createNode:Bu};Dn.createPairs=Bu;Dn.pairs=lg;Dn.resolvePairs=Lu});var is=k(rs=>{"use strict";var Vu=_(),ts=st(),ei=pt(),ug=ht(),Mu=qn(),Ft=class e extends ug.YAMLSeq{constructor(){super(),this.add=ei.YAMLMap.prototype.add.bind(this),this.delete=ei.YAMLMap.prototype.delete.bind(this),this.get=ei.YAMLMap.prototype.get.bind(this),this.has=ei.YAMLMap.prototype.has.bind(this),this.set=ei.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Vu.isPair(n)?(a=ts.toJS(n.key,"",r),o=ts.toJS(n.value,a,r)):a=ts.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Mu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Ft.tag="tag:yaml.org,2002:omap";var dg={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ft,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Mu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Vu.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Ft,r)},createNode:(e,t,r)=>Ft.from(e,t,r)};rs.YAMLOMap=Ft;rs.omap=dg});var Uu=k(ns=>{"use strict";var Wu=B();function zu({value:e,source:t},r){return t&&(e?Ju:Gu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Ju={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 Wu.Scalar(!0),stringify:zu},Gu={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 Wu.Scalar(!1),stringify:zu};ns.falseTag=Gu;ns.trueTag=Ju});var Ku=k(Fn=>{"use strict";var fg=B(),as=ur(),pg={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:as.stringifyNumber},hg={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():as.stringifyNumber(e)}},mg={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 fg.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:as.stringifyNumber};Fn.float=mg;Fn.floatExp=hg;Fn.floatNaN=pg});var Xu=k(ri=>{"use strict";var Yu=ur(),ti=e=>typeof e=="bigint"||Number.isInteger(e);function Ln(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){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,r);return n==="-"?-1*a:a}function os(e,t,r){let{value:i}=e;if(ti(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Yu.stringifyNumber(e)}var vg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Ln(e,2,2,r),stringify:e=>os(e,2,"0b")},gg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Ln(e,1,8,r),stringify:e=>os(e,8,"0")},wg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Ln(e,0,10,r),stringify:Yu.stringifyNumber},yg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Ln(e,2,16,r),stringify:e=>os(e,16,"0x")};ri.int=wg;ri.intBin=vg;ri.intHex=yg;ri.intOct=gg});var cs=k(ss=>{"use strict";var Mn=_(),Bn=dt(),Vn=pt(),Lt=class e extends Vn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Mn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Bn.Pair(t.key,null):r=new Bn.Pair(t,null),Vn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Vn.findPair(this.items,t);return!r&&Mn.isPair(i)?Mn.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Vn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Bn.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Bn.createPair(o,null,i));return a}};Lt.tag="tag:yaml.org,2002:set";var Ng={collection:"map",identify:e=>e instanceof Set,nodeClass:Lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Lt.from(e,t,r),resolve(e,t){if(Mn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Lt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ss.YAMLSet=Lt;ss.set=Ng});var us=k(Wn=>{"use strict";var bg=ur();function ls(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function Qu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return bg.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(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))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var kg={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:r})=>ls(e,r),stringify:Qu},Sg={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=>ls(e,!1),stringify:Qu},Zu={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(Zu.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),d=t[8];if(d&&d!=="Z"){let u=ls(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Wn.floatTime=Sg;Wn.intTime=kg;Wn.timestamp=Zu});var rd=k(td=>{"use strict";var Eg=cr(),xg=In(),Cg=lr(),Pg=Qr(),Rg=Zo(),ed=Uu(),ds=Ku(),zn=Xu(),_g=Sn(),Ag=is(),Ig=qn(),jg=cs(),fs=us(),Tg=[Eg.map,Cg.seq,Pg.string,xg.nullTag,ed.trueTag,ed.falseTag,zn.intBin,zn.intOct,zn.int,zn.intHex,ds.floatNaN,ds.floatExp,ds.float,Rg.binary,_g.merge,Ag.omap,Ig.pairs,jg.set,fs.intTime,fs.floatTime,fs.timestamp];td.schema=Tg});var fd=k(ms=>{"use strict";var od=cr(),$g=In(),sd=lr(),Og=Qr(),Hg=zo(),ps=Go(),hs=Ko(),Dg=Ou(),qg=qu(),cd=Zo(),ii=Sn(),ld=is(),ud=qn(),id=rd(),dd=cs(),Jn=us(),nd=new Map([["core",Dg.schema],["failsafe",[od.map,sd.seq,Og.string]],["json",qg.schema],["yaml11",id.schema],["yaml-1.1",id.schema]]),ad={binary:cd.binary,bool:Hg.boolTag,float:ps.float,floatExp:ps.floatExp,floatNaN:ps.floatNaN,floatTime:Jn.floatTime,int:hs.int,intHex:hs.intHex,intOct:hs.intOct,intTime:Jn.intTime,map:od.map,merge:ii.merge,null:$g.nullTag,omap:ld.omap,pairs:ud.pairs,seq:sd.seq,set:dd.set,timestamp:Jn.timestamp},Fg={"tag:yaml.org,2002:binary":cd.binary,"tag:yaml.org,2002:merge":ii.merge,"tag:yaml.org,2002:omap":ld.omap,"tag:yaml.org,2002:pairs":ud.pairs,"tag:yaml.org,2002:set":dd.set,"tag:yaml.org,2002:timestamp":Jn.timestamp};function Lg(e,t,r){let i=nd.get(t);if(i&&!e)return r&&!i.includes(ii.merge)?i.concat(ii.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(nd.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 r&&(n=n.concat(ii.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?ad[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(ad).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}ms.coreKnownTags=Fg;ms.getTags=Lg});var ws=k(pd=>{"use strict";var vs=_(),Bg=cr(),Vg=lr(),Mg=Qr(),Gn=fd(),Wg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,gs=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Gn.getTags(t,"compat"):t?Gn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Gn.coreKnownTags:{},this.tags=Gn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,vs.MAP,{value:Bg.map}),Object.defineProperty(this,vs.SCALAR,{value:Mg.string}),Object.defineProperty(this,vs.SEQ,{value:Vg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Wg:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};pd.Schema=gs});var md=k(hd=>{"use strict";var zg=_(),ys=Kr(),ni=zr();function Jg(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=ys.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ni.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(zg.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);r.push(ni.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ys.stringify(e.contents,n,()=>s=null,c);s&&(l+=ni.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(ys.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
58
  `)?(r.push("..."),r.push(ni.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(ni.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
60
  `}hd.stringifyDocument=Jg});var ai=k(vd=>{"use strict";var Gg=Mr(),dr=pn(),he=_(),Ug=dt(),Kg=st(),Yg=ws(),Xg=md(),Ns=ln(),Qg=Eo(),Zg=Wr(),bs=So(),ks=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,he.NODE_TYPE,{value:he.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new bs.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[he.NODE_TYPE]:{value:he.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=he.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){fr(this.contents)&&this.contents.add(t)}addIn(t,r){fr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Ns.anchorNames(this);t.anchor=!r||i.has(r)?Ns.findNewAnchor(r||"a",i):r}return new Gg.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let g=b=>typeof b=="number"||b instanceof String||b instanceof Number,v=r.filter(g).map(String);v.length>0&&(r=r.concat(v)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:d}=i??{},{onAnchor:u,setAnchors:f,sourceObjects:h}=Ns.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=Zg.createNode(t,d,m);return s&&he.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Ug.Pair(n,a)}delete(t){return fr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return dr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):fr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return he.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return dr.isEmptyPath(t)?!r&&he.isScalar(this.contents)?this.contents.value:this.contents:he.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return he.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return dr.isEmptyPath(t)?this.contents!==void 0:he.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=dr.collectionFromPath(this.schema,[t],r):fr(this.contents)&&this.contents.set(t,r)}setIn(t,r){dr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=dr.collectionFromPath(this.schema,Array.from(t),r):fr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new bs.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new bs.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=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(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Yg.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Kg.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?Qg.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}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 r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Xg.stringifyDocument(this,t)}};function fr(e){if(he.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}vd.Document=ks});var ci=k(si=>{"use strict";var oi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Ss=class extends oi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Es=class extends oi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},ew=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).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)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
@@ -62,14 +62,14 @@ ${a.comment}`:i.comment}i=n}e.items[r]=Hn.isPair(i)?i:new es.Pair(i)}}else t("Ex
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};si.YAMLError=oi;si.YAMLParseError=Ss;si.YAMLWarning=Es;si.prettifyError=ew});var li=k(gd=>{"use strict";function tw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,u="",f="",h=!1,m=!1,p=null,g=null,v=null,b=null,N=null,y=null,E=null;for(let S of e)switch(m&&(S.type!=="space"&&S.type!=="newline"&&S.type!=="comma"&&a(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),p&&(l&&S.type!=="comment"&&S.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),S.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&S.source.includes(" ")&&(p=S),d=!0;break;case"comment":{d||a(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=S.source.substring(1)||" ";u?u+=f+I:u=I,f="",l=!1;break}case"newline":l?u?u+=S.source:(!y||r!=="seq-item-ind")&&(c=!0):f+=S.source,l=!0,h=!0,(g||v)&&(b=S),d=!0;break;case"anchor":g&&a(S,"MULTIPLE_ANCHORS","A node can have at most one anchor"),S.source.endsWith(":")&&a(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=S,E??(E=S.offset),l=!1,d=!1,m=!0;break;case"tag":{v&&a(S,"MULTIPLE_TAGS","A node can have at most one tag"),v=S,E??(E=S.offset),l=!1,d=!1,m=!0;break}case r:(g||v)&&a(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`),y&&a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${t??"collection"}`),y=S,l=r==="seq-item-ind"||r==="explicit-key-ind",d=!1;break;case"comma":if(t){N&&a(S,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=S,l=!1,d=!1;break}default:a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),l=!1,d=!1}let w=e[e.length-1],R=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:y,spaceBefore:c,comment:u,hasNewline:h,anchor:g,tag:v,newlineAfterProp:b,end:R,start:E??R}}gd.resolveProps=tw});var Un=k(wd=>{"use strict";function Cs(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 r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(Cs(t.key)||Cs(t.value))return!0}return!1;default:return!0}}wd.containsNewline=Cs});var xs=k(yd=>{"use strict";var rw=Un();function iw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&rw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}yd.flowIndentCheck=iw});var Ps=k(bd=>{"use strict";var Nd=_();function nw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Nd.isScalar(a)&&Nd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}bd.mapIncludes=nw});var Pd=k(xd=>{"use strict";var kd=dt(),aw=pt(),Sd=li(),ow=Un(),Ed=xs(),sw=Ps(),Cd="All mapping items must start at the same column";function cw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??aw.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let d of i.items){let{start:u,key:f,sep:h,value:m}=d,p=Sd.resolveProps(u,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),g=!p.found;if(g){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!==i.indent&&n(c,"BAD_INDENT",Cd)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
67
- `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||ow.containsNewline(f))&&n(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&n(c,"BAD_INDENT",Cd);r.atKey=!0;let v=p.end,b=f?e(r,f,p,n):t(r,v,u,null,p,n);r.schema.compat&&Ed.flowIndentCheck(i.indent,f,n),r.atKey=!1,sw.mapIncludes(r,s.items,b)&&n(v,"DUPLICATE_KEY","Map keys must be unique");let N=Sd.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=N.end,N.found){g&&(m?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<N.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let y=m?e(r,m,N,n):t(r,c,h,null,N,n);r.schema.compat&&Ed.flowIndentCheck(i.indent,m,n),c=y.range[2];let E=new kd.Pair(b,y);r.options.keepSourceTokens&&(E.srcToken=d),s.items.push(E)}else{g&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(b.comment?b.comment+=`
68
- `+N.comment:b.comment=N.comment);let y=new kd.Pair(b);r.options.keepSourceTokens&&(y.srcToken=d),s.items.push(y)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}xd.resolveBlockMap=cw});var _d=k(Rd=>{"use strict";var lw=ht(),uw=li(),dw=xs();function fw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??lw.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:d,value:u}of i.items){let f=uw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.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=u?e(r,u,f,n):t(r,f.end,d,null,f,n);r.schema.compat&&dw.flowIndentCheck(i.indent,u,n),c=h.range[2],s.items.push(h)}return s.range=[i.offset,c,l??c],s}Rd.resolveBlockSeq=fw});var pr=k(Ad=>{"use strict";function pw(e,t,r,i){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":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";n?n+=o+d:n=d,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Ad.resolveEnd=pw});var $d=k(Td=>{"use strict";var hw=_(),mw=dt(),Id=pt(),vw=ht(),gw=pr(),jd=li(),ww=Un(),yw=Ps(),Rs="Block collections are not allowed within flow collections",_s=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Nw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Id.YAMLMap:vw.YAMLSeq),l=new c(r.schema);l.flow=!0;let d=r.atRoot;d&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let g=0;g<i.items.length;++g){let v=i.items[g],{start:b,key:N,sep:y,value:E}=v,w=jd.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:N??y?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!y&&!E){g===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(l.comment?l.comment+=`
65
+ `}};si.YAMLError=oi;si.YAMLParseError=Ss;si.YAMLWarning=Es;si.prettifyError=ew});var li=k(gd=>{"use strict";function tw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,u="",f="",h=!1,m=!1,p=null,g=null,v=null,b=null,N=null,y=null,E=null;for(let S of e)switch(m&&(S.type!=="space"&&S.type!=="newline"&&S.type!=="comma"&&a(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),p&&(l&&S.type!=="comment"&&S.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),S.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&S.source.includes(" ")&&(p=S),d=!0;break;case"comment":{d||a(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=S.source.substring(1)||" ";u?u+=f+I:u=I,f="",l=!1;break}case"newline":l?u?u+=S.source:(!y||r!=="seq-item-ind")&&(c=!0):f+=S.source,l=!0,h=!0,(g||v)&&(b=S),d=!0;break;case"anchor":g&&a(S,"MULTIPLE_ANCHORS","A node can have at most one anchor"),S.source.endsWith(":")&&a(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=S,E??(E=S.offset),l=!1,d=!1,m=!0;break;case"tag":{v&&a(S,"MULTIPLE_TAGS","A node can have at most one tag"),v=S,E??(E=S.offset),l=!1,d=!1,m=!0;break}case r:(g||v)&&a(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`),y&&a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${t??"collection"}`),y=S,l=r==="seq-item-ind"||r==="explicit-key-ind",d=!1;break;case"comma":if(t){N&&a(S,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=S,l=!1,d=!1;break}default:a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),l=!1,d=!1}let w=e[e.length-1],R=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:y,spaceBefore:c,comment:u,hasNewline:h,anchor:g,tag:v,newlineAfterProp:b,end:R,start:E??R}}gd.resolveProps=tw});var Un=k(wd=>{"use strict";function xs(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 r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(xs(t.key)||xs(t.value))return!0}return!1;default:return!0}}wd.containsNewline=xs});var Cs=k(yd=>{"use strict";var rw=Un();function iw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&rw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}yd.flowIndentCheck=iw});var Ps=k(bd=>{"use strict";var Nd=_();function nw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Nd.isScalar(a)&&Nd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}bd.mapIncludes=nw});var Pd=k(Cd=>{"use strict";var kd=dt(),aw=pt(),Sd=li(),ow=Un(),Ed=Cs(),sw=Ps(),xd="All mapping items must start at the same column";function cw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??aw.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let d of i.items){let{start:u,key:f,sep:h,value:m}=d,p=Sd.resolveProps(u,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),g=!p.found;if(g){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!==i.indent&&n(c,"BAD_INDENT",xd)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
67
+ `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||ow.containsNewline(f))&&n(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&n(c,"BAD_INDENT",xd);r.atKey=!0;let v=p.end,b=f?e(r,f,p,n):t(r,v,u,null,p,n);r.schema.compat&&Ed.flowIndentCheck(i.indent,f,n),r.atKey=!1,sw.mapIncludes(r,s.items,b)&&n(v,"DUPLICATE_KEY","Map keys must be unique");let N=Sd.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=N.end,N.found){g&&(m?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<N.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let y=m?e(r,m,N,n):t(r,c,h,null,N,n);r.schema.compat&&Ed.flowIndentCheck(i.indent,m,n),c=y.range[2];let E=new kd.Pair(b,y);r.options.keepSourceTokens&&(E.srcToken=d),s.items.push(E)}else{g&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(b.comment?b.comment+=`
68
+ `+N.comment:b.comment=N.comment);let y=new kd.Pair(b);r.options.keepSourceTokens&&(y.srcToken=d),s.items.push(y)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Cd.resolveBlockMap=cw});var _d=k(Rd=>{"use strict";var lw=ht(),uw=li(),dw=Cs();function fw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??lw.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:d,value:u}of i.items){let f=uw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.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=u?e(r,u,f,n):t(r,f.end,d,null,f,n);r.schema.compat&&dw.flowIndentCheck(i.indent,u,n),c=h.range[2],s.items.push(h)}return s.range=[i.offset,c,l??c],s}Rd.resolveBlockSeq=fw});var pr=k(Ad=>{"use strict";function pw(e,t,r,i){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":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";n?n+=o+d:n=d,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Ad.resolveEnd=pw});var $d=k(Td=>{"use strict";var hw=_(),mw=dt(),Id=pt(),vw=ht(),gw=pr(),jd=li(),ww=Un(),yw=Ps(),Rs="Block collections are not allowed within flow collections",_s=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Nw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Id.YAMLMap:vw.YAMLSeq),l=new c(r.schema);l.flow=!0;let d=r.atRoot;d&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let g=0;g<i.items.length;++g){let v=i.items[g],{start:b,key:N,sep:y,value:E}=v,w=jd.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:N??y?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!y&&!E){g===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(l.comment?l.comment+=`
69
69
  `+w.comment:l.comment=w.comment),u=w.end;continue}!o&&r.options.strict&&ww.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)w.comma&&n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(w.comma||n(w.start,"MISSING_CHAR",`Missing , between ${s} items`),w.comment){let R="";e:for(let S of b)switch(S.type){case"comma":case"space":break;case"comment":R=S.source.substring(1);break e;default:break e}if(R){let S=l.items[l.items.length-1];hw.isPair(S)&&(S=S.value??S.key),S.comment?S.comment+=`
70
70
  `+R:S.comment=R,w.comment=w.comment.substring(R.length+1)}}if(!o&&!y&&!w.found){let R=E?e(r,E,w,n):t(r,w.end,y,null,w,n);l.items.push(R),u=R.range[2],_s(E)&&n(R.range,"BLOCK_IN_FLOW",Rs)}else{r.atKey=!0;let R=w.end,S=N?e(r,N,w,n):t(r,R,b,null,w,n);_s(N)&&n(S.range,"BLOCK_IN_FLOW",Rs),r.atKey=!1;let I=jd.resolveProps(y??[],{flow:s,indicator:"map-value-ind",next:E,offset:S.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(I.found){if(!o&&!w.found&&r.options.strict){if(y)for(let F of y){if(F===I.found)break;if(F.type==="newline"){n(F,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<I.found.offset-1024&&n(I.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(I.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let K=E?e(r,E,I,n):I.found?t(r,I.end,y,null,I,n):null;K?_s(E)&&n(K.range,"BLOCK_IN_FLOW",Rs):I.comment&&(S.comment?S.comment+=`
71
71
  `+I.comment:S.comment=I.comment);let Ne=new mw.Pair(S,K);if(r.options.keepSourceTokens&&(Ne.srcToken=v),o){let F=l;yw.mapIncludes(r,F.items,S)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),F.items.push(Ne)}else{let F=new Id.YAMLMap(r.schema);F.flow=!0,F.items.push(Ne);let qr=(K??S).range;F.range=[S.range[0],qr[1],qr[2]],l.items.push(F)}u=K?K.range[2]:I.end}}let f=o?"}":"]",[h,...m]=i.end,p=u;if(h?.source===f)p=h.offset+h.source.length;else{let g=s[0].toUpperCase()+s.substring(1),v=d?`${g} must end with a ${f}`:`${g} in block collection must be sufficiently indented and end with a ${f}`;n(u,d?"MISSING_CHAR":"BAD_INDENT",v),h&&h.source.length!==1&&m.unshift(h)}if(m.length>0){let g=gw.resolveEnd(m,p,r.options.strict,n);g.comment&&(l.comment?l.comment+=`
72
- `+g.comment:l.comment=g.comment),l.range=[i.offset,p,g.offset]}else l.range=[i.offset,p,p];return l}Td.resolveFlowCollection=Nw});var Hd=k(Od=>{"use strict";var bw=_(),kw=B(),Sw=pt(),Ew=ht(),Cw=Pd(),xw=_d(),Pw=$d();function As(e,t,r,i,n,a){let o=r.type==="block-map"?Cw.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?xw.resolveBlockSeq(e,t,r,i,a):Pw.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Rw(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=i,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!h||h.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Sw.YAMLMap.tagName&&s==="map"||o===Ew.YAMLSeq.tagName&&s==="seq")return As(e,t,r,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),As(e,t,r,n,o)}let l=As(e,t,r,n,o,c),d=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,u=bw.isNode(d)?d:new kw.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Od.composeCollection=Rw});var js=k(Dd=>{"use strict";var Is=B();function _w(e,t,r){let i=t.offset,n=Aw(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Is.Scalar.BLOCK_FOLDED:Is.Scalar.BLOCK_LITERAL,o=t.source?Iw(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let g=o[p][1];if(g===""||g==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
72
+ `+g.comment:l.comment=g.comment),l.range=[i.offset,p,g.offset]}else l.range=[i.offset,p,p];return l}Td.resolveFlowCollection=Nw});var Hd=k(Od=>{"use strict";var bw=_(),kw=B(),Sw=pt(),Ew=ht(),xw=Pd(),Cw=_d(),Pw=$d();function As(e,t,r,i,n,a){let o=r.type==="block-map"?xw.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Cw.resolveBlockSeq(e,t,r,i,a):Pw.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Rw(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=i,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!h||h.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Sw.YAMLMap.tagName&&s==="map"||o===Ew.YAMLSeq.tagName&&s==="seq")return As(e,t,r,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),As(e,t,r,n,o)}let l=As(e,t,r,n,o,c),d=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,u=bw.isNode(d)?d:new kw.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Od.composeCollection=Rw});var js=k(Dd=>{"use strict";var Is=B();function _w(e,t,r){let i=t.offset,n=Aw(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Is.Scalar.BLOCK_FOLDED:Is.Scalar.BLOCK_LITERAL,o=t.source?Iw(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let g=o[p][1];if(g===""||g==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",g=i+n.length;return t.source&&(g+=t.source.length),{value:p,type:a,comment:n.comment,range:[i,g,g]}}let c=t.indent+n.indent,l=t.offset+n.length,d=0;for(let p=0;p<s;++p){let[g,v]=o[p];if(v===""||v==="\r")n.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&r(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=g.length),d=p,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+v.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let u="",f="",h=!1;for(let p=0;p<d;++p)u+=o[p][0].slice(c)+`
74
74
  `;for(let p=d;p<s;++p){let[g,v]=o[p];l+=g.length+v.length+1;let b=v[v.length-1]==="\r";if(b&&(v=v.slice(0,-1)),v&&g.length<c){let y=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-v.length-(b?2:1),"BAD_INDENT",y),g=""}a===Is.Scalar.BLOCK_LITERAL?(u+=f+g.slice(c)+v,f=`
75
75
  `):g.length>c||v[0]===" "?(f===" "?f=`
@@ -135,40 +135,40 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
135
135
  `,a=this.buffer[i+1]):r=i),a==="#"||t&&Zn.has(a))break;if(n===`
136
136
  `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Zn.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield fi.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(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(Js),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ke(i)||r&&Zn.has(i)){r?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,r=this.buffer[t];for(;!ke(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(Sy.has(r))r=this.buffer[++t];else if(r==="%"&&uf.has(this.buffer[t+1])&&uf.has(this.buffer[t+2]))r=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 r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};df.Lexer=Gs});var Ys=k(ff=>{"use strict";var Ks=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};ff.LineCounter=Ks});var Qs=k(gf=>{"use strict";var Cy=nn("process"),pf=Qn(),xy=Us();function mt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function hf(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 vf(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 ea(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 hr(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 ta(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function mf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!mt(t.start,"explicit-key-ind")&&!mt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,vf(t.value)?t.value.end?ta(t.value.end,t.sep):t.value.end=t.sep:ta(t.start,t.sep),delete t.sep)}var Xs=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 xy.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,Cy.env.LOG_TOKENS&&console.log("|",pf.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=pf.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){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 i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,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 r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&mf(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&hf(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.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":{hf(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 r=this.startBlockValue(t);r?this.stack.push(r):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 r=ea(this.peek(2)),i=hr(r),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:i,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 r=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};df.Lexer=Gs});var Ys=k(ff=>{"use strict";var Ks=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};ff.LineCounter=Ks});var Qs=k(gf=>{"use strict";var xy=nn("process"),pf=Qn(),Cy=Us();function mt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function hf(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 vf(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 ea(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 hr(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 ta(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function mf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!mt(t.start,"explicit-key-ind")&&!mt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,vf(t.value)?t.value.end?ta(t.value.end,t.sep):t.value.end=t.sep:ta(t.start,t.sep),delete t.sep)}var Xs=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 Cy.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,xy.env.LOG_TOKENS&&console.log("|",pf.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=pf.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){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 i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,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 r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&mf(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&hf(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.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":{hf(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 r=this.startBlockValue(t);r?this.stack.push(r):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 r=ea(this.peek(2)),i=hr(r),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:i,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 r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
140
  `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){ta(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.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=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.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(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(mt(r.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(vf(r.key)&&!mt(r.sep,"newline")){let o=hr(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(mt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=hr(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):mt(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{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||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!mt(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){ta(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||mt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=ea(i),a=hr(n);mf(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 r=this.source.indexOf(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,r)+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 r=ea(t),i=hr(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=ea(t),i=hr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};gf.Parser=Xs});var kf=k(hi=>{"use strict";var wf=qs(),Py=ai(),pi=ci(),Ry=Ho(),_y=_(),Ay=Ys(),yf=Qs();function Nf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ay.LineCounter||null,prettyErrors:t}}function Iy(e,t={}){let{lineCounter:r,prettyErrors:i}=Nf(t),n=new yf.Parser(r?.addNewLine),a=new wf.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(pi.prettifyError(e,r)),s.warnings.forEach(pi.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function bf(e,t={}){let{lineCounter:r,prettyErrors:i}=Nf(t),n=new yf.Parser(r?.addNewLine),a=new wf.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 pi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(pi.prettifyError(e,r)),o.warnings.forEach(pi.prettifyError(e,r))),o}function jy(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=bf(e,r);if(!n)return null;if(n.warnings.forEach(a=>Ry.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:i},r))}function Ty(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return _y.isDocument(e)&&!i?e.toString(r):new Py.Document(e,i,r).toString(r)}hi.parse=jy;hi.parseAllDocuments=Iy;hi.parseDocument=bf;hi.stringify=Ty});var De=k(j=>{"use strict";var $y=qs(),Oy=ai(),Hy=ws(),Zs=ci(),Dy=Mr(),vt=_(),qy=dt(),Fy=B(),Ly=pt(),By=ht(),Vy=Qn(),My=Us(),Wy=Ys(),zy=Qs(),ra=kf(),Sf=Fr();j.Composer=$y.Composer;j.Document=Oy.Document;j.Schema=Hy.Schema;j.YAMLError=Zs.YAMLError;j.YAMLParseError=Zs.YAMLParseError;j.YAMLWarning=Zs.YAMLWarning;j.Alias=Dy.Alias;j.isAlias=vt.isAlias;j.isCollection=vt.isCollection;j.isDocument=vt.isDocument;j.isMap=vt.isMap;j.isNode=vt.isNode;j.isPair=vt.isPair;j.isScalar=vt.isScalar;j.isSeq=vt.isSeq;j.Pair=qy.Pair;j.Scalar=Fy.Scalar;j.YAMLMap=Ly.YAMLMap;j.YAMLSeq=By.YAMLSeq;j.CST=Vy;j.Lexer=My.Lexer;j.LineCounter=Wy.LineCounter;j.Parser=zy.Parser;j.parse=ra.parse;j.parseAllDocuments=ra.parseAllDocuments;j.parseDocument=ra.parseDocument;j.stringify=ra.stringify;j.visit=Sf.visit;j.visitAsync=Sf.visitAsync});function Yy(e){return e.toLowerCase().startsWith(".env")}function vi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Yy(i))?"environment-file":r.some(i=>Ky.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Uy.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Uy,Ky,gi=C(()=>{"use strict";Uy=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Ky=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function yt(e){return e!==0&&e!==0n&&e!=="0"}function Ye(e,t){return yt(e.dev)&&yt(t.dev)&&yt(e.ino)&&yt(t.ino)}function O(e,t){let r=yt(e.dev)&&yt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=yt(e.ino)&&yt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var wi=C(()=>{"use strict"});var qe=C(()=>{"use strict";wi()});import{createHash as Xy}from"node:crypto";import{promises as Se}from"node:fs";import me from"node:path";import{TextDecoder as Qy}from"node:util";function tc(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function Zy(e){let t=me.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})||me.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 r=e.toLowerCase(),i=vi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function eN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function tN(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function na(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ye(r,i)?O(r,i):O(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Cf(e){let t=await Se.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Se.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function rN(e,t){let r=me.resolve(e),i=me.resolve(t);if(!tc(r,i))throw new Error("Native artifact path is outside its root");let n=[await Cf(r)],a=r;for(let o of me.relative(r,i).split(me.sep).filter(Boolean)){a=me.join(a,o);let s=await Cf(a);if(!tc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function xf(e){for(let t of e){let r=await Se.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tN(t,r)||await Se.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function H(e){let t=Zy(e.ref),r=e.maxBytes===null?null:eN(e.maxBytes??Pf),i=me.resolve(e.root,...t.split("/")),n=await rN(e.root,me.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Se.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Se.realpath(i);if(!tc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Se.open(i,"r");try{let[c,l,d]=await Promise.all([s.stat(),Se.lstat(i),Se.realpath(i)]);if(await xf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!na(a,c)||!na(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?h.length:r+1-f,y=await s.read(h,0,Math.min(h.length,N),null);if(y.bytesRead===0)break;if(f+=y.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(h.subarray(0,y.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,g]=await Promise.all([s.stat(),Se.lstat(i),Se.realpath(i)]);if(await xf(n),!p.isFile()||p.isSymbolicLink()||g!==o||!na(c,m)||!na(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(u,f),b;try{b=new Qy("utf-8",{fatal:!0}).decode(v)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:e.includeHash===!1?null:Xy("sha256").update(v).digest("hex"),text:b}}finally{await s.close()}}var Pf,oe=C(()=>{"use strict";gi();qe();Pf=1024*1024});import{promises as ic}from"node:fs";async function nc(e,t){let r;for(let i=0;i<=rc.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===rc.length||!iN.has(a??""))throw n;await new Promise(o=>setTimeout(o,rc[i]))}throw r}async function ac(e,t){await nc(()=>ic.rename(e,t),`rename ${t}`)}async function oc(e){await nc(()=>ic.unlink(e),`unlink ${e}`)}async function sc(e,t){await nc(()=>ic.link(e,t),`link ${t}`)}var iN,rc,cc=C(()=>{"use strict";iN=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),rc=[50,100,200]});import{randomUUID as nN}from"crypto";import{promises as Q}from"fs";import Ee from"path";function aa(e,t){let r=Ee.relative(e,t);return r===""||!Ee.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ee.sep}`)}function aN(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function oa(e,t){return O({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function oN(e,t){return oa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Rf(e){let t=await Q.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Q.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function vr(e){for(let t of e){let r=await Q.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!aN(t,r)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function sN(e,t,r){let[i,n]=await Promise.all([Q.lstat(e),Q.realpath(e),r?vr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!oa(i,t)||r&&!aa(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function cN(e,t){let r=Ee.resolve(e),i=Ee.resolve(t);if(!aa(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Rf(r)],a=Ee.relative(r,i).split(Ee.sep).filter(Boolean),o=r;for(let s of a){await vr(n),o=Ee.join(o,s);try{await Q.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Rf(o);if(!aa(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await vr(n),n}async function lN(e){let t;try{t=await Q.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function uN(e,t,r={}){let i=Ee.dirname(e),n=r.containedRoot?await cN(r.containedRoot,i):null;n||await Q.mkdir(i,{recursive:!0});let a=Ee.join(i,`.${Ee.basename(e)}.${nN()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Q.open(a,"wx"),s=await o.stat(),n){let[l,d]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await vr(n),!l.isFile()||l.isSymbolicLink()||!oa(s,l)||!aa(n[0].realPath,d))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!oa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await sN(a,c,n),await r.beforeCommit?.(),n){await vr(n);let l=await Q.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!oN(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await sc(a,e),await oc(a)):await ac(a,e),await lN(i)}catch(l){if(await o?.close(),!n)await Q.rm(a,{force:!0});else try{await vr(n),await Q.rm(a,{force:!0})}catch{}throw l}}async function Fe(e,t,r={}){await uN(e,t,r)}async function se(e,t,r={}){await Fe(e,JSON.stringify(t,null,2)+`
143
- `,r)}var D=C(()=>{"use strict";cc();qe()});function hN(e,t){return lc[e][t]}function sa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${hN(e,r)}
142
+ `,r)+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 r=ea(t),i=hr(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=ea(t),i=hr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};gf.Parser=Xs});var kf=k(hi=>{"use strict";var wf=qs(),Py=ai(),pi=ci(),Ry=Ho(),_y=_(),Ay=Ys(),yf=Qs();function Nf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ay.LineCounter||null,prettyErrors:t}}function Iy(e,t={}){let{lineCounter:r,prettyErrors:i}=Nf(t),n=new yf.Parser(r?.addNewLine),a=new wf.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(pi.prettifyError(e,r)),s.warnings.forEach(pi.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function bf(e,t={}){let{lineCounter:r,prettyErrors:i}=Nf(t),n=new yf.Parser(r?.addNewLine),a=new wf.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 pi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(pi.prettifyError(e,r)),o.warnings.forEach(pi.prettifyError(e,r))),o}function jy(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=bf(e,r);if(!n)return null;if(n.warnings.forEach(a=>Ry.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:i},r))}function Ty(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return _y.isDocument(e)&&!i?e.toString(r):new Py.Document(e,i,r).toString(r)}hi.parse=jy;hi.parseAllDocuments=Iy;hi.parseDocument=bf;hi.stringify=Ty});var De=k(j=>{"use strict";var $y=qs(),Oy=ai(),Hy=ws(),Zs=ci(),Dy=Mr(),vt=_(),qy=dt(),Fy=B(),Ly=pt(),By=ht(),Vy=Qn(),My=Us(),Wy=Ys(),zy=Qs(),ra=kf(),Sf=Fr();j.Composer=$y.Composer;j.Document=Oy.Document;j.Schema=Hy.Schema;j.YAMLError=Zs.YAMLError;j.YAMLParseError=Zs.YAMLParseError;j.YAMLWarning=Zs.YAMLWarning;j.Alias=Dy.Alias;j.isAlias=vt.isAlias;j.isCollection=vt.isCollection;j.isDocument=vt.isDocument;j.isMap=vt.isMap;j.isNode=vt.isNode;j.isPair=vt.isPair;j.isScalar=vt.isScalar;j.isSeq=vt.isSeq;j.Pair=qy.Pair;j.Scalar=Fy.Scalar;j.YAMLMap=Ly.YAMLMap;j.YAMLSeq=By.YAMLSeq;j.CST=Vy;j.Lexer=My.Lexer;j.LineCounter=Wy.LineCounter;j.Parser=zy.Parser;j.parse=ra.parse;j.parseAllDocuments=ra.parseAllDocuments;j.parseDocument=ra.parseDocument;j.stringify=ra.stringify;j.visit=Sf.visit;j.visitAsync=Sf.visitAsync});function Yy(e){return e.toLowerCase().startsWith(".env")}function vi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Yy(i))?"environment-file":r.some(i=>Ky.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Uy.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Uy,Ky,gi=x(()=>{"use strict";Uy=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Ky=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function yt(e){return e!==0&&e!==0n&&e!=="0"}function Ye(e,t){return yt(e.dev)&&yt(t.dev)&&yt(e.ino)&&yt(t.ino)}function O(e,t){let r=yt(e.dev)&&yt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=yt(e.ino)&&yt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var wi=x(()=>{"use strict"});var qe=x(()=>{"use strict";wi()});import{createHash as Xy}from"node:crypto";import{promises as Se}from"node:fs";import me from"node:path";import{TextDecoder as Qy}from"node:util";function tc(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function Zy(e){let t=me.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})||me.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 r=e.toLowerCase(),i=vi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function eN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function tN(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function na(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ye(r,i)?O(r,i):O(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function xf(e){let t=await Se.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Se.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function rN(e,t){let r=me.resolve(e),i=me.resolve(t);if(!tc(r,i))throw new Error("Native artifact path is outside its root");let n=[await xf(r)],a=r;for(let o of me.relative(r,i).split(me.sep).filter(Boolean)){a=me.join(a,o);let s=await xf(a);if(!tc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Cf(e){for(let t of e){let r=await Se.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tN(t,r)||await Se.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function H(e){let t=Zy(e.ref),r=e.maxBytes===null?null:eN(e.maxBytes??Pf),i=me.resolve(e.root,...t.split("/")),n=await rN(e.root,me.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Se.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Se.realpath(i);if(!tc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Se.open(i,"r");try{let[c,l,d]=await Promise.all([s.stat(),Se.lstat(i),Se.realpath(i)]);if(await Cf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!na(a,c)||!na(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?h.length:r+1-f,y=await s.read(h,0,Math.min(h.length,N),null);if(y.bytesRead===0)break;if(f+=y.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(h.subarray(0,y.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,g]=await Promise.all([s.stat(),Se.lstat(i),Se.realpath(i)]);if(await Cf(n),!p.isFile()||p.isSymbolicLink()||g!==o||!na(c,m)||!na(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(u,f),b;try{b=new Qy("utf-8",{fatal:!0}).decode(v)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:e.includeHash===!1?null:Xy("sha256").update(v).digest("hex"),text:b}}finally{await s.close()}}var Pf,oe=x(()=>{"use strict";gi();qe();Pf=1024*1024});import{promises as ic}from"node:fs";async function nc(e,t){let r;for(let i=0;i<=rc.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===rc.length||!iN.has(a??""))throw n;await new Promise(o=>setTimeout(o,rc[i]))}throw r}async function ac(e,t){await nc(()=>ic.rename(e,t),`rename ${t}`)}async function oc(e){await nc(()=>ic.unlink(e),`unlink ${e}`)}async function sc(e,t){await nc(()=>ic.link(e,t),`link ${t}`)}var iN,rc,cc=x(()=>{"use strict";iN=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),rc=[50,100,200]});import{randomUUID as nN}from"crypto";import{promises as Q}from"fs";import Ee from"path";function aa(e,t){let r=Ee.relative(e,t);return r===""||!Ee.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ee.sep}`)}function aN(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function oa(e,t){return O({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function oN(e,t){return oa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Rf(e){let t=await Q.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Q.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function vr(e){for(let t of e){let r=await Q.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!aN(t,r)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function sN(e,t,r){let[i,n]=await Promise.all([Q.lstat(e),Q.realpath(e),r?vr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!oa(i,t)||r&&!aa(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function cN(e,t){let r=Ee.resolve(e),i=Ee.resolve(t);if(!aa(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Rf(r)],a=Ee.relative(r,i).split(Ee.sep).filter(Boolean),o=r;for(let s of a){await vr(n),o=Ee.join(o,s);try{await Q.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Rf(o);if(!aa(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await vr(n),n}async function lN(e){let t;try{t=await Q.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function uN(e,t,r={}){let i=Ee.dirname(e),n=r.containedRoot?await cN(r.containedRoot,i):null;n||await Q.mkdir(i,{recursive:!0});let a=Ee.join(i,`.${Ee.basename(e)}.${nN()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Q.open(a,"wx"),s=await o.stat(),n){let[l,d]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await vr(n),!l.isFile()||l.isSymbolicLink()||!oa(s,l)||!aa(n[0].realPath,d))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!oa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await sN(a,c,n),await r.beforeCommit?.(),n){await vr(n);let l=await Q.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!oN(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await sc(a,e),await oc(a)):await ac(a,e),await lN(i)}catch(l){if(await o?.close(),!n)await Q.rm(a,{force:!0});else try{await vr(n),await Q.rm(a,{force:!0})}catch{}throw l}}async function Fe(e,t,r={}){await uN(e,t,r)}async function se(e,t,r={}){await Fe(e,JSON.stringify(t,null,2)+`
143
+ `,r)}var D=x(()=>{"use strict";cc();qe()});function hN(e,t){return lc[e][t]}function sa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${hN(e,r)}
144
144
  `).join(`
145
- `)}var lc,dN,fN,pN,_f,Mt=C(()=>{"use strict";lc={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},dN={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},fN={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},pN=new Map,_f=new Map;for(let e of Object.keys(lc)){for(let[t,r]of Object.entries(lc[e]))pN.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(dN[e]))_f.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(fN[e]))_f.set(r.toLocaleLowerCase("en-US"),t)}});import Nt from"path";function yN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Nt.posix.isAbsolute(r)||Nt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Wt(e){let t=yN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Df(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function da(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Nt.posix.isAbsolute(i)||Nt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.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(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function qf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function fa(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>la)throw new Error(`${t} exceeds ${la} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>ua)throw new Error(`${t} contains more than ${ua} wildcard tokens`);return e}function $f(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>fa(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function yi(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Of(e,t,r){let i=yi(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function NN(e){if(e===void 0)return{...ce,include:[...ce.include],exclude:[...ce.exclude]};let t=Xe(e,"native.snapshot");return{include:$f(t.include,"native.snapshot.include",ce.include),exclude:$f(t.exclude,"native.snapshot.exclude",ce.exclude),max_files:yi(t.max_files,ce.max_files,"native.snapshot.max_files"),max_total_bytes:yi(t.max_total_bytes,ce.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:yi(t.max_duration_ms,ce.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:yi(t.max_selection_records,ce.max_selection_records,"native.snapshot.max_selection_records")}}function bN(e){if(e===void 0)return;let t=Xe(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="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=Xe(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:r,fromArtifactRoot:Wt(i),toArtifactRoot:Wt(n),stage:a,...o?{cleanup:o}:{}}}function kN(e){if(e===void 0)return;let t=Xe(e,"native.finish");if(t.pull_request===void 0)return{};let r=Xe(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Nt.posix.isAbsolute(i[0])||Nt.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??mN;if(!Number.isSafeInteger(n)||n<1||n>Tf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Tf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function SN(e,t={}){let r=Xe(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??dc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=bN(r.pending_root_move),l=kN(r.finish);return{artifact_root:Wt(i),language:qf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:NN(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function EN(e){let t=Xe(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Df(t.artifact_layout),language:qf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function CN(e){let r=Xe(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>da(i,`hook.allow_paths[${n}]`)))]}}function xN(e){if(e===void 0)return{...ca};let t=Xe(e,"memory"),r=t.learning??ca.learning,i=t.retrieval??ca.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function fc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function PN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Nt.posix.isAbsolute(r)||Nt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Af)throw new Error(`${t} exceeds ${Af} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>If)throw new Error(`${t} contains more than ${If} wildcard tokens`);return r}function RN(e){let t=fc(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>PN(n,`knowledge.local.include[${a}]`)))],max_file_mb:Of(t.max_file_mb,jf.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Of(t.max_total_mb,jf.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function _N(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function AN(e){let t=fc(e,"knowledge.remote"),r=_N(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function IN(e){if(e===void 0)return{...Hf};let t=fc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:RN(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:AN(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function jN(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function TN(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)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 d=e.workflows??[e.default_workflow];if(!Array.isArray(d)||d.length===0||d.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(d)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function bi(e,t={}){let r=(0,uc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=jN(n.ambient_resume),o=n.hook===void 0?void 0:CN(n.hook),s=xN(n.memory),c=IN(n.knowledge),l=n.native===void 0?void 0:SN(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),d=n.classic===void 0?void 0:EN(n.classic),u=TN(n,o,s,c,l,d,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...d?{classic:d}:{}}}function pa(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ca},knowledge:{...Hf},native:{artifact_root:Wt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:dc,snapshot:{...ce,include:[...ce.include],exclude:[...ce.exclude]}}}}var uc,Ni,la,ua,Af,If,dc,ca,jf,Hf,mN,Tf,vN,gN,wN,ce,bt=C(()=>{"use strict";uc=Je(De(),1),Ni=Number.MAX_SAFE_INTEGER,la=1024,ua=64,Af=1024,If=64,dc=5,ca={learning:!0,retrieval:!0},jf={include:[],max_file_mb:1,max_total_mb:32},Hf={provider:"local"},mN=12e4,Tf=6e5,vN=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/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/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],gN=["**/.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"],wN=[...vN,...gN].sort((e,t)=>e.localeCompare(t,"en")),ce={include:["**/*"],exclude:[...wN],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as ha,promises as zt}from"fs";function pc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ff(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ki(e){return{dev:e.dev,ino:e.ino,birthtime:pc(e)}}function ma(e,t){let r=ki(e),i=ki(t);return Ye(r,i)?O(r,i):O(r,i)&&pc(e)===pc(t)&&Ff(e)===Ff(t)&&e.size===t.size}async function Si(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await zt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Le("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Le("too-large",`${i} exceeds ${t} bytes`);let o=await zt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ki(a)});let s=process.platform==="win32"?ha.O_RDONLY:ha.O_RDONLY|ha.O_NOFOLLOW|ha.O_NONBLOCK,c;try{c=await zt.open(e,s)}catch(l){throw l.code==="ELOOP"?new Le("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:n}),zt.lstat(e,{bigint:n}),zt.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!ma(a,l)||!ma(a,d))throw new Le("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:ki(l)}),await r.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-h,{bytesRead:N}=await c.read(m,0,Math.min(m.length,b),null);if(N===0)break;if(h+=N,h>t)throw new Le("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[p,g,v]=await Promise.all([c.stat({bigint:n}),zt.lstat(e,{bigint:n}),zt.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==o||!ma(a,p)||!ma(a,g))throw new Le("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:ki(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:v}}finally{await c.close()}}var Le,Ei=C(()=>{"use strict";wi();Le=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as va}from"fs";import kt from"path";function $N(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function hc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}async function Lf(e,t){let r=kt.resolve(e),i=await va.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return va.realpath(r)}async function Bf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=kt.join(n,r[a]);let o;try{o=await va.lstat(n)}catch(d){if($N(d))return{exists:!1,kind:"missing"};throw d}let s=kt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await va.realpath(n);if(!hc(t,l))throw new Error(`${i.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 gr(e,t,r){let i=da(t,r.label),n=kt.resolve(e),a=await Lf(n,r.label),o=i.split("/"),s=kt.resolve(n,...o);if(!hc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Bf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Qe(e,t,r,i){let n=await gr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Lf(n.projectRoot,i.label);return Si(n.target,r,{...i,verify:async(o,s)=>{if(!hc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Bf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var St=C(()=>{"use strict";Ei();bt()});import{createHash as ON}from"crypto";function HN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ga(e,t={}){return(await wa(e,t)).document}async function DN(e){try{return(await Qe(e,Ci,Ni,{label:Ci})).bytes}catch(t){if(HN(t))return null;throw t}}function qN(e){return e?{exists:!0,sha256:ON("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function wa(e,t={}){let r=await DN(e);return{document:r?bi(r.toString("utf8"),t):null,identity:qN(r)}}async function mc(e){return(await ga(e))?.config??null}var Ci,wr=C(()=>{"use strict";bt();St();Ci=".comet/config.yaml"});var yr=C(()=>{"use strict";cc();wi()});var BP,vc=C(()=>{"use strict";yr();wr();St();BP=16*1024});var yc=C(()=>{"use strict";yr();bt();wr();St();vc()});import{existsSync as Mf,promises as Jt}from"fs";import P from"path";import MN from"os";async function Nc(e){try{return await Jt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function zN(e){try{let t=await Jt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function br(e,t){let r=P.relative(e,t);return r===""||!P.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${P.sep}`)}async function Nr(e){let t=[],r=e;for(;!await Nc(r);){let n=P.dirname(r);if(n===r)break;t.push(P.basename(r)),r=n}let i=await Jt.realpath(r);return P.resolve(i,...t.reverse())}async function bc(e){try{return(await Jt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Na(e){let t=P.resolve(e);try{(await Jt.stat(t)).isDirectory()||(t=P.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=P.resolve(MN.homedir());for(;;){if(!(t===i&&r!==i)){let o=P.join(t,...ya.split("/")),s=t===r||await zN(o);if(await Nc(o)&&s)return t}if(await Nc(P.join(t,".git")))return t;let a=P.dirname(t);if(a===t)return r;t=a}}function ba(e){return Wt(e)}async function JN(e,t){let r=ba(t),i=P.resolve(e,...r.split("/")),n=await Jt.realpath(e),a=await Nr(i);if(!br(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Be(e,t){let r=ba(t),i=await JN(e,r),n=P.join(i,"comet");if(await bc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Nr(i),Nr(n)]);if(!br(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=P.resolve(e),c=P.join(s,".comet","runtime","native");if(await bc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([Jt.realpath(s),Nr(c)]);if(!br(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:P.join(e,...ya.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:P.join(n,"specs"),changesDir:P.join(n,"changes"),archiveDir:P.join(n,"archive"),runtimeDir:c,changesRuntimeDir:P.join(c,"changes"),locksDir:P.join(c,"locks"),transactionsDir:P.join(c,"transactions")}}function kc(e){if(!WN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){kc(t);let r=P.join(e.changesRuntimeDir,t);if(!z(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function GN(e,t){kc(t);let r=P.join(e.changesDir,t,"runtime");if(!z(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=Ve(e,t);if(Mf(r))return r;let i=GN(e,t);return Mf(i)?i:r}function Gt(e,t){kc(t);let r=P.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:P.join(r,"brief.md"),childrenPath:P.join(r,"children.yaml"),specsDir:P.join(r,"specs"),verificationPath:P.join(r,"verification.md"),statePath:P.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:P.join(i,"state.json")}}function Ce(e,t){let r=P.resolve(t);if(z(e.runtimeDir,r))return e.runtimeDir;if(z(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function z(e,t){return br(P.resolve(e),P.resolve(t))}async function L(e,t){let r=P.resolve(e),i=P.resolve(t);if(!br(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await bc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Nr(r),Nr(i)]);if(!br(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var ya,WN,A=C(()=>{"use strict";bt();ya=".comet/config.yaml",WN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function KN(e="docs",t="en"){return pa(e,t)}async function le(e){let t=(await ga(e))?.config??null;return t?.native?t:null}async function Wf(e){let t=await Na(e.startPath),r=await le(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${ya} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?ba(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??KN(i??"docs"),a=await Be(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var ka,fe=C(()=>{"use strict";bt();wr();yc();D();A();ka=fa});var cR,Sa=C(()=>{"use strict";cR=["$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 dR,Ea=C(()=>{"use strict";Sa();dR=8*1024*1024});var Ca=C(()=>{"use strict";Ea()});import{AsyncLocalStorage as ZN}from"async_hooks";var NR,bR,kR,Pi=C(()=>{"use strict";Ei();Ca();A();qe();NR=16*1024,bR=900*1e3,kR=new ZN});var Gf,Sc=C(()=>{"use strict";Gf=Je(De(),1)});var Ze,Et,Ct,Ri=C(()=>{"use strict";Ze="comet.native.v3",Et="comet.native.v2",Ct="comet.native.v1"});import eb from"node:path";function Ii(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xf(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ut(e){if(!Yf.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Qf(e){if(!Yf.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Zf(e,t){if(e.length===0||eb.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cb(e,t){let r=Ii(e,`spec_changes[${t}]`);if(Xf(r,ib,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Qf(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Zf(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Cc.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Cc.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function lb(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 xc(e,t){if(Xf(e,t,tt),typeof e.name!="string")throw new Error("Native change name is required");if(Ut(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"||!nb.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&&!ab.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 r=e.spec_changes.map(cb),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!ob.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"&&Zf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lb(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:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ji(e){let t=Ii(e,tt);if(t.schema!==Ct)throw new Error(`Expected ${Ct}`);return{schema:Ct,...xc(t,tb)}}function Ai(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ec(e,t,r){if(e===null)return null;let i=typeof e=="string"?sb.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function ub(e){if(e==null)return null;if(typeof e!="string"||!Cc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function db(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 Ti(e){let t=Ii(e,tt);if(t.schema!==Et)throw new Error(`Expected ${Et}`);if(Ai(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Et} minimum_runtime_version must be 2`);return{schema:Et,minimum_runtime_version:2,revision:Ai(t.revision,"Native v2 revision"),...xc(t,Kf)}}function kr(e){let t=Ii(e,tt);if(t.schema!==Ze){if(t.schema===Ct||t.schema===Et){let o=t.schema===Ct?ji(t):Ti(t);throw new _i(o.name,o.schema)}throw new Me(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Ai(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Me(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Ai(t.revision,"Native revision"),n=xc(t,rb),a=ub(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ze,minimum_runtime_version:3,revision:i,verification_protocol:db(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Ec(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ec(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ec(t.partial_allowance,"Native partial_allowance","allowances")}}function Pc(e){let t=Ii(e,tt);if(t.schema===Ct){let n=ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ze}`}}if(t.schema===Et){let n=Ti(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ze}`}}if(t.schema!==Ze){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 Me(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Ai(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Me(t.schema,r).message};let i=kr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Uf,tb,Kf,rb,ib,nb,ab,ob,tt,Cc,Yf,sb,_i,Me,xa=C(()=>{"use strict";Ri();Uf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],tb=new Set(Uf),Kf=new Set([...Uf,"minimum_runtime_version","revision"]),rb=new Set([...Kf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),ib=new Set(["capability","operation","source","base_hash"]),nb=new Set(["shape","build","verify","archive"]),ab=new Set(["implicit","confirmed"]),ob=new Set(["pending","pass","fail"]),tt="comet-state.yaml",Cc=/^[a-f0-9]{64}$/u,Yf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sb=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,_i=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Me=class extends Error{constructor(r,i){super(r!==Ze||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import{createHash as fb}from"crypto";function xe(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function pb(e,t){t.has(e)&&xe("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||xe("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&xe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&xe("symbol properties are not supported"),`[${e.map(i=>Rc(i,t)).join(",")}]`}finally{t.delete(e)}}function hb(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&xe("only plain objects are supported"),t.has(e)&&xe("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&xe("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&xe("accessor properties are not supported"),`${JSON.stringify(o)}:${Rc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Rc(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)||xe("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?pb(e,t):hb(e,t);case"bigint":case"function":case"symbol":case"undefined":return xe(`${typeof e} values are not supported`)}return xe("unsupported value type")}function _c(e){return Rc(e,new Set)}function T(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 fb("sha256").update(`${e}
146
- ${_c(t)}`).digest("hex")}var q=C(()=>{"use strict"});var TR,ep,$i=C(()=>{"use strict";Mt();q();TR=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ep=Object.freeze({maxCriteria:1024})});var Ac=C(()=>{"use strict";$i()});function Ic(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Sr,Pa,tp,Oi=C(()=>{"use strict";Sr="comet.native.v4",Pa="comet.native.local-execution.v4",tp=["multi-session","single-session"]});var Hc={};gm(Hc,{NativePortableStateVersionConflictError:()=>Hi,appendNativePortableHistory:()=>Di,compareAndSwapNativePortableState:()=>np,createNativePortableState:()=>ip,parseNativePortableState:()=>ue,readNativePortableState:()=>xt,writeNativePortableState:()=>Oc});import{promises as wb}from"node:fs";function Z(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ee(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function J(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Tc(e,t){return e===null?null:J(e,t)}function $c(e,t){let r=J(e,t);if(!kb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Er(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function $(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Eb(e,t){return e===null?null:$(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function We(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ia(e,t){return We(e,t,(r,i)=>J(r,`${t}[${i}]`))}function Kt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Cr(e,t){let r=J(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function _a(e,t,r=!1){let i=J(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ve(e,t){let r=Z(e,t);return ee(r,new Set(["text","truncated"]),t),{text:J(r.text,`${t}.text`,{empty:!0}),truncated:Er(r.truncated,`${t}.truncated`)}}function Cb(e,t){let r=`Native spec_changes[${t}]`,i=Z(e,r);ee(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=J(i.capability,`${r}.capability`);if(!Nb.test(n))throw new Error(`${r}.capability is invalid`);let a=V(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:_a(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:_a(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:$c(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function xb(e){let t="Native workspace",r=Z(e,t);ee(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=V(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Tc(r.change_branch,`${t}.change_branch`),a=Tc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:V(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Pb(e){let t="Native loop",r=Z(e,t);ee(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Ia(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Kt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:V(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:V(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:$(r.goal_cycle,`${t}.goal_cycle`,1),iteration:$(r.iteration,`${t}.iteration`),attempt:$(r.attempt,`${t}.attempt`),retry_epoch:$(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:$(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:$(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:$(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Tc(r.next_action,`${t}.next_action`)}}function Rb(e,t){let r=`Native acceptance[${t}]`,i=Z(e,r);ee(i,new Set(["id","source","text","result","reason"]),r);let n=J(i.id,`${r}.id`);if(!bb.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:_a(i.source,`${r}.source`),text:J(i.text,`${r}.text`),result:V(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ve(i.reason,`${r}.reason`)}}function _b(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Z(e,r);return ee(i,new Set(["name","result","note"]),r),{name:ve(i.name,`${r}.name`),result:V(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ve(i.note,`${r}.note`)}}function Ab(e){let t="Native builder_handoff",r=Z(e,t);ee(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ia(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Kt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Z(r.review,`${t}.review`);return n&&ee(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:J(r.candidate_id,`${t}.candidate_id`),identity_provider:J(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:J(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:$(r.iteration,`${t}.iteration`,1),summary:ve(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:We(r.checks,`${t}.checks`,_b),checks_truncated:Er(r.checks_truncated,`${t}.checks_truncated`),known_limits:We(r.known_limits,`${t}.known_limits`,(a,o)=>ve(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Er(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:V(n.status,["passed"],`${t}.review.status`),summary:ve(n.summary,`${t}.review.summary`),reviewer_execution_ref:J(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Cr(r.submitted_at,`${t}.submitted_at`)}}function Ib(e,t){let r=`Native blockers[${t}]`,i=Z(e,r);ee(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ia(i.acceptance_ids,`${r}.acceptance_ids`);return Kt(n,`${r}.acceptance_ids`),{owner:V(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ve(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:V(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function jb(e,t){let r=`Native verification.checks[${t}]`,i=Z(e,r);return ee(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:J(i.id,`${r}.id`),name:ve(i.name,`${r}.name`),argv_display:We(i.argv_display,`${r}.argv_display`,(n,a)=>ve(n,`${r}.argv_display[${a}]`)),argv_truncated:Er(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:_a(i.cwd_ref,`${r}.cwd_ref`,!0),status:V(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Eb(i.exit_code,`${r}.exit_code`),duration_ms:$(i.duration_ms,`${r}.duration_ms`)}}function Tb(e){let t="Native verification",r=Z(e,t);ee(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=We(r.checks,`${t}.checks`,jb);Kt(i.map(a=>a.id),`${t}.checks IDs`);let n=J(r.identity_provider,`${t}.identity_provider`);return{candidate_id:J(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:J(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:$(r.iteration,`${t}.iteration`,1),attempt:$(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ve(r.summary,`${t}.summary`),risks:We(r.risks,`${t}.risks`,(a,o)=>ve(a,`${t}.risks[${o}]`)),risks_truncated:Er(r.risks_truncated,`${t}.risks_truncated`),completed_at:Cr(r.completed_at,`${t}.completed_at`)}}function rp(e,t){let r=`Native history[${t}]`,i=Z(e,r);ee(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ia(i.unresolved_ids,`${r}.unresolved_ids`);return Kt(n,`${r}.unresolved_ids`),{goal_cycle:$(i.goal_cycle,`${r}.goal_cycle`,1),iteration:$(i.iteration,`${r}.iteration`),attempt:$(i.attempt,`${r}.attempt`),outcome:V(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ve(i.summary,`${r}.summary`),completed_at:Cr(i.completed_at,`${r}.completed_at`)}}function $b(e){let t="Native history_overflow.outcome_counts",r=Z(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ee(r,new Set(i),t),{pass:$(r.pass,`${t}.pass`),fail:$(r.fail,`${t}.fail`),blocked:$(r.blocked,`${t}.blocked`),"execution-error":$(r["execution-error"],`${t}.execution-error`),recovery:$(r.recovery,`${t}.recovery`)}}function Ob(e){let t="Native history_overflow",r=Z(e,t);ee(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=$(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Cr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Cr(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=$b(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Hb(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(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.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}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 i=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(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Db(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 r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);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(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.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 ue(e){let t=Z(e,"Native portable state");if(ee(t,Sb,"Native portable state"),t.schema!==Sr)throw new Error(`Native portable state schema must be ${Sr}`);let r=J(t.name,"Native state name");if(!yb.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=We(t.spec_changes,"Native spec_changes",Cb);Kt(i.map(s=>s.capability),"Native spec change capabilities");let n=We(t.acceptance,"Native acceptance",Rb);Kt(n.map(s=>s.id),"Native acceptance IDs");let a=We(t.history,"Native history",rp);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Sr,name:r,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:$(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1?{document_constraints_version:1}:(()=>{throw new Error("Native document_constraints_version must be 1")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:$c(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:$c(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:V(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:xb(t.workspace),loop:Pb(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ab(t.builder_handoff),blockers:We(t.blockers,"Native blockers",Ib),verification:t.verification===null?null:Tb(t.verification),history:a,history_overflow:Ob(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:Er(t.archived,"Native archived"),created_at:Cr(t.created_at,"Native created_at")};return Hb(o),Db(o),o}function ip(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ue({schema:Sr,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Ic(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Di(e,t){let r=ue(e),i=rp(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ue({...r,history:n,history_overflow:a})}function qb(e,t){let r=(0,Aa.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function xt(e){let t=await wb.readFile(e,"utf8");return ue(qb(t,"Native portable state"))}async function Oc(e,t,r={}){let i=ue(t);await Fe(e,(0,Aa.stringify)(i),r)}async function Fb(e,t){let r=Ra.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Ra.set(e,a),await r;try{return await t()}finally{i(),Ra.get(e)===a&&Ra.delete(e)}}async function np(e){return Fb(e.file,async()=>{let t=$(e.expectedStateVersion,"Native expected state version",1),r=ue(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await xt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Hi(t,i.state_version);return await Oc(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await xt(e.file);if(n.state_version!==t)throw new Hi(t,n.state_version)}}),r})}var Aa,yb,Nb,bb,kb,Sb,Hi,Ra,Pe=C(()=>{"use strict";Aa=Je(De(),1);D();Oi();yb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Nb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bb=/^A[1-9][0-9]*$/u,kb=/^[a-f0-9]{64}$/u,Sb=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Hi=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Ra=new Map});var Yt=C(()=>{"use strict"});var ap=C(()=>{"use strict";xa();Ac();Pe();Yt();Oi();Ri()});var op,t_,r_,Dc=C(()=>{"use strict";oe();Sc();ap();op="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",t_=new RegExp(`^portable-archive-(${op})\\.json$`,"u"),r_=new RegExp(`^portable-migration-(${op})\\.json$`,"u")});import{createHash as Vb}from"node:crypto";import{constants as ja,promises as Re}from"node:fs";import _e from"node:path";import{TextDecoder as Mb}from"node:util";function $a(e,t){let r=_e.relative(e,t);return r===""||!_e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_e.sep}`)}function Wb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function zb(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Jb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ta(e,t){return O({...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 qc(e,t){let r=await Re.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Re.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function sp(e,t,r){let i=_e.resolve(e),n=_e.resolve(t);if(!$a(i,n))throw new Error(`${r} is outside its managed root`);let a=[await qc(i,r)],o=i;for(let s of _e.relative(i,n).split(_e.sep).filter(Boolean)){await Pt(a,r),o=_e.join(o,s);let c=await qc(o,r);if(!$a(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Pt(a,r),a}async function Pt(e,t){for(let r of e){let i=await Re.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!zb(r,i)||await Re.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Gb(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Fi(e){let t=e.maxBytes===null?null:Wb(e.maxBytes),r=_e.resolve(e.file),i=await sp(e.root,_e.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>qc(_e.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Pt(i,e.label);let a=await Re.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Jb(a),s=await Re.realpath(r);if(!$a(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>$a(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ja.O_RDONLY:ja.O_RDONLY|ja.O_NOFOLLOW|ja.O_NONBLOCK,l=await Re.open(r,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[u,f]=await Promise.all([Re.lstat(r),Re.realpath(r)]);if(await Pt(i,e.label),await Pt(n,e.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!Ta(o,d)||!Ta(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await Gb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,g]=await Promise.all([l.stat(),Re.lstat(r),Re.realpath(r)]);if(await Pt(i,e.label),await Pt(n,e.label),!p.isFile()||p.isSymbolicLink()||g!==s||!Ta(o,m)||!Ta(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:Vb("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function cp(e){let t=await Fi(e),r;try{r=new Mb("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function Li(e){let t=await sp(e.root,e.directory,e.label);return{verify:()=>Pt(t,e.label)}}var ge=C(()=>{"use strict";D();qe()});import{TextDecoder as Kb}from"util";var w_,Oa=C(()=>{"use strict";D();A();ge();w_=new Kb("utf-8",{fatal:!0})});var G=C(()=>{"use strict";fe();Pi();Dc();Oa()});import{createHash as Xb}from"crypto";function de(e){return Xb("sha256").update(e).digest("hex")}var Ae=C(()=>{"use strict"});import Bc from"path";function Ha(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function gk(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 wk(e,t){return de(`comet.native.snapshot-policy.v1
147
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Lc(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function yk(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function pp(e){let t=ka(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?yk(n):void 0;if(a&&!a())return!1;let o=Lc(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let d=r[l];d&&(d.kind==="literal"&&d.value===s||d.kind==="question"&&s!=="/"?c.add(l+1):d.kind==="star"&&s!=="/"||d.kind==="globstar"?c.add(l):d.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Lc(r,c,a),o===null||o.size===0)return!1}return Lc(r,o,a)?.has(r.length)??!1}}function Nk(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ka(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>ka(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 i=wk(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(pp),excludeMatchers:r.map(pp),excludedDirectoryPrefixes:r.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 we(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ye(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Pr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ze(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function vp(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 r=Bc.posix.normalize(e);if(r!==e||Bc.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function bk(e,t){let r=we(e,`Native snapshot entry ${t}`);ye(r,uk,`Native snapshot entry ${t}`);let i=vp(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Da.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:ze(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!vk.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function kk(e,t){let r=we(e,`Native snapshot omission ${t}`);if(ye(r,dk,`Native snapshot omission ${t}`),!hk.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!mk.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:vp(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:ze(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function Sk(e){let t=we(e,"Native snapshot omission overflow");if(ye(t,fk,"Native snapshot omission overflow"),typeof t.hash!="string"||!Da.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Pr(t.count,"Native snapshot omission overflow count")}}function xr(e,t){let r=we(e,t);if(ye(r,sk,t),typeof r.hash!="string"||!Da.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=ze(r.recordCount,`${t} recordCount`),n=ze(r.storedRecordCount,`${t} storedRecordCount`),a=ze(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function hp(e){let t=we(e,"Native Git selection evidence");if(ye(t,ok,"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 r=xr(t.stageBefore,"Native Git selection stageBefore"),i=xr(t.combined,"Native Git selection combined"),n=xr(t.stageAfter,"Native Git selection stageAfter"),a=xr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=xr(t.finalCombined,"Native Git selection finalCombined"),s=xr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(u=>u.overflow),l=!Ha(r,n)||!Ha(n,a)||!Ha(i,o)||!Ha(a,s),d=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==d)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:d,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function mp(e,t){let r=we(e,t);if(ye(r,lk,t),typeof r.hash!="string"||!Da.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=ze(r.visitedNodeCount,`${t} visitedNodeCount`),n=ze(r.recordCount,`${t} recordCount`),a=ze(r.storedRecordCount,`${t} storedRecordCount`),o=ze(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function Ek(e){let t=we(e,"Native physical selection evidence");if(ye(t,ck,"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 r=mp(t.before,"Native physical selection before"),i=mp(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!gk(r,i);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:r,after:i}}function gp(e){let t=we(e,"Native content snapshot manifest");if(ye(t,tk,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!pk.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=we(t.capture,"Native content snapshot capture");if(ye(w,nk,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=w.gitSelection===void 0?void 0:hp(w.gitSelection),S=w.physicalSelection===void 0?void 0:Ek(w.physicalSelection),I=null;if(w.projection!==void 0){let K=we(w.projection,"Native content snapshot projection");if(ye(K,ak,"Native content snapshot projection"),K.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");I={provider:"git",...K.selection===void 0?{}:{selection:hp(K.selection)}}}if(w.provider==="git"){if(S||I)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(S&&I)throw new Error("Native physical-tree capture cannot combine selection and projection");r=I?{provider:"physical-tree",projection:I}:{provider:"physical-tree",...S?{physicalSelection:S}:{}}}}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 i=we(t.limits,"Native content snapshot limits");ye(i,rk,"Native content snapshot limits");let n={maxFiles:Pr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Pr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Pr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Pr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Pr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=we(t.policy,"Native snapshot policy");if(ye(w,ik,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Nk({include:w.include,exclude:w.exclude,hash:w.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(bk),s=t.omitted.map(kk),c=ze(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Sk(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,R)=>w+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Zb||c<s.length)throw new Error("Native content snapshot omission count is invalid");let d=c-s.length;if(d===0&&l||d>0&&l?.count!==d)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 u=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...u,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(u.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 g=s.filter(w=>w.reason==="physical-enumeration-limit"),v=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...g,...v])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||v.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,N=b?.status==="overflow"||b?.status==="overflow-and-changed",y=b?.status==="changed"||b?.status==="overflow-and-changed";if(N!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(v.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}function Ck(e,t){if(!ek.test(t))throw new Error(`Invalid Native change name: ${t}`);return Bc.join(Y(e,t),"baseline-manifest.json")}async function Vc(e,t){let r=Ck(e,t),i=Ce(e,r);await L(i,r);try{let n=await cp({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return gp(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var B_,Zb,ek,tk,rk,ik,nk,ak,ok,sk,ck,lk,uk,dk,fk,pk,hk,mk,Da,vk,V_,M_,W_,z_,J_,Rr=C(()=>{"use strict";D();fe();Ae();qe();A();ge();gi();B_={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Zb=1e3,ek=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tk=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),rk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),ik=new Set(["schema","include","exclude","hash"]),nk=new Set(["provider","gitSelection","physicalSelection","projection"]),ak=new Set(["provider","selection"]),ok=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),sk=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),ck=new Set(["schema","status","before","after"]),lk=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),uk=new Set(["path","hash","size","type","gitObjectId"]),dk=new Set(["path","size","type","reason"]),fk=new Set(["ref","hash","count"]),pk=new Set(["change-created","legacy-migration","explicit"]),hk=new Set(["file","directory","other"]),mk=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"]),Da=/^[a-f0-9]{64}$/u,vk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,V_=64*1024,M_=64*1024,W_={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},z_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};J_=(1n<<256n)-1n});function Rp(){eS+=1}var eS,_p=C(()=>{"use strict";eS=0});import{execFileSync as tS}from"node:child_process";function nS(e,t){Rp();try{return tS("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:rS,maxBuffer:iS,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Qc(e,t,i)}}function pe(e,t){return nS(e,t).trim()}var rS,iS,Qc,Ie=C(()=>{"use strict";_p();rS=3e4,iS=8*1024*1024,Qc=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as aS}from"node:fs";import oS from"node:path";function Wa(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ma(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Ip(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function fS(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function jp(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.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=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Hp(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===el&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let d=s.get(l),u=e.acceptance_index[l];d&&u&&(u.source!==d.source||u.text!==d.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(d=>!c.has(d)));return i.uncovered=o.filter(l=>!Tp(e.children,l)),$p(i)?i:null}if(e.schema===Xt&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Tp(e.children,a)),$p(i)?i:null}return null}function Tp(e,t){return e.some(r=>r.covers.includes(t))}function $p(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function _t(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function pS(e){let t=Wa(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Wa(n,`Native children acceptance_index.${i}`);if(Ma(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function hS(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let d=c.get(l);if(!d)continue;let u=e[l];if(u.source!==d.source||u.text!==d.text){let f=["source","text"].filter(h=>u[h]!==d[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function Dp(e,t,r={}){let i=(0,Op.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Wa(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Xt&&a!==Rt)throw Ma(n,Ap,"Native children contract"),new Error(`Native children schema must be ${Xt} or ${Rt}`);let o=a===Xt?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ma(n,o==="indexed-v2"?cS:Ap,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let m=Wa(f,`Native child ${h}`);if(Ma(m,o==="indexed-v2"?dS:o==="summary-v2"?uS:lS,`Native ${s} child fields (child ${h})`),typeof m.name!="string"||!sS.test(m.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:p?m.summary:null,depends_on:Ip(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Ip(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let d=new Set(l);for(let f of c){let h=f.depends_on.filter(m=>!d.has(m));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}fS(c);let u=r.policy==="advisory";if(a===el){if(o==="indexed-v2"){let f=pS(n.acceptance_index);u||hS(f,t,r);let h=Object.keys(f);return u||jp(c,h,h),{schema:Rt,acceptance_index:f,children:c}}return{schema:Rt,children:c}}return t&&!u&&jp(c,t),{schema:Xt,children:c}}async function it(e){let t=oS.join(e.changeDir,Zc);try{await aS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await H({root:e.changeDir,ref:Zc}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Dp(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Hp(a,e.acceptanceIds,e.validation??{}):null}}var Op,Zc,Xt,Rt,el,sS,Ap,cS,lS,uS,dS,za=C(()=>{"use strict";Op=Je(De(),1);oe();Zc="children.yaml",Xt="comet.native.children.v1",Rt="comet.native.children.v2",el=Rt,sS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ap=new Set(["schema","children"]),cS=new Set(["schema","acceptance_index","children"]),lS=new Set(["name","depends_on","covers"]),uS=new Set(["name","summary","depends_on"]),dS=new Set(["name","depends_on","covers"])});var Ja,tl=C(()=>{"use strict";Ja=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});var Wi=C(()=>{"use strict"});var Ga=C(()=>{"use strict";tl();Wi()});function nt(e,t){if(!vS.test(e))throw new Error(`${t} must be a Git commit`)}function rl(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Ka(e){nt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:il(e.contract,i.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:zi,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function il(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Ya(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var vS,zi,Ua,Qt=C(()=>{"use strict";q();Ga();vS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;zi="comet.native.supervisor.v2",Ua=3});import Ji from"node:path";import{promises as Fp}from"node:fs";function nl(e,t){return Ji.join(Ve(e,t),"supervisor")}function Xa(e,t){return Ji.join(nl(e,t),"state.json")}function Lp(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==zi)throw new Error(`Native Supervisor state schema must be ${zi}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(nt(t.integration.targetCommit,"Native Supervisor target commit"),nt(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");nt(n.candidateCommit,"Native Supervisor integration candidate commit"),nt(n.integrationCommit,"Native Supervisor integration check commit"),qp(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&nt(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(nt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&qp(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function je(e,t,r={}){try{let i=await Fp.readFile(Xa(e,t),"utf8"),n=JSON.parse(i);if(Lp(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(Pe(),Hc)),c=await s(Ji.join(o.changesDir,t,"comet-state.yaml")),l=await it({changeDir:Ji.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:d})=>d),validation:_t(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let d of n.children)l.contract.children.some(({name:u})=>u===d.name)&&(d.acceptanceScope=il(l.contract,d.name),d.contractHash=T("comet.native.supervisor-contract.v1",l.contract),d.task&&(d.task.acceptance=structuredClone(d.acceptanceScope),d.task.contractHash=d.contractHash,d.task.verificationBoundary="child-scope-parent-reverifies-all",d.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Pe(),Hc)),s=await o(Ji.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function At(e,t){Lp(t),await Fp.mkdir(e.changesRuntimeDir,{recursive:!0}),await se(Xa(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function qp(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var It=C(()=>{"use strict";D();q();za();A();Qt()});var al=C(()=>{"use strict"});var jt=C(()=>{"use strict"});import{accessSync as Kj,constants as Yj,createWriteStream as Xj,existsSync as Qj,promises as Zj,statSync as yS}from"node:fs";import Zt from"node:path";function NS(e,t){let r=Zt.relative(e,t);return r===""||!Zt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Zt.sep}`)}function Bp(e,t){if(t.length===0||t.includes("\\")||Zt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Zt.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Zt.resolve(e),i=Zt.resolve(r,...t.split("/"));if(!NS(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=yS(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Qa=C(()=>{"use strict";Sa();al();jt()});var Vp=C(()=>{"use strict";Ie();Qa();q()});var Za=C(()=>{"use strict";Ie();D()});var Kp,er=C(()=>{"use strict";q();Rr();Kp=1024*1024});var ro=C(()=>{"use strict";q();jt();gi();er()});var ph,bE,kE,SE,EH,EE,CH,wl=C(()=>{"use strict";q();ph="scoped-text-safety",bE=1,kE=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),SE="comet.native.checker-policy.v1",EH=T(SE,{policy:ph,version:bE,limits:kE,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),EE=["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"],CH=new Set(EE)});var Ki=C(()=>{"use strict";q();wl();jt()});var CE,VH,Ot=C(()=>{"use strict";D();A();qe();er();ro();Ki();CE=Kp,VH=3*CE});var Kc=Je(De(),1);import{promises as Xk}from"fs";import _r from"path";import{execFileSync as Jy}from"child_process";import Gy from"fs";import gt from"path";function mr(e,t){return Jy("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function mi(e,t){return Ef(e)===Ef(t)}function Ef(e){let t=gt.resolve(e);try{let r=Gy.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function W(e){try{let t=gt.resolve(mr(e,["rev-parse","--show-toplevel"])),i=mr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?gt.resolve(i.slice(9)):t,a=null;try{a=mr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!mi(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ia(e){try{mr(e,["rev-parse","--is-inside-work-tree"]);let t=mr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:gt.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function wt(e){return ia(e).map(t=>t.root)}function ec(e,t){let r=t.find(a=>mi(gt.resolve(a.root),gt.resolve(e)));if(!r)return null;let i=gt.resolve(t[0].root),n=gt.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!mi(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Ke(e,t){try{let r=mr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}oe();D();Mt();fe();G();A();ge();Rr();G();A();yr();bt();var Ik=Je(De(),1);yr();bt();St();St();wr();yc();yr();St();var cA=4*1024*1024;var jk=null;function Tk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function wp(e,t){return(...r)=>{let i=jk;if(i===null)return t(...r);let n=Tk(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}wr();var pA=wp("hookWritePolicy",async e=>(await mc(e))?.hook??{allow_paths:[]});Ei();var $k=16*1024;vc();wi();var mI=Number.MAX_SAFE_INTEGER;D();qe();var RI={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import{createHash as Bk}from"node:crypto";import{promises as qa}from"node:fs";import rt from"node:path";D();oe();G();A();var Bi=/^[a-f0-9]{64}$/u,yp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Vk=16*1024,zc=process.platform;function Sp(e,t){let r=rt.relative(e,t);return rt.isAbsolute(r)||r===".."||r.startsWith(`..${rt.sep}`)?null:r.replaceAll("\\","/")||"."}function Ep(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Cp(e,t){if(e.length===0||Ep(e)||e.includes("\\")||rt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=rt.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Jc(e,t){return Bk("sha256").update(`${e}
145
+ `)}var lc,dN,fN,pN,_f,Mt=x(()=>{"use strict";lc={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},dN={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},fN={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},pN=new Map,_f=new Map;for(let e of Object.keys(lc)){for(let[t,r]of Object.entries(lc[e]))pN.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(dN[e]))_f.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(fN[e]))_f.set(r.toLocaleLowerCase("en-US"),t)}});import Nt from"path";function yN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Nt.posix.isAbsolute(r)||Nt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Wt(e){let t=yN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Df(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function da(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Nt.posix.isAbsolute(i)||Nt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.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(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function qf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function fa(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>la)throw new Error(`${t} exceeds ${la} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>ua)throw new Error(`${t} contains more than ${ua} wildcard tokens`);return e}function $f(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>fa(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function yi(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Of(e,t,r){let i=yi(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function NN(e){if(e===void 0)return{...ce,include:[...ce.include],exclude:[...ce.exclude]};let t=Xe(e,"native.snapshot");return{include:$f(t.include,"native.snapshot.include",ce.include),exclude:$f(t.exclude,"native.snapshot.exclude",ce.exclude),max_files:yi(t.max_files,ce.max_files,"native.snapshot.max_files"),max_total_bytes:yi(t.max_total_bytes,ce.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:yi(t.max_duration_ms,ce.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:yi(t.max_selection_records,ce.max_selection_records,"native.snapshot.max_selection_records")}}function bN(e){if(e===void 0)return;let t=Xe(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="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=Xe(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:r,fromArtifactRoot:Wt(i),toArtifactRoot:Wt(n),stage:a,...o?{cleanup:o}:{}}}function kN(e){if(e===void 0)return;let t=Xe(e,"native.finish");if(t.pull_request===void 0)return{};let r=Xe(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Nt.posix.isAbsolute(i[0])||Nt.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??mN;if(!Number.isSafeInteger(n)||n<1||n>Tf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Tf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function SN(e,t={}){let r=Xe(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??dc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=bN(r.pending_root_move),l=kN(r.finish);return{artifact_root:Wt(i),language:qf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:NN(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function EN(e){let t=Xe(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Df(t.artifact_layout),language:qf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function xN(e){let r=Xe(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>da(i,`hook.allow_paths[${n}]`)))]}}function CN(e){if(e===void 0)return{...ca};let t=Xe(e,"memory"),r=t.learning??ca.learning,i=t.retrieval??ca.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function fc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function PN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Nt.posix.isAbsolute(r)||Nt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Af)throw new Error(`${t} exceeds ${Af} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>If)throw new Error(`${t} contains more than ${If} wildcard tokens`);return r}function RN(e){let t=fc(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>PN(n,`knowledge.local.include[${a}]`)))],max_file_mb:Of(t.max_file_mb,jf.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Of(t.max_total_mb,jf.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function _N(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function AN(e){let t=fc(e,"knowledge.remote"),r=_N(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function IN(e){if(e===void 0)return{...Hf};let t=fc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:RN(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:AN(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function jN(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function TN(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)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 d=e.workflows??[e.default_workflow];if(!Array.isArray(d)||d.length===0||d.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(d)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function bi(e,t={}){let r=(0,uc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=jN(n.ambient_resume),o=n.hook===void 0?void 0:xN(n.hook),s=CN(n.memory),c=IN(n.knowledge),l=n.native===void 0?void 0:SN(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),d=n.classic===void 0?void 0:EN(n.classic),u=TN(n,o,s,c,l,d,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...d?{classic:d}:{}}}function pa(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ca},knowledge:{...Hf},native:{artifact_root:Wt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:dc,snapshot:{...ce,include:[...ce.include],exclude:[...ce.exclude]}}}}var uc,Ni,la,ua,Af,If,dc,ca,jf,Hf,mN,Tf,vN,gN,wN,ce,bt=x(()=>{"use strict";uc=Je(De(),1),Ni=Number.MAX_SAFE_INTEGER,la=1024,ua=64,Af=1024,If=64,dc=5,ca={learning:!0,retrieval:!0},jf={include:[],max_file_mb:1,max_total_mb:32},Hf={provider:"local"},mN=12e4,Tf=6e5,vN=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/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/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],gN=["**/.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"],wN=[...vN,...gN].sort((e,t)=>e.localeCompare(t,"en")),ce={include:["**/*"],exclude:[...wN],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as ha,promises as zt}from"fs";function pc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ff(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ki(e){return{dev:e.dev,ino:e.ino,birthtime:pc(e)}}function ma(e,t){let r=ki(e),i=ki(t);return Ye(r,i)?O(r,i):O(r,i)&&pc(e)===pc(t)&&Ff(e)===Ff(t)&&e.size===t.size}async function Si(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await zt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Le("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Le("too-large",`${i} exceeds ${t} bytes`);let o=await zt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ki(a)});let s=process.platform==="win32"?ha.O_RDONLY:ha.O_RDONLY|ha.O_NOFOLLOW|ha.O_NONBLOCK,c;try{c=await zt.open(e,s)}catch(l){throw l.code==="ELOOP"?new Le("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:n}),zt.lstat(e,{bigint:n}),zt.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!ma(a,l)||!ma(a,d))throw new Le("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:ki(l)}),await r.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-h,{bytesRead:N}=await c.read(m,0,Math.min(m.length,b),null);if(N===0)break;if(h+=N,h>t)throw new Le("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[p,g,v]=await Promise.all([c.stat({bigint:n}),zt.lstat(e,{bigint:n}),zt.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==o||!ma(a,p)||!ma(a,g))throw new Le("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:ki(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:v}}finally{await c.close()}}var Le,Ei=x(()=>{"use strict";wi();Le=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as va}from"fs";import kt from"path";function $N(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function hc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}async function Lf(e,t){let r=kt.resolve(e),i=await va.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return va.realpath(r)}async function Bf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=kt.join(n,r[a]);let o;try{o=await va.lstat(n)}catch(d){if($N(d))return{exists:!1,kind:"missing"};throw d}let s=kt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await va.realpath(n);if(!hc(t,l))throw new Error(`${i.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 gr(e,t,r){let i=da(t,r.label),n=kt.resolve(e),a=await Lf(n,r.label),o=i.split("/"),s=kt.resolve(n,...o);if(!hc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Bf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Qe(e,t,r,i){let n=await gr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Lf(n.projectRoot,i.label);return Si(n.target,r,{...i,verify:async(o,s)=>{if(!hc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Bf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var St=x(()=>{"use strict";Ei();bt()});import{createHash as ON}from"crypto";function HN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ga(e,t={}){return(await wa(e,t)).document}async function DN(e){try{return(await Qe(e,xi,Ni,{label:xi})).bytes}catch(t){if(HN(t))return null;throw t}}function qN(e){return e?{exists:!0,sha256:ON("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function wa(e,t={}){let r=await DN(e);return{document:r?bi(r.toString("utf8"),t):null,identity:qN(r)}}async function mc(e){return(await ga(e))?.config??null}var xi,wr=x(()=>{"use strict";bt();St();xi=".comet/config.yaml"});var yr=x(()=>{"use strict";cc();wi()});var BP,vc=x(()=>{"use strict";yr();wr();St();BP=16*1024});var yc=x(()=>{"use strict";yr();bt();wr();St();vc()});import{existsSync as Mf,promises as Jt}from"fs";import P from"path";import MN from"os";async function Nc(e){try{return await Jt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function zN(e){try{let t=await Jt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function br(e,t){let r=P.relative(e,t);return r===""||!P.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${P.sep}`)}async function Nr(e){let t=[],r=e;for(;!await Nc(r);){let n=P.dirname(r);if(n===r)break;t.push(P.basename(r)),r=n}let i=await Jt.realpath(r);return P.resolve(i,...t.reverse())}async function bc(e){try{return(await Jt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Na(e){let t=P.resolve(e);try{(await Jt.stat(t)).isDirectory()||(t=P.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=P.resolve(MN.homedir());for(;;){if(!(t===i&&r!==i)){let o=P.join(t,...ya.split("/")),s=t===r||await zN(o);if(await Nc(o)&&s)return t}if(await Nc(P.join(t,".git")))return t;let a=P.dirname(t);if(a===t)return r;t=a}}function ba(e){return Wt(e)}async function JN(e,t){let r=ba(t),i=P.resolve(e,...r.split("/")),n=await Jt.realpath(e),a=await Nr(i);if(!br(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Be(e,t){let r=ba(t),i=await JN(e,r),n=P.join(i,"comet");if(await bc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Nr(i),Nr(n)]);if(!br(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=P.resolve(e),c=P.join(s,".comet","runtime","native");if(await bc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([Jt.realpath(s),Nr(c)]);if(!br(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:P.join(e,...ya.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:P.join(n,"specs"),changesDir:P.join(n,"changes"),archiveDir:P.join(n,"archive"),runtimeDir:c,changesRuntimeDir:P.join(c,"changes"),locksDir:P.join(c,"locks"),transactionsDir:P.join(c,"transactions")}}function kc(e){if(!WN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){kc(t);let r=P.join(e.changesRuntimeDir,t);if(!z(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function GN(e,t){kc(t);let r=P.join(e.changesDir,t,"runtime");if(!z(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=Ve(e,t);if(Mf(r))return r;let i=GN(e,t);return Mf(i)?i:r}function Gt(e,t){kc(t);let r=P.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:P.join(r,"brief.md"),childrenPath:P.join(r,"children.yaml"),specsDir:P.join(r,"specs"),verificationPath:P.join(r,"verification.md"),statePath:P.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:P.join(i,"state.json")}}function xe(e,t){let r=P.resolve(t);if(z(e.runtimeDir,r))return e.runtimeDir;if(z(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function z(e,t){return br(P.resolve(e),P.resolve(t))}async function L(e,t){let r=P.resolve(e),i=P.resolve(t);if(!br(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await bc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Nr(r),Nr(i)]);if(!br(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var ya,WN,A=x(()=>{"use strict";bt();ya=".comet/config.yaml",WN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function KN(e="docs",t="en"){return pa(e,t)}async function le(e){let t=(await ga(e))?.config??null;return t?.native?t:null}async function Wf(e){let t=await Na(e.startPath),r=await le(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${ya} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?ba(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??KN(i??"docs"),a=await Be(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var ka,fe=x(()=>{"use strict";bt();wr();yc();D();A();ka=fa});var cR,Sa=x(()=>{"use strict";cR=["$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 dR,Ea=x(()=>{"use strict";Sa();dR=8*1024*1024});var xa=x(()=>{"use strict";Ea()});import{AsyncLocalStorage as ZN}from"async_hooks";var NR,bR,kR,Pi=x(()=>{"use strict";Ei();xa();A();qe();NR=16*1024,bR=900*1e3,kR=new ZN});var Gf,Sc=x(()=>{"use strict";Gf=Je(De(),1)});var Ze,Et,xt,Ri=x(()=>{"use strict";Ze="comet.native.v3",Et="comet.native.v2",xt="comet.native.v1"});import eb from"node:path";function Ii(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xf(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ut(e){if(!Yf.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Qf(e){if(!Yf.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Zf(e,t){if(e.length===0||eb.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cb(e,t){let r=Ii(e,`spec_changes[${t}]`);if(Xf(r,ib,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Qf(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Zf(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!xc.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!xc.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function lb(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 Cc(e,t){if(Xf(e,t,tt),typeof e.name!="string")throw new Error("Native change name is required");if(Ut(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"||!nb.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&&!ab.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 r=e.spec_changes.map(cb),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!ob.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"&&Zf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lb(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:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ji(e){let t=Ii(e,tt);if(t.schema!==xt)throw new Error(`Expected ${xt}`);return{schema:xt,...Cc(t,tb)}}function Ai(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ec(e,t,r){if(e===null)return null;let i=typeof e=="string"?sb.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function ub(e){if(e==null)return null;if(typeof e!="string"||!xc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function db(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 Ti(e){let t=Ii(e,tt);if(t.schema!==Et)throw new Error(`Expected ${Et}`);if(Ai(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Et} minimum_runtime_version must be 2`);return{schema:Et,minimum_runtime_version:2,revision:Ai(t.revision,"Native v2 revision"),...Cc(t,Kf)}}function kr(e){let t=Ii(e,tt);if(t.schema!==Ze){if(t.schema===xt||t.schema===Et){let o=t.schema===xt?ji(t):Ti(t);throw new _i(o.name,o.schema)}throw new Me(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Ai(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Me(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Ai(t.revision,"Native revision"),n=Cc(t,rb),a=ub(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ze,minimum_runtime_version:3,revision:i,verification_protocol:db(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Ec(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ec(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ec(t.partial_allowance,"Native partial_allowance","allowances")}}function Pc(e){let t=Ii(e,tt);if(t.schema===xt){let n=ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ze}`}}if(t.schema===Et){let n=Ti(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ze}`}}if(t.schema!==Ze){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 Me(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Ai(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Me(t.schema,r).message};let i=kr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Uf,tb,Kf,rb,ib,nb,ab,ob,tt,xc,Yf,sb,_i,Me,Ca=x(()=>{"use strict";Ri();Uf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],tb=new Set(Uf),Kf=new Set([...Uf,"minimum_runtime_version","revision"]),rb=new Set([...Kf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),ib=new Set(["capability","operation","source","base_hash"]),nb=new Set(["shape","build","verify","archive"]),ab=new Set(["implicit","confirmed"]),ob=new Set(["pending","pass","fail"]),tt="comet-state.yaml",xc=/^[a-f0-9]{64}$/u,Yf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sb=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,_i=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Me=class extends Error{constructor(r,i){super(r!==Ze||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import{createHash as fb}from"crypto";function Ce(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function pb(e,t){t.has(e)&&Ce("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||Ce("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Ce("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ce("symbol properties are not supported"),`[${e.map(i=>Rc(i,t)).join(",")}]`}finally{t.delete(e)}}function hb(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ce("only plain objects are supported"),t.has(e)&&Ce("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ce("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Ce("accessor properties are not supported"),`${JSON.stringify(o)}:${Rc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Rc(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)||Ce("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?pb(e,t):hb(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ce(`${typeof e} values are not supported`)}return Ce("unsupported value type")}function _c(e){return Rc(e,new Set)}function T(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 fb("sha256").update(`${e}
146
+ ${_c(t)}`).digest("hex")}var q=x(()=>{"use strict"});var TR,ep,$i=x(()=>{"use strict";Mt();q();TR=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ep=Object.freeze({maxCriteria:1024})});var Ac=x(()=>{"use strict";$i()});function Ic(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Sr,Pa,tp,Oi=x(()=>{"use strict";Sr="comet.native.v4",Pa="comet.native.local-execution.v4",tp=["multi-session","single-session"]});var Hc={};gm(Hc,{NativePortableStateVersionConflictError:()=>Hi,appendNativePortableHistory:()=>Di,compareAndSwapNativePortableState:()=>np,createNativePortableState:()=>ip,parseNativePortableState:()=>ue,readNativePortableState:()=>Ct,writeNativePortableState:()=>Oc});import{promises as wb}from"node:fs";function Z(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ee(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function J(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Tc(e,t){return e===null?null:J(e,t)}function $c(e,t){let r=J(e,t);if(!kb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Er(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function $(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Eb(e,t){return e===null?null:$(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function We(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ia(e,t){return We(e,t,(r,i)=>J(r,`${t}[${i}]`))}function Kt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function xr(e,t){let r=J(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function _a(e,t,r=!1){let i=J(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ve(e,t){let r=Z(e,t);return ee(r,new Set(["text","truncated"]),t),{text:J(r.text,`${t}.text`,{empty:!0}),truncated:Er(r.truncated,`${t}.truncated`)}}function xb(e,t){let r=`Native spec_changes[${t}]`,i=Z(e,r);ee(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=J(i.capability,`${r}.capability`);if(!Nb.test(n))throw new Error(`${r}.capability is invalid`);let a=V(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:_a(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:_a(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:$c(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function Cb(e){let t="Native workspace",r=Z(e,t);ee(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=V(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Tc(r.change_branch,`${t}.change_branch`),a=Tc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:V(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Pb(e){let t="Native loop",r=Z(e,t);ee(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Ia(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Kt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:V(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:V(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:$(r.goal_cycle,`${t}.goal_cycle`,1),iteration:$(r.iteration,`${t}.iteration`),attempt:$(r.attempt,`${t}.attempt`),retry_epoch:$(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:$(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:$(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:$(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Tc(r.next_action,`${t}.next_action`)}}function Rb(e,t){let r=`Native acceptance[${t}]`,i=Z(e,r);ee(i,new Set(["id","source","text","result","reason"]),r);let n=J(i.id,`${r}.id`);if(!bb.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:_a(i.source,`${r}.source`),text:J(i.text,`${r}.text`),result:V(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ve(i.reason,`${r}.reason`)}}function _b(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Z(e,r);return ee(i,new Set(["name","result","note"]),r),{name:ve(i.name,`${r}.name`),result:V(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ve(i.note,`${r}.note`)}}function Ab(e){let t="Native builder_handoff",r=Z(e,t);ee(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ia(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Kt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Z(r.review,`${t}.review`);return n&&ee(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:J(r.candidate_id,`${t}.candidate_id`),identity_provider:J(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:J(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:$(r.iteration,`${t}.iteration`,1),summary:ve(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:We(r.checks,`${t}.checks`,_b),checks_truncated:Er(r.checks_truncated,`${t}.checks_truncated`),known_limits:We(r.known_limits,`${t}.known_limits`,(a,o)=>ve(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Er(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:V(n.status,["passed"],`${t}.review.status`),summary:ve(n.summary,`${t}.review.summary`),reviewer_execution_ref:J(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:xr(r.submitted_at,`${t}.submitted_at`)}}function Ib(e,t){let r=`Native blockers[${t}]`,i=Z(e,r);ee(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ia(i.acceptance_ids,`${r}.acceptance_ids`);return Kt(n,`${r}.acceptance_ids`),{owner:V(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ve(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:V(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function jb(e,t){let r=`Native verification.checks[${t}]`,i=Z(e,r);return ee(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:J(i.id,`${r}.id`),name:ve(i.name,`${r}.name`),argv_display:We(i.argv_display,`${r}.argv_display`,(n,a)=>ve(n,`${r}.argv_display[${a}]`)),argv_truncated:Er(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:_a(i.cwd_ref,`${r}.cwd_ref`,!0),status:V(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Eb(i.exit_code,`${r}.exit_code`),duration_ms:$(i.duration_ms,`${r}.duration_ms`)}}function Tb(e){let t="Native verification",r=Z(e,t);ee(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=We(r.checks,`${t}.checks`,jb);Kt(i.map(a=>a.id),`${t}.checks IDs`);let n=J(r.identity_provider,`${t}.identity_provider`);return{candidate_id:J(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:J(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:$(r.iteration,`${t}.iteration`,1),attempt:$(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ve(r.summary,`${t}.summary`),risks:We(r.risks,`${t}.risks`,(a,o)=>ve(a,`${t}.risks[${o}]`)),risks_truncated:Er(r.risks_truncated,`${t}.risks_truncated`),completed_at:xr(r.completed_at,`${t}.completed_at`)}}function rp(e,t){let r=`Native history[${t}]`,i=Z(e,r);ee(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ia(i.unresolved_ids,`${r}.unresolved_ids`);return Kt(n,`${r}.unresolved_ids`),{goal_cycle:$(i.goal_cycle,`${r}.goal_cycle`,1),iteration:$(i.iteration,`${r}.iteration`),attempt:$(i.attempt,`${r}.attempt`),outcome:V(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ve(i.summary,`${r}.summary`),completed_at:xr(i.completed_at,`${r}.completed_at`)}}function $b(e){let t="Native history_overflow.outcome_counts",r=Z(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ee(r,new Set(i),t),{pass:$(r.pass,`${t}.pass`),fail:$(r.fail,`${t}.fail`),blocked:$(r.blocked,`${t}.blocked`),"execution-error":$(r["execution-error"],`${t}.execution-error`),recovery:$(r.recovery,`${t}.recovery`)}}function Ob(e){let t="Native history_overflow",r=Z(e,t);ee(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=$(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:xr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:xr(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=$b(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Hb(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(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.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}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 i=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(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Db(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 r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);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(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.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 ue(e){let t=Z(e,"Native portable state");if(ee(t,Sb,"Native portable state"),t.schema!==Sr)throw new Error(`Native portable state schema must be ${Sr}`);let r=J(t.name,"Native state name");if(!yb.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=We(t.spec_changes,"Native spec_changes",xb);Kt(i.map(s=>s.capability),"Native spec change capabilities");let n=We(t.acceptance,"Native acceptance",Rb);Kt(n.map(s=>s.id),"Native acceptance IDs");let a=We(t.history,"Native history",rp);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Sr,name:r,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:$(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1?{document_constraints_version:1}:(()=>{throw new Error("Native document_constraints_version must be 1")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:$c(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:$c(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:V(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:Cb(t.workspace),loop:Pb(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ab(t.builder_handoff),blockers:We(t.blockers,"Native blockers",Ib),verification:t.verification===null?null:Tb(t.verification),history:a,history_overflow:Ob(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:Er(t.archived,"Native archived"),created_at:xr(t.created_at,"Native created_at")};return Hb(o),Db(o),o}function ip(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ue({schema:Sr,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Ic(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Di(e,t){let r=ue(e),i=rp(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ue({...r,history:n,history_overflow:a})}function qb(e,t){let r=(0,Aa.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Ct(e){let t=await wb.readFile(e,"utf8");return ue(qb(t,"Native portable state"))}async function Oc(e,t,r={}){let i=ue(t);await Fe(e,(0,Aa.stringify)(i),r)}async function Fb(e,t){let r=Ra.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Ra.set(e,a),await r;try{return await t()}finally{i(),Ra.get(e)===a&&Ra.delete(e)}}async function np(e){return Fb(e.file,async()=>{let t=$(e.expectedStateVersion,"Native expected state version",1),r=ue(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Ct(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Hi(t,i.state_version);return await Oc(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ct(e.file);if(n.state_version!==t)throw new Hi(t,n.state_version)}}),r})}var Aa,yb,Nb,bb,kb,Sb,Hi,Ra,Pe=x(()=>{"use strict";Aa=Je(De(),1);D();Oi();yb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Nb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bb=/^A[1-9][0-9]*$/u,kb=/^[a-f0-9]{64}$/u,Sb=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Hi=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Ra=new Map});var Yt=x(()=>{"use strict"});var ap=x(()=>{"use strict";Ca();Ac();Pe();Yt();Oi();Ri()});var op,t_,r_,Dc=x(()=>{"use strict";oe();Sc();ap();op="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",t_=new RegExp(`^portable-archive-(${op})\\.json$`,"u"),r_=new RegExp(`^portable-migration-(${op})\\.json$`,"u")});import{createHash as Vb}from"node:crypto";import{constants as ja,promises as Re}from"node:fs";import _e from"node:path";import{TextDecoder as Mb}from"node:util";function $a(e,t){let r=_e.relative(e,t);return r===""||!_e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_e.sep}`)}function Wb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function zb(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Jb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ta(e,t){return O({...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 qc(e,t){let r=await Re.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Re.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function sp(e,t,r){let i=_e.resolve(e),n=_e.resolve(t);if(!$a(i,n))throw new Error(`${r} is outside its managed root`);let a=[await qc(i,r)],o=i;for(let s of _e.relative(i,n).split(_e.sep).filter(Boolean)){await Pt(a,r),o=_e.join(o,s);let c=await qc(o,r);if(!$a(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Pt(a,r),a}async function Pt(e,t){for(let r of e){let i=await Re.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!zb(r,i)||await Re.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Gb(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Fi(e){let t=e.maxBytes===null?null:Wb(e.maxBytes),r=_e.resolve(e.file),i=await sp(e.root,_e.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>qc(_e.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Pt(i,e.label);let a=await Re.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Jb(a),s=await Re.realpath(r);if(!$a(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>$a(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ja.O_RDONLY:ja.O_RDONLY|ja.O_NOFOLLOW|ja.O_NONBLOCK,l=await Re.open(r,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[u,f]=await Promise.all([Re.lstat(r),Re.realpath(r)]);if(await Pt(i,e.label),await Pt(n,e.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!Ta(o,d)||!Ta(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await Gb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,g]=await Promise.all([l.stat(),Re.lstat(r),Re.realpath(r)]);if(await Pt(i,e.label),await Pt(n,e.label),!p.isFile()||p.isSymbolicLink()||g!==s||!Ta(o,m)||!Ta(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:Vb("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function cp(e){let t=await Fi(e),r;try{r=new Mb("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function Li(e){let t=await sp(e.root,e.directory,e.label);return{verify:()=>Pt(t,e.label)}}var ge=x(()=>{"use strict";D();qe()});import{TextDecoder as Kb}from"util";var w_,Oa=x(()=>{"use strict";D();A();ge();w_=new Kb("utf-8",{fatal:!0})});var G=x(()=>{"use strict";fe();Pi();Dc();Oa()});import{createHash as Xb}from"crypto";function de(e){return Xb("sha256").update(e).digest("hex")}var Ae=x(()=>{"use strict"});import Bc from"path";function Ha(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function gk(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 wk(e,t){return de(`comet.native.snapshot-policy.v1
147
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Lc(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function yk(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function pp(e){let t=ka(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?yk(n):void 0;if(a&&!a())return!1;let o=Lc(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let d=r[l];d&&(d.kind==="literal"&&d.value===s||d.kind==="question"&&s!=="/"?c.add(l+1):d.kind==="star"&&s!=="/"||d.kind==="globstar"?c.add(l):d.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Lc(r,c,a),o===null||o.size===0)return!1}return Lc(r,o,a)?.has(r.length)??!1}}function Nk(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ka(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>ka(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 i=wk(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(pp),excludeMatchers:r.map(pp),excludedDirectoryPrefixes:r.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 we(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ye(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Pr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ze(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function vp(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 r=Bc.posix.normalize(e);if(r!==e||Bc.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function bk(e,t){let r=we(e,`Native snapshot entry ${t}`);ye(r,uk,`Native snapshot entry ${t}`);let i=vp(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Da.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:ze(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!vk.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function kk(e,t){let r=we(e,`Native snapshot omission ${t}`);if(ye(r,dk,`Native snapshot omission ${t}`),!hk.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!mk.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:vp(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:ze(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function Sk(e){let t=we(e,"Native snapshot omission overflow");if(ye(t,fk,"Native snapshot omission overflow"),typeof t.hash!="string"||!Da.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Pr(t.count,"Native snapshot omission overflow count")}}function Cr(e,t){let r=we(e,t);if(ye(r,sk,t),typeof r.hash!="string"||!Da.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=ze(r.recordCount,`${t} recordCount`),n=ze(r.storedRecordCount,`${t} storedRecordCount`),a=ze(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function hp(e){let t=we(e,"Native Git selection evidence");if(ye(t,ok,"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 r=Cr(t.stageBefore,"Native Git selection stageBefore"),i=Cr(t.combined,"Native Git selection combined"),n=Cr(t.stageAfter,"Native Git selection stageAfter"),a=Cr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Cr(t.finalCombined,"Native Git selection finalCombined"),s=Cr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(u=>u.overflow),l=!Ha(r,n)||!Ha(n,a)||!Ha(i,o)||!Ha(a,s),d=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==d)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:d,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function mp(e,t){let r=we(e,t);if(ye(r,lk,t),typeof r.hash!="string"||!Da.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=ze(r.visitedNodeCount,`${t} visitedNodeCount`),n=ze(r.recordCount,`${t} recordCount`),a=ze(r.storedRecordCount,`${t} storedRecordCount`),o=ze(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function Ek(e){let t=we(e,"Native physical selection evidence");if(ye(t,ck,"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 r=mp(t.before,"Native physical selection before"),i=mp(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!gk(r,i);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:r,after:i}}function gp(e){let t=we(e,"Native content snapshot manifest");if(ye(t,tk,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!pk.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=we(t.capture,"Native content snapshot capture");if(ye(w,nk,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=w.gitSelection===void 0?void 0:hp(w.gitSelection),S=w.physicalSelection===void 0?void 0:Ek(w.physicalSelection),I=null;if(w.projection!==void 0){let K=we(w.projection,"Native content snapshot projection");if(ye(K,ak,"Native content snapshot projection"),K.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");I={provider:"git",...K.selection===void 0?{}:{selection:hp(K.selection)}}}if(w.provider==="git"){if(S||I)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(S&&I)throw new Error("Native physical-tree capture cannot combine selection and projection");r=I?{provider:"physical-tree",projection:I}:{provider:"physical-tree",...S?{physicalSelection:S}:{}}}}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 i=we(t.limits,"Native content snapshot limits");ye(i,rk,"Native content snapshot limits");let n={maxFiles:Pr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Pr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Pr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Pr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Pr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=we(t.policy,"Native snapshot policy");if(ye(w,ik,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Nk({include:w.include,exclude:w.exclude,hash:w.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(bk),s=t.omitted.map(kk),c=ze(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Sk(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,R)=>w+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Zb||c<s.length)throw new Error("Native content snapshot omission count is invalid");let d=c-s.length;if(d===0&&l||d>0&&l?.count!==d)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 u=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...u,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(u.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 g=s.filter(w=>w.reason==="physical-enumeration-limit"),v=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...g,...v])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||v.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,N=b?.status==="overflow"||b?.status==="overflow-and-changed",y=b?.status==="changed"||b?.status==="overflow-and-changed";if(N!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(v.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}function xk(e,t){if(!ek.test(t))throw new Error(`Invalid Native change name: ${t}`);return Bc.join(Y(e,t),"baseline-manifest.json")}async function Vc(e,t){let r=xk(e,t),i=xe(e,r);await L(i,r);try{let n=await cp({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return gp(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var B_,Zb,ek,tk,rk,ik,nk,ak,ok,sk,ck,lk,uk,dk,fk,pk,hk,mk,Da,vk,V_,M_,W_,z_,J_,Rr=x(()=>{"use strict";D();fe();Ae();qe();A();ge();gi();B_={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Zb=1e3,ek=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tk=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),rk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),ik=new Set(["schema","include","exclude","hash"]),nk=new Set(["provider","gitSelection","physicalSelection","projection"]),ak=new Set(["provider","selection"]),ok=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),sk=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),ck=new Set(["schema","status","before","after"]),lk=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),uk=new Set(["path","hash","size","type","gitObjectId"]),dk=new Set(["path","size","type","reason"]),fk=new Set(["ref","hash","count"]),pk=new Set(["change-created","legacy-migration","explicit"]),hk=new Set(["file","directory","other"]),mk=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"]),Da=/^[a-f0-9]{64}$/u,vk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,V_=64*1024,M_=64*1024,W_={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},z_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};J_=(1n<<256n)-1n});function Rp(){eS+=1}var eS,_p=x(()=>{"use strict";eS=0});import{execFileSync as tS}from"node:child_process";function nS(e,t){Rp();try{return tS("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:rS,maxBuffer:iS,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Qc(e,t,i)}}function pe(e,t){return nS(e,t).trim()}var rS,iS,Qc,Ie=x(()=>{"use strict";_p();rS=3e4,iS=8*1024*1024,Qc=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as aS}from"node:fs";import oS from"node:path";function Wa(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ma(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Ip(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function fS(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function jp(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.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=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Hp(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===el&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let d=s.get(l),u=e.acceptance_index[l];d&&u&&(u.source!==d.source||u.text!==d.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(d=>!c.has(d)));return i.uncovered=o.filter(l=>!Tp(e.children,l)),$p(i)?i:null}if(e.schema===Xt&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Tp(e.children,a)),$p(i)?i:null}return null}function Tp(e,t){return e.some(r=>r.covers.includes(t))}function $p(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function _t(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function pS(e){let t=Wa(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Wa(n,`Native children acceptance_index.${i}`);if(Ma(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function hS(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let d=c.get(l);if(!d)continue;let u=e[l];if(u.source!==d.source||u.text!==d.text){let f=["source","text"].filter(h=>u[h]!==d[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function Dp(e,t,r={}){let i=(0,Op.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Wa(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Xt&&a!==Rt)throw Ma(n,Ap,"Native children contract"),new Error(`Native children schema must be ${Xt} or ${Rt}`);let o=a===Xt?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ma(n,o==="indexed-v2"?cS:Ap,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let m=Wa(f,`Native child ${h}`);if(Ma(m,o==="indexed-v2"?dS:o==="summary-v2"?uS:lS,`Native ${s} child fields (child ${h})`),typeof m.name!="string"||!sS.test(m.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:p?m.summary:null,depends_on:Ip(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Ip(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let d=new Set(l);for(let f of c){let h=f.depends_on.filter(m=>!d.has(m));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}fS(c);let u=r.policy==="advisory";if(a===el){if(o==="indexed-v2"){let f=pS(n.acceptance_index);u||hS(f,t,r);let h=Object.keys(f);return u||jp(c,h,h),{schema:Rt,acceptance_index:f,children:c}}return{schema:Rt,children:c}}return t&&!u&&jp(c,t),{schema:Xt,children:c}}async function it(e){let t=oS.join(e.changeDir,Zc);try{await aS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await H({root:e.changeDir,ref:Zc}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Dp(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Hp(a,e.acceptanceIds,e.validation??{}):null}}var Op,Zc,Xt,Rt,el,sS,Ap,cS,lS,uS,dS,za=x(()=>{"use strict";Op=Je(De(),1);oe();Zc="children.yaml",Xt="comet.native.children.v1",Rt="comet.native.children.v2",el=Rt,sS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ap=new Set(["schema","children"]),cS=new Set(["schema","acceptance_index","children"]),lS=new Set(["name","depends_on","covers"]),uS=new Set(["name","summary","depends_on"]),dS=new Set(["name","depends_on","covers"])});var Ja,tl=x(()=>{"use strict";Ja=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});var Wi=x(()=>{"use strict"});var Ga=x(()=>{"use strict";tl();Wi()});function nt(e,t){if(!vS.test(e))throw new Error(`${t} must be a Git commit`)}function rl(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Ka(e){nt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:il(e.contract,i.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:zi,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function il(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Ya(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var vS,zi,Ua,Qt=x(()=>{"use strict";q();Ga();vS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;zi="comet.native.supervisor.v2",Ua=3});import Ji from"node:path";import{promises as Fp}from"node:fs";function nl(e,t){return Ji.join(Ve(e,t),"supervisor")}function Xa(e,t){return Ji.join(nl(e,t),"state.json")}function Lp(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==zi)throw new Error(`Native Supervisor state schema must be ${zi}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(nt(t.integration.targetCommit,"Native Supervisor target commit"),nt(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");nt(n.candidateCommit,"Native Supervisor integration candidate commit"),nt(n.integrationCommit,"Native Supervisor integration check commit"),qp(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&nt(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(nt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&qp(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function je(e,t,r={}){try{let i=await Fp.readFile(Xa(e,t),"utf8"),n=JSON.parse(i);if(Lp(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(Pe(),Hc)),c=await s(Ji.join(o.changesDir,t,"comet-state.yaml")),l=await it({changeDir:Ji.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:d})=>d),validation:_t(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let d of n.children)l.contract.children.some(({name:u})=>u===d.name)&&(d.acceptanceScope=il(l.contract,d.name),d.contractHash=T("comet.native.supervisor-contract.v1",l.contract),d.task&&(d.task.acceptance=structuredClone(d.acceptanceScope),d.task.contractHash=d.contractHash,d.task.verificationBoundary="child-scope-parent-reverifies-all",d.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Pe(),Hc)),s=await o(Ji.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function At(e,t){Lp(t),await Fp.mkdir(e.changesRuntimeDir,{recursive:!0}),await se(Xa(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function qp(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var It=x(()=>{"use strict";D();q();za();A();Qt()});var al=x(()=>{"use strict"});var jt=x(()=>{"use strict"});import{accessSync as Kj,constants as Yj,createWriteStream as Xj,existsSync as Qj,promises as Zj,statSync as yS}from"node:fs";import Zt from"node:path";function NS(e,t){let r=Zt.relative(e,t);return r===""||!Zt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Zt.sep}`)}function Bp(e,t){if(t.length===0||t.includes("\\")||Zt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Zt.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Zt.resolve(e),i=Zt.resolve(r,...t.split("/"));if(!NS(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=yS(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Qa=x(()=>{"use strict";Sa();al();jt()});var Vp=x(()=>{"use strict";Ie();Qa();q()});var Za=x(()=>{"use strict";Ie();D()});var Kp,er=x(()=>{"use strict";q();Rr();Kp=1024*1024});var ro=x(()=>{"use strict";q();jt();gi();er()});var ph,bE,kE,SE,EH,EE,xH,wl=x(()=>{"use strict";q();ph="scoped-text-safety",bE=1,kE=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),SE="comet.native.checker-policy.v1",EH=T(SE,{policy:ph,version:bE,limits:kE,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),EE=["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"],xH=new Set(EE)});var Ki=x(()=>{"use strict";q();wl();jt()});var xE,VH,Ot=x(()=>{"use strict";D();A();qe();er();ro();Ki();xE=Kp,VH=3*xE});var Kc=Je(De(),1);import{promises as Xk}from"fs";import _r from"path";import{execFileSync as Jy}from"child_process";import Gy from"fs";import gt from"path";function mr(e,t){return Jy("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function mi(e,t){return Ef(e)===Ef(t)}function Ef(e){let t=gt.resolve(e);try{let r=Gy.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function W(e){try{let t=gt.resolve(mr(e,["rev-parse","--show-toplevel"])),i=mr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?gt.resolve(i.slice(9)):t,a=null;try{a=mr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!mi(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ia(e){try{mr(e,["rev-parse","--is-inside-work-tree"]);let t=mr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:gt.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function wt(e){return ia(e).map(t=>t.root)}function ec(e,t){let r=t.find(a=>mi(gt.resolve(a.root),gt.resolve(e)));if(!r)return null;let i=gt.resolve(t[0].root),n=gt.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!mi(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Ke(e,t){try{let r=mr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}oe();D();Mt();fe();G();A();ge();Rr();G();A();yr();bt();var Ik=Je(De(),1);yr();bt();St();St();wr();yc();yr();St();var cA=4*1024*1024;var jk=null;function Tk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function wp(e,t){return(...r)=>{let i=jk;if(i===null)return t(...r);let n=Tk(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}wr();var pA=wp("hookWritePolicy",async e=>(await mc(e))?.hook??{allow_paths:[]});Ei();var $k=16*1024;vc();wi();var mI=Number.MAX_SAFE_INTEGER;D();qe();var RI={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import{createHash as Bk}from"node:crypto";import{promises as qa}from"node:fs";import rt from"node:path";D();oe();G();A();var Bi=/^[a-f0-9]{64}$/u,yp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Vk=16*1024,zc=process.platform;function Sp(e,t){let r=rt.relative(e,t);return rt.isAbsolute(r)||r===".."||r.startsWith(`..${rt.sep}`)?null:r.replaceAll("\\","/")||"."}function Ep(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function xp(e,t){if(e.length===0||Ep(e)||e.includes("\\")||rt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=rt.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Jc(e,t){return Bk("sha256").update(`${e}
148
148
  ${t}`).digest("hex")}async function Np(e,t){let r=await qa.realpath(t),i=await qa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=zc==="win32"?rt.normalize(r).toLowerCase():r;return Jc(e,`${n}
149
149
  ${i.dev}
150
150
  ${i.ino}
151
- ${i.birthtimeMs}`)}async function bp(e,t){let r=await qa.realpath(t),i=await qa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=zc==="win32"?rt.normalize(r).toLowerCase():r;return Jc(e,n)}function Mk(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 Wc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ep(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function xp(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Wc(e.changeBranch,"Native workspace change branch"),Wc(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 Wk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!yp.test(t.baseCommit)||typeof t.targetCommit!="string"||!yp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Wc(t.targetBranch,"Native workspace Git target branch")}function Fa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.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"||!Bi.test(String(t.projectRootId))||!Bi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Mk(t.capturedAt),Cp(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&&!Bi.test(String(t.projectRootPathId))||a&&!Bi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Bi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Wk(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(xp(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 zk(e,t){return rt.join(Y(e,t),"workspace.json")}function Jk(e,t){let r=zk(e,t),i=Ce(e,r),n=Sp(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Cp(n,"Native workspace file ref")}}async function Gk(e,t){try{let r=Jk(e,t),i=await H({root:r.root,ref:r.ref,maxBytes:Vk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Gc(e,t){let r=W(e.projectRoot),i={projectRoot:rt.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await Vi(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await La({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Uk(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Sp(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=W(e.paths.projectRoot),i=r.isGitWorktree?Ke(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Ke(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,d]=await Promise.all([Np("comet.native.workspace-project-root.v2",e.paths.projectRoot),Np("comet.native.workspace-native-root.v2",e.paths.nativeRoot),bp("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),bp("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),u=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&xp(e.binding);let f={capturedAt:u,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:d,...o?{git:o}:{},...e.sessionId?{sessionHash:Jc("comet.native.workspace-session.v2",`${s}
151
+ ${i.birthtimeMs}`)}async function bp(e,t){let r=await qa.realpath(t),i=await qa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=zc==="win32"?rt.normalize(r).toLowerCase():r;return Jc(e,n)}function Mk(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 Wc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ep(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Cp(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Wc(e.changeBranch,"Native workspace change branch"),Wc(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 Wk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!yp.test(t.baseCommit)||typeof t.targetCommit!="string"||!yp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Wc(t.targetBranch,"Native workspace Git target branch")}function Fa(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.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"||!Bi.test(String(t.projectRootId))||!Bi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Mk(t.capturedAt),xp(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&&!Bi.test(String(t.projectRootPathId))||a&&!Bi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Bi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Wk(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(Cp(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 zk(e,t){return rt.join(Y(e,t),"workspace.json")}function Jk(e,t){let r=zk(e,t),i=xe(e,r),n=Sp(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:xp(n,"Native workspace file ref")}}async function Gk(e,t){try{let r=Jk(e,t),i=await H({root:r.root,ref:r.ref,maxBytes:Vk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Gc(e,t){let r=W(e.projectRoot),i={projectRoot:rt.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await Vi(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await La({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Uk(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Sp(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=W(e.paths.projectRoot),i=r.isGitWorktree?Ke(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Ke(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,d]=await Promise.all([Np("comet.native.workspace-project-root.v2",e.paths.projectRoot),Np("comet.native.workspace-native-root.v2",e.paths.nativeRoot),bp("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),bp("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),u=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&Cp(e.binding);let f={capturedAt:u,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:d,...o?{git:o}:{},...e.sessionId?{sessionHash:Jc("comet.native.workspace-session.v2",`${s}
152
152
  ${c}
153
- ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Fa(h),h}async function Vi(e,t){let r=await Gk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Fa(r),r)}async function Uc(e){Fa(e.identity);let t=await Uk({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),zc==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function La(e){if(Fa(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 Uc(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=W(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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"}}Ri();xa();xa();var Ba=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Mi=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Va=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;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"},vj=sa("en");function te(e,t){Ut(t);let r=_r.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Yc(e,t){let r=Y(e,t),i=_r.join(r,"schema-migration.json");await L(z(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Xk.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Qk(e,t=_r.dirname(e)){let r=_r.relative(t,e).split(_r.sep).join("/"),i=await H({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Kc.parseDocument)(i.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 Xc(e,t){let r=_r.join(te(e,t),tt);await L(e.nativeRoot,r);let i=Pc(await Qk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Yc(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await Zk(e,i.state),i)}async function Zk(e,t){if(await Vc(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}oe();var Gp=Je(De(),1);import{promises as $S}from"node:fs";import Te from"node:path";Ie();oe();q();fe();A();Pe();za();za();Qt();It();Ie();Ca();D();q();Qa();G();A();Vp();Qt();It();Za();Ie();fe();Za();Pi();A();var eo=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function ol(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}import IS from"node:path";Ie();fe();G();Qt();It();async function to(e){let t=ol(e.parent),r=Ke(e.paths.projectRoot,t);if(!r)return null;let i=Ke(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=wt(e.paths.projectRoot).map(o=>IS.resolve(o)).find(o=>W(o).currentBranch===t);if(!n)return null;let a=Ka({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return rl(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function sl(e,t){let r=Te.normalize(Te.resolve(e)),i=Te.normalize(Te.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function OS(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function HS(e){let t=OS(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function cl(e){try{let t=await H({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return HS(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ll(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function DS(e){let t=wt(e.projectRoot);t.some(i=>sl(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Te.resolve(n)))]){let n=await le(i);n&&r.push({projectRoot:i,paths:await Be(i,n.native.artifact_root),parent:sl(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function qS(e,t){let r=Te.join(e.paths.changesDir,t,"comet-state.yaml");try{return await xt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function FS(e,t){let r;try{r=await $S.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Te.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await xt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function LS(e,t,r){let i=Te.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Te.sep}`))return null;let n=i.split(Te.sep).join("/");try{let a=(0,Gp.parseDocument)(pe(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ue(a.toJS({mapAsMap:!1}))}catch{return null}}function BS(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||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 ${r??"(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 Jp(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ir(e){let t=Te.join(e.paths.changesDir,e.state.name),r=await cl(t),i=null,n;try{n=await it({changeDir:t,validation:_t(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,n=null}if(!n){let v=await je(e.paths,e.state.name,{diagnostics:!0});if(v){let b=Ya(v);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(N=>({...N,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=ll({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Rt){let v=await je(e.paths,e.state.name,{diagnostics:!0});if(!v){let y=e.state.workspace.change_branch??e.state.workspace.target_branch;if(y){let E=await to({paths:e.paths,parent:e.state.name,targetBranch:y,contract:n.contract});E&&(v=E,await At(e.paths,E))}}if(v){let y=Ya(v);return e.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let b=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(E=>n.contract.children.filter(({name:w})=>w!==y.name).every(({name:w})=>w!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await DS(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),d=new Map,u=new Map;for(let v of c){let b=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await FS(v,l)){let y={...N,source:v,committedState:LS(v,N.file,b)};d.set(N.state.name,[...d.get(N.state.name)??[],y])}for(let N of l){let y=await qS(v,N);y&&u.set(N,[...u.get(N)??[],{source:v,state:y}])}}let f=new Map;for(let v of n.contract.children){let b=(d.get(v.name)??[]).find(({source:E,committedState:w})=>E.parent&&w?.name===v.name&&Jp(w,o));if(b){f.set(v.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let N=d.get(v.name)?.[0];if(N){f.set(v.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=u.get(v.name)??[];y.length>1?f.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):y[0]&&f.set(v.name,BS(y[0].state,y[0].source,o))}let h=new Map(n.contract.children.map(v=>[v.name,v])),m=new Map,p=v=>{let b=m.get(v);if(b)return b;let N=h.get(v),E=N.depends_on.map(p).every(({status:Ne})=>Ne==="done"),w=f.get(v),R=w?.kind==="active"&&E?N.depends_on.filter(Ne=>!(d.get(Ne)??[]).some(({source:F,committedState:qr})=>sl(F.projectRoot,w.projectRoot)&&qr?.name===Ne&&Jp(qr,o))):[],S,I=w?.message??null;w?.kind==="done"?(S=E?"done":"blocked",E||(I=`Native child ${v} was merged before its dependencies`)):w?.kind==="active"?(S=E&&R.length===0?"active":"blocked",E?R.length>0&&(I=`Native child ${v} does not include merged dependencies: ${R.join(", ")}`):I=`Native child ${v} started before its dependencies merged`):w?.kind==="blocked"?S="blocked":(S=s&&E?"ready":"pending",s||(I="Parent Shape confirmation is required"));let K={name:v,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:S,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:I};return m.set(v,K),K},g=n.contract.children.map(({name:v})=>p(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}import{promises as eh}from"fs";import th from"path";Mt();oe();Ae();A();var VS=["outcome","scope","nonGoals","acceptanceExamples"],J$=[...VS,"constraints","decisions","openQuestions","verificationExpectations"];oe();D();Ae();A();ge();gi();jt();G();D();Ae();Pi();G();A();ge();jt();q();q();ro();er();Ae();var Yp={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},GS=de("comet-native-runtime:v3:scope-reopen"),PO=[{skillVersion:"3",skillHash:de("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:de("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:de("comet-native-runtime:v1")}];Ae();Ae();Ri();var Qp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],o0=new Set(Qp),QS=new Set([...Qp,"minimum_runtime_version","revision"]),s0=new Set([...QS,"operation"]),ZS=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),c0=new Set([...ZS,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Ae();G();ge();jt();A();oe();$i();q();var C0={maxAcceptanceCriteria:ep.maxCriteria};var fl={maxSpecs:64};var rh=fl.maxSpecs*4;async function rE(e,t){let r=th.join(te(e,t),"specs"),i;try{i=await Li({root:e.nativeRoot,directory:r,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await eh.opendir(r);try{for await(let s of o){if(a+=1,a>rh)throw new Error(`Native proposed specs directory exceeds ${rh} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Ut(s.name);let c=th.join(r,s.name,"spec.md");await L(e.nativeRoot,c);let l;try{l=await eh.lstat(c)}catch(d){if(d.code==="ENOENT")continue;throw d}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>fl.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await i.verify(),n.sort()}async function nh(e,t){let r=te(e,t),i={};for(let n of await rE(e,t)){let a=await H({root:r,ref:`specs/${n}/spec.md`,maxBytes:null});i[n]=a.text}return i}Oi();Qt();function re(e,t,r){return e.language==="zh-CN"?r:t}function iE(e,t,r){let i=n=>({required:!1,message:null,suggestedReply:null,agentInstruction:n});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:re(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:re(e,"Reply A or B","回复 A 或 B"),agentInstruction:re(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(re(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(re(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:n})=>n==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let a=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",o=a?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=a?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:o,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:re(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:re(e,"Accept the result","接受结果"),agentInstruction:re(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=Ua)??!1;return n&&!a&&!o&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(re(e,"Implement the confirmed scope and run focused checks. A separate pre-review is optional, not a prerequisite for Builder handoff. If review is useful, retain the same Reviewer for focused repair follow-ups rather than starting repeated full reviews. Submit the stable candidate for one complete independent verification; release completed helper tasks.","实现已确认范围并运行相关检查。额外预审是可选项,不是 Builder 交接的前置条件。确有必要审查时,保留同一个 Reviewer 复核修复及受影响范围,避免反复启动完整审查。候选稳定后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(re(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function nE(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function aE(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:re(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:re(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function ch(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function rr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ah(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function oE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function oh(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function sE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function cE(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Tt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:ch({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[rr("summary","--summary"),oE(e.name,e.flag)]}}function sh(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:re(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function lE(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function ao(e){return[Tt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Tt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function uE(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function jr(e,t,r={}){let i=sE(t)&&e.coordination_mode===void 0,n=iE(e,i,t),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...ao({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Tt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...ao({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:ao({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:ao({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?ch({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:cE({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[oh("coordination-mode","--coordination-mode",tp)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,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:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"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}],verification_checks:[ah()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),d=t.children.some(({status:m})=>m==="ready"||m==="active"),u=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Ua)??null,f=u===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:u.name,stateVersion:t.supervisorStateVersion},description:re(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},h=c&&!l&&!d&&f===null;return{...a,disposition:h?"blocked":"continue",action:"advance-children",commandArgs:h?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:h?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:h?[]:f!==null?[f]:[rr("summary","--summary")],runnerAction:o("none")}}return{...a,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}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=ah();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${re(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:uE([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(d=>({...d,argv:[...d.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let d=sh(e,r.archiveBlockers)[0];return d&&r.archiveBlockers.every(u=>lE(u))?{...a,disposition:"continue",action:"repair",commandArgs:d.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:sh(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[oh("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...aE(e)],userCommunication:nE(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Tt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}Ie();Ca();q();Qa();import Dr from"node:path";Pe();Yt();Wi();Ga();import{promises as fE}from"node:fs";D();Oi();import lh from"node:path";function Gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ui(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ie(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Tr(e,t){return e===null?null:ie(e,t)}function $r(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function pE(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 hE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Or(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function hl(e,t){if(e===null)return null;let r=ie(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function mE(e,t){let r=ie(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function ml(e,t){let r=ie(e,t);if(!lh.isAbsolute(r))throw new Error(`${t} must be absolute`);return lh.resolve(r)}function vE(e,t){let r=`Native local checks[${t}]`,i=Gi(e,r);if(Ui(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((d,u)=>ie(d,`${r}.argv[${u}]`,!0)),a=Or(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=hl(i.startedAt,`${r}.startedAt`),s=hl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=$r(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let d=Gi(i.activeProcess,`${r}.activeProcess`),u=Or(d.status,["starting","running"],`${r}.activeProcess.status`);if(Ui(d,new Set(["status","pid","identity"]),`${r}.activeProcess`),u==="starting"){if(Object.hasOwn(d,"pid")||Object.hasOwn(d,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:$r(d.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(d,"identity")?{identity:ie(d.identity,`${r}.activeProcess.identity`)}:{}}}return{id:ie(i.id,`${r}.id`),name:ie(i.name,`${r}.name`),operationId:ie(i.operationId,`${r}.operationId`),status:a,repeatable:hE(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:$r(i.executionCount,`${r}.executionCount`),argv:n,cwd:ml(i.cwd,`${r}.cwd`),exitCode:pE(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:ie(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Or(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:ie(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function gE(e){let t="Native local execution state",r=Gi(e,t);if(Ui(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Pa)throw new Error(`Native local execution schema must be ${Pa}`);let i=Gi(r.workspace,"Native local workspace");Ui(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Gi(r.execution,"Native local execution");Ui(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=hl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:ie(o.operationId,"Native local execution.operationId"),stage:Or(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Or(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Tr(o.executionId,"Native local execution.executionId"),status:Or(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:$r(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:mE(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:$r(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:ie(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(vE);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:Pa,change:ie(r.change,"Native local change"),basedOnStateVersion:$r(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Tr(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Tr(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Tr(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Tr(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:ml(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ml(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Tr(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:ie(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function oo(e){let t;try{t=await fE.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return gE(r)}function vl(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}G();Yt();A();import{promises as wE}from"node:fs";import gl from"node:path";Ie();Pe();A();var uh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dh="comet-state.yaml",fh="state.json";function at(e,t){if(!uh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=gl.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}function so(e,t){return gl.join(at(e,t),dh)}function $t(e,t){return gl.join(Ve(e,t),fh)}async function Hr(e,t){try{let r=await wE.readFile(so(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function $e(e,t){return xt(so(e,t))}async function co(e){let t=await $e(e.paths,e.name),r=$t(e.paths,e.name);try{let i=await oo(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}D();oe();q();G();Ac();Sc();Pe();Yt();D();Mt();Wi();A();Mt();Ot();fe();var mh=Je(De(),1);St();var WH=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var YH=256*1024;Pe();Yt();It();var _E=sa("en");function IE(e,t){let r=Dr.relative(Dr.resolve(e),Dr.resolve(t));if(Dr.isAbsolute(r)||r===".."||r.startsWith(`..${Dr.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Dr.sep).join("/");return Bp(e,i),i}function Nl(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:IE(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var cq=1024*1024*1024;fe();G();Qt();It();Pe();Yt();G();Ga();Wi();It();G();It();G();Dc();Ei();import tn from"path";import{realpathSync as uC}from"fs";function Nh(e,t){let r=d=>d!==null&&typeof d=="object"&&!Array.isArray(d)?d:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var ot={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function bh(e){return e?e.command?`${ot.next} ${e.command}`:e.ask_user?`${ot.next} ${e.ask_user}`:null:null}function kh(e,t){let r=[e.summary],i=bh(e.next);return i&&r.push(i),e.user_message&&r.push("",ot.relay,e.user_message),t!==void 0&&r.push("",ot.details,JSON.stringify(t,null,2)),`${r.join(`
153
+ ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Fa(h),h}async function Vi(e,t){let r=await Gk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Fa(r),r)}async function Uc(e){Fa(e.identity);let t=await Uk({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),zc==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function La(e){if(Fa(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 Uc(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=W(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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"}}Ri();Ca();Ca();var Ba=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Mi=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Va=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;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"},vj=sa("en");function te(e,t){Ut(t);let r=_r.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Yc(e,t){let r=Y(e,t),i=_r.join(r,"schema-migration.json");await L(z(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Xk.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Qk(e,t=_r.dirname(e)){let r=_r.relative(t,e).split(_r.sep).join("/"),i=await H({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Kc.parseDocument)(i.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 Xc(e,t){let r=_r.join(te(e,t),tt);await L(e.nativeRoot,r);let i=Pc(await Qk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Yc(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await Zk(e,i.state),i)}async function Zk(e,t){if(await Vc(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}oe();var Gp=Je(De(),1);import{promises as $S}from"node:fs";import Te from"node:path";Ie();oe();q();fe();A();Pe();za();za();Qt();It();Ie();xa();D();q();Qa();G();A();Vp();Qt();It();Za();Ie();fe();Za();Pi();A();var eo=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function ol(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}import IS from"node:path";Ie();fe();G();Qt();It();async function to(e){let t=ol(e.parent),r=Ke(e.paths.projectRoot,t);if(!r)return null;let i=Ke(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=wt(e.paths.projectRoot).map(o=>IS.resolve(o)).find(o=>W(o).currentBranch===t);if(!n)return null;let a=Ka({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return rl(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function sl(e,t){let r=Te.normalize(Te.resolve(e)),i=Te.normalize(Te.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function OS(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function HS(e){let t=OS(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function cl(e){try{let t=await H({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return HS(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ll(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function DS(e){let t=wt(e.projectRoot);t.some(i=>sl(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Te.resolve(n)))]){let n=await le(i);n&&r.push({projectRoot:i,paths:await Be(i,n.native.artifact_root),parent:sl(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function qS(e,t){let r=Te.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ct(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function FS(e,t){let r;try{r=await $S.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Te.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ct(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function LS(e,t,r){let i=Te.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Te.sep}`))return null;let n=i.split(Te.sep).join("/");try{let a=(0,Gp.parseDocument)(pe(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ue(a.toJS({mapAsMap:!1}))}catch{return null}}function BS(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||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 ${r??"(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 Jp(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ir(e){let t=Te.join(e.paths.changesDir,e.state.name),r=await cl(t),i=null,n;try{n=await it({changeDir:t,validation:_t(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,n=null}if(!n){let v=await je(e.paths,e.state.name,{diagnostics:!0});if(v){let b=Ya(v);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(N=>({...N,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=ll({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Rt){let v=await je(e.paths,e.state.name,{diagnostics:!0});if(!v){let y=e.state.workspace.change_branch??e.state.workspace.target_branch;if(y){let E=await to({paths:e.paths,parent:e.state.name,targetBranch:y,contract:n.contract});E&&(v=E,await At(e.paths,E))}}if(v){let y=Ya(v);return e.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let b=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(E=>n.contract.children.filter(({name:w})=>w!==y.name).every(({name:w})=>w!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await DS(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),d=new Map,u=new Map;for(let v of c){let b=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await FS(v,l)){let y={...N,source:v,committedState:LS(v,N.file,b)};d.set(N.state.name,[...d.get(N.state.name)??[],y])}for(let N of l){let y=await qS(v,N);y&&u.set(N,[...u.get(N)??[],{source:v,state:y}])}}let f=new Map;for(let v of n.contract.children){let b=(d.get(v.name)??[]).find(({source:E,committedState:w})=>E.parent&&w?.name===v.name&&Jp(w,o));if(b){f.set(v.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let N=d.get(v.name)?.[0];if(N){f.set(v.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=u.get(v.name)??[];y.length>1?f.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):y[0]&&f.set(v.name,BS(y[0].state,y[0].source,o))}let h=new Map(n.contract.children.map(v=>[v.name,v])),m=new Map,p=v=>{let b=m.get(v);if(b)return b;let N=h.get(v),E=N.depends_on.map(p).every(({status:Ne})=>Ne==="done"),w=f.get(v),R=w?.kind==="active"&&E?N.depends_on.filter(Ne=>!(d.get(Ne)??[]).some(({source:F,committedState:qr})=>sl(F.projectRoot,w.projectRoot)&&qr?.name===Ne&&Jp(qr,o))):[],S,I=w?.message??null;w?.kind==="done"?(S=E?"done":"blocked",E||(I=`Native child ${v} was merged before its dependencies`)):w?.kind==="active"?(S=E&&R.length===0?"active":"blocked",E?R.length>0&&(I=`Native child ${v} does not include merged dependencies: ${R.join(", ")}`):I=`Native child ${v} started before its dependencies merged`):w?.kind==="blocked"?S="blocked":(S=s&&E?"ready":"pending",s||(I="Parent Shape confirmation is required"));let K={name:v,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:S,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:I};return m.set(v,K),K},g=n.contract.children.map(({name:v})=>p(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}import{promises as eh}from"fs";import th from"path";Mt();oe();Ae();A();var VS=["outcome","scope","nonGoals","acceptanceExamples"],J$=[...VS,"constraints","decisions","openQuestions","verificationExpectations"];oe();D();Ae();A();ge();gi();jt();G();D();Ae();Pi();G();A();ge();jt();q();q();ro();er();Ae();var Yp={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},GS=de("comet-native-runtime:v3:scope-reopen"),PO=[{skillVersion:"3",skillHash:de("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:de("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:de("comet-native-runtime:v1")}];Ae();Ae();Ri();var Qp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],o0=new Set(Qp),QS=new Set([...Qp,"minimum_runtime_version","revision"]),s0=new Set([...QS,"operation"]),ZS=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),c0=new Set([...ZS,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Ae();G();ge();jt();A();oe();$i();q();var x0={maxAcceptanceCriteria:ep.maxCriteria};var fl={maxSpecs:64};var rh=fl.maxSpecs*4;async function rE(e,t){let r=th.join(te(e,t),"specs"),i;try{i=await Li({root:e.nativeRoot,directory:r,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await eh.opendir(r);try{for await(let s of o){if(a+=1,a>rh)throw new Error(`Native proposed specs directory exceeds ${rh} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Ut(s.name);let c=th.join(r,s.name,"spec.md");await L(e.nativeRoot,c);let l;try{l=await eh.lstat(c)}catch(d){if(d.code==="ENOENT")continue;throw d}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>fl.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await i.verify(),n.sort()}async function nh(e,t){let r=te(e,t),i={};for(let n of await rE(e,t)){let a=await H({root:r,ref:`specs/${n}/spec.md`,maxBytes:null});i[n]=a.text}return i}Oi();Qt();function re(e,t,r){return e.language==="zh-CN"?r:t}function iE(e,t,r){let i=n=>({required:!1,message:null,suggestedReply:null,agentInstruction:n});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:re(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:re(e,"Reply A or B","回复 A 或 B"),agentInstruction:re(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(re(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(re(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:n})=>n==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let a=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",o=a?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=a?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:o,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:re(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:re(e,"Accept the result","接受结果"),agentInstruction:re(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=Ua)??!1;return n&&!a&&!o&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(re(e,"Implement the confirmed scope and run focused checks. A separate pre-review is optional, not a prerequisite for Builder handoff. If review is useful, retain the same Reviewer for focused repair follow-ups rather than starting repeated full reviews. Submit the stable candidate for one complete independent verification; release completed helper tasks.","实现已确认范围并运行相关检查。额外预审是可选项,不是 Builder 交接的前置条件。确有必要审查时,保留同一个 Reviewer 复核修复及受影响范围,避免反复启动完整审查。候选稳定后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(re(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function nE(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function aE(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:re(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:re(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function ch(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function rr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ah(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function oE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function oh(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function sE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function cE(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Tt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:ch({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[rr("summary","--summary"),oE(e.name,e.flag)]}}function sh(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:re(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function lE(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function ao(e){return[Tt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Tt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function uE(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function jr(e,t,r={}){let i=sE(t)&&e.coordination_mode===void 0,n=iE(e,i,t),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...ao({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Tt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:[Tt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...ao({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[rr("summary","--summary")],commandAlternatives:ao({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:ao({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?ch({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:cE({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[oh("coordination-mode","--coordination-mode",tp)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,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:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"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}],verification_checks:[ah()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),d=t.children.some(({status:m})=>m==="ready"||m==="active"),u=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Ua)??null,f=u===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:u.name,stateVersion:t.supervisorStateVersion},description:re(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},h=c&&!l&&!d&&f===null;return{...a,disposition:h?"blocked":"continue",action:"advance-children",commandArgs:h?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:h?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:h?[]:f!==null?[f]:[rr("summary","--summary")],runnerAction:o("none")}}return{...a,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}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=ah();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${re(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:uE([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(d=>({...d,argv:[...d.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let d=sh(e,r.archiveBlockers)[0];return d&&r.archiveBlockers.every(u=>lE(u))?{...a,disposition:"continue",action:"repair",commandArgs:d.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:sh(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[oh("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...aE(e)],userCommunication:nE(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Tt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}Ie();xa();q();Qa();import Dr from"node:path";Pe();Yt();Wi();Ga();import{promises as fE}from"node:fs";D();Oi();import lh from"node:path";function Gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ui(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ie(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Tr(e,t){return e===null?null:ie(e,t)}function $r(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function pE(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 hE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Or(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function hl(e,t){if(e===null)return null;let r=ie(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function mE(e,t){let r=ie(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function ml(e,t){let r=ie(e,t);if(!lh.isAbsolute(r))throw new Error(`${t} must be absolute`);return lh.resolve(r)}function vE(e,t){let r=`Native local checks[${t}]`,i=Gi(e,r);if(Ui(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((d,u)=>ie(d,`${r}.argv[${u}]`,!0)),a=Or(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=hl(i.startedAt,`${r}.startedAt`),s=hl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=$r(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let d=Gi(i.activeProcess,`${r}.activeProcess`),u=Or(d.status,["starting","running"],`${r}.activeProcess.status`);if(Ui(d,new Set(["status","pid","identity"]),`${r}.activeProcess`),u==="starting"){if(Object.hasOwn(d,"pid")||Object.hasOwn(d,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:$r(d.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(d,"identity")?{identity:ie(d.identity,`${r}.activeProcess.identity`)}:{}}}return{id:ie(i.id,`${r}.id`),name:ie(i.name,`${r}.name`),operationId:ie(i.operationId,`${r}.operationId`),status:a,repeatable:hE(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:$r(i.executionCount,`${r}.executionCount`),argv:n,cwd:ml(i.cwd,`${r}.cwd`),exitCode:pE(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:ie(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Or(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:ie(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function gE(e){let t="Native local execution state",r=Gi(e,t);if(Ui(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Pa)throw new Error(`Native local execution schema must be ${Pa}`);let i=Gi(r.workspace,"Native local workspace");Ui(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Gi(r.execution,"Native local execution");Ui(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=hl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:ie(o.operationId,"Native local execution.operationId"),stage:Or(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Or(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Tr(o.executionId,"Native local execution.executionId"),status:Or(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:$r(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:mE(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:$r(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:ie(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(vE);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:Pa,change:ie(r.change,"Native local change"),basedOnStateVersion:$r(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Tr(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Tr(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Tr(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Tr(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:ml(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ml(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Tr(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:ie(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function oo(e){let t;try{t=await fE.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return gE(r)}function vl(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}G();Yt();A();import{promises as wE}from"node:fs";import gl from"node:path";Ie();Pe();A();var uh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dh="comet-state.yaml",fh="state.json";function at(e,t){if(!uh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=gl.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}function so(e,t){return gl.join(at(e,t),dh)}function $t(e,t){return gl.join(Ve(e,t),fh)}async function Hr(e,t){try{let r=await wE.readFile(so(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function $e(e,t){return Ct(so(e,t))}async function co(e){let t=await $e(e.paths,e.name),r=$t(e.paths,e.name);try{let i=await oo(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}D();oe();q();G();Ac();Sc();Pe();Yt();D();Mt();Wi();A();Mt();Ot();fe();var mh=Je(De(),1);St();var WH=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var YH=256*1024;Pe();Yt();It();var _E=sa("en");function IE(e,t){let r=Dr.relative(Dr.resolve(e),Dr.resolve(t));if(Dr.isAbsolute(r)||r===".."||r.startsWith(`..${Dr.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Dr.sep).join("/");return Bp(e,i),i}function Nl(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:IE(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var cq=1024*1024*1024;fe();G();Qt();It();Pe();Yt();G();Ga();Wi();It();G();It();G();Dc();Ei();import tn from"path";import{realpathSync as ux}from"fs";function Nh(e,t){let r=d=>d!==null&&typeof d=="object"&&!Array.isArray(d)?d:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var ot={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function bh(e){return e?e.command?`${ot.next} ${e.command}`:e.ask_user?`${ot.next} ${e.ask_user}`:null:null}function kh(e,t){let r=[e.summary],i=bh(e.next);return i&&r.push(i),e.user_message&&r.push("",ot.relay,e.user_message),t!==void 0&&r.push("",ot.details,JSON.stringify(t,null,2)),`${r.join(`
154
154
  `)}
155
155
  `}function Sh(e,t,r){let i=[e.summary],n=bh(e.next);return n&&i.push(n),e.user_message&&i.push("",ot.relay,e.user_message),i.push("",`${ot.detail} ${t}`),r!==void 0&&i.push("",ot.details,JSON.stringify(r,null,2)),i.join(`
156
- `)}q();oe();q();var TE=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});Ot();ge();fe();A();$i();oe();Ot();Rr();er();ro();import{execFile as FE}from"node:child_process";Sa();al();import{promisify as LE}from"node:util";D();wl();A();qe();Ot();G();jt();var en=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Rr();Ki();er();var sB=64*1024;var cB=3600*1e3;var lB=LE(FE);Ki();var uo=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};Ae();ge();D();qe();A();ge();Oa();D();Mt();Ot();var sV=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ae();Pi();G();A();ge();fe();G();var hV=16*1024;Oa();var fo=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},po=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};A();fe();function x(e,t,r){return e==="zh-CN"?r:t}var Sl={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function xh(e,t){return typeof e=="string"&&Sl[e]?x(t,Sl[e].en,Sl[e].zh):typeof e=="string"?e:""}function El(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function KE(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Ph(e,t){let r=[];e.failed>0&&r.push(x(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(x(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(x(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=x(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Rh(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Cl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function YE(e,t,r){return e==="done"?x(r,"complete","已完成"):e==="await-user"?x(r,"waiting for a user decision","等待用户决定"):e==="blocked"?x(r,"paused: needs attention","已暂停,需要处理"):t?x(r,"waiting for a user decision","等待用户决定"):x(r,"ready to continue","可继续推进")}function XE(e,t,r){let i=Cl(e),n=[];r&&n.push(r);let a=x(i,`Change ${e.change}`,`需求 ${e.change}`),o=xh(e.phase,i),s=YE(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Ph(t,i));let c=e.userCommunication,l=_h(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function _h(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:x(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:x(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:x(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function QE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function ZE(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=xh(e.phase,t),n=e.status==="await-user"?x(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?x(t,"paused","已暂停"):e.status==="done"?x(t,"complete","已完成"):x(t,"in progress","进行中"),a=El(e.acceptance)?`${x(t,", ",",")}${Ph(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function eC(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function tC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function rC(e){if(e.healthy){let i=e.repaired?x("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):x("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=iC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:x("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:x("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function iC(e){return Rh(e)?_h(e,Cl(e)):void 0}function Ah(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(tC(t))return rC(t);if(QE(t)){let i=eC(t.items);return{summary:[t.total===t.items.length?x(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):x(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>ZE(a,i))].join(`
157
- `)}}let r=t.continuation;if(Rh(r)){let i=Cl(r),n=XE(r,nC(t),oC(t,i));return aC(t)==="unconfirmed"?{...n,summary:`${n.summary}${x(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:x(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function nC(e){if(El(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(El(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return KE(r.acceptance)}return null}function aC(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function oC(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return x(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?x(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ih(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:x("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:x("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:x("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:x("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:x("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:x("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:x("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:x("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:x("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}tl();var jh=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],xl=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","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:jh,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
156
+ `)}q();oe();q();var TE=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});Ot();ge();fe();A();$i();oe();Ot();Rr();er();ro();import{execFile as FE}from"node:child_process";Sa();al();import{promisify as LE}from"node:util";D();wl();A();qe();Ot();G();jt();var en=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Rr();Ki();er();var sB=64*1024;var cB=3600*1e3;var lB=LE(FE);Ki();var uo=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};Ae();ge();D();qe();A();ge();Oa();D();Mt();Ot();var sV=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ae();Pi();G();A();ge();fe();G();var hV=16*1024;Oa();var fo=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},po=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};A();fe();function C(e,t,r){return e==="zh-CN"?r:t}var Sl={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Ch(e,t){return typeof e=="string"&&Sl[e]?C(t,Sl[e].en,Sl[e].zh):typeof e=="string"?e:""}function El(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function KE(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Ph(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Rh(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function xl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function YE(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function XE(e,t,r){let i=xl(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=Ch(e.phase,i),s=YE(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Ph(t,i));let c=e.userCommunication,l=_h(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function _h(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function QE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function ZE(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Ch(e.phase,t),n=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=El(e.acceptance)?`${C(t,", ",",")}${Ph(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function ex(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function tx(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function rx(e){if(e.healthy){let i=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=ix(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:C("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function ix(e){return Rh(e)?_h(e,xl(e)):void 0}function Ah(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(tx(t))return rx(t);if(QE(t)){let i=ex(t.items);return{summary:[t.total===t.items.length?C(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>ZE(a,i))].join(`
157
+ `)}}let r=t.continuation;if(Rh(r)){let i=xl(r),n=XE(r,nx(t),ox(t,i));return ax(t)==="unconfirmed"?{...n,summary:`${n.summary}${C(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:C(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function nx(e){if(El(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(El(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return KE(r.acceptance)}return null}function ax(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function ox(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ih(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:C("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:C("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}tl();var jh=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Cl=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","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:jh,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
158
158
  comet native spec remove <change-name> <capability>
159
159
  comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],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."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},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, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with canonical artifact paths and local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary 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> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
160
160
  comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
161
161
  comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, 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 the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--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 failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--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, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, verification_checks, known_limits, optional review. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan is reused without executing the same plan twice when dispatch-verifier receives the unchanged plan. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," 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."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". 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 --expected-state-version <n> --expected-action confirm-shape','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]
162
162
  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 Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--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, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; 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 ho(e,t){return`${e}:
163
163
  ${t.map(r=>` ${r}`).join(`
164
- `)}`}function sC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return xl[r]||t.length>1&&xl[t[0]]?.subcommands?r:t[0]}function cC(e=[]){let t=sC(e),r=xl[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",ho("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",ho("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...jh];return n&&n.length>0&&i.push("",ho("Options",n)),i.push("",`Output:
164
+ `)}`}function sx(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Cl[r]||t.length>1&&Cl[t[0]]?.subcommands?r:t[0]}function cx(e=[]){let t=sx(e),r=Cl[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",ho("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",ho("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...jh];return n&&n.length>0&&i.push("",ho("Options",n)),i.push("",`Output:
165
165
  ${r.output}`),r.examples&&i.push("",ho("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
166
166
  `)}
167
- `}}var lC=cC().usage;var $h=10*1024*1024,Ht=class extends Error{};function Rl(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Ht(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Oh(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Ht(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new Ht(`${t} requires a value`);return e.splice(i,2),n}function Hh(e){if(e.length>0)throw new Ht(`Unexpected argument: ${e[0]}`)}function Dh(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Ht(`${t} is required`);return r}function Pl(e,t){let r=tn.normalize(Th(e)),i=tn.normalize(Th(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Th(e){let t=tn.resolve(e);try{return uC.native(t)}catch{return t}}function dC(e){let t=tn.resolve(e),r=W(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=W(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Pl(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Pl(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Pl(process.cwd(),r.currentWorktreeRoot)?tn.resolve(process.cwd()):r.currentWorktreeRoot}async function qh(e){return e?dC(e):Na(process.cwd())}async function Fh(e){let t=await Wf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Lh(e){return JSON.stringify(e,null,2)+`
168
- `}function mo(e,t,r){return{command:e,exitCode:0,data:t,text:r??Lh(t)}}function fC(e,t){if(t instanceof Ja)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Ht)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof fo)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 po)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ba)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 Mi)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 eo)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Va)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 uo)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof en)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Bh(e,t){let r=fC(e,t),i=r.error;if(!i)return r;let n=Ih({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function pC(e,t,r=!1){let i=e.envelope??Ah(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:Nh(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
167
+ `}}var lx=cx().usage;var $h=10*1024*1024,Ht=class extends Error{};function Rl(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Ht(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Oh(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Ht(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new Ht(`${t} requires a value`);return e.splice(i,2),n}function Hh(e){if(e.length>0)throw new Ht(`Unexpected argument: ${e[0]}`)}function Dh(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Ht(`${t} is required`);return r}function Pl(e,t){let r=tn.normalize(Th(e)),i=tn.normalize(Th(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Th(e){let t=tn.resolve(e);try{return ux.native(t)}catch{return t}}function dx(e){let t=tn.resolve(e),r=W(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=W(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Pl(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Pl(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Pl(process.cwd(),r.currentWorktreeRoot)?tn.resolve(process.cwd()):r.currentWorktreeRoot}async function qh(e){return e?dx(e):Na(process.cwd())}async function Fh(e){let t=await Wf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Lh(e){return JSON.stringify(e,null,2)+`
168
+ `}function mo(e,t,r){return{command:e,exitCode:0,data:t,text:r??Lh(t)}}function fx(e,t){if(t instanceof Ja)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Ht)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof fo)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 po)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ba)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 Mi)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 eo)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Va)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 uo)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof en)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Bh(e,t){let r=fx(e,t),i=r.error;if(!i)return r;let n=Ih({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function px(e,t,r=!1){let i=e.envelope??Ah(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:Nh(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
169
169
  `}:e.error?{exitCode:e.exitCode,stderr:i?Sh(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:kh(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Lh(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
170
170
  ${ot.details}
171
171
  ${JSON.stringify(e.data,null,2)}
172
- `}:{exitCode:e.exitCode,stdout:e.text}}function hC(e,t,r=!1){let i=pC(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function Vh(e,t,r=!1){return hC(e,t,r).output}A();import ir from"node:path";import{realpathSync as PC}from"node:fs";q();fe();import{promises as vC}from"fs";$i();q();A();Rr();A();A();Ot();Ki();er();Ot();ge();A();var rn=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function Wh(e){let t;try{t=await Li({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await vC.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>rn.maxChanges))throw new Error(`Native status exceeds ${rn.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}A();var Al=Je(De(),1);Ie();q();oe();Pe();import{promises as gC}from"node:fs";import _l from"node:path";var vo=class extends Error{};async function Il(e,t){let r=await H({root:e.nativeRoot,ref:_l.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,Al.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new vo("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:ue(i)}}async function Jh(e,t,r){let i;try{i=await gC.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=_l.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await Il(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof vo)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function go(e){return T("comet.native.status-record.v1",e)}function zh(e){let t=_l.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=pe(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=ue((0,Al.parse)(pe(e.projectRoot,["show",`${r}:${t}`])));return go(i)===go(e.state)?r:null}catch{return null}}function Gh(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=zh(e),i=zh(t);if(!r||!i)return!1;try{return pe(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function Uh(e,t){return e.state.archived&&t.state.archived&&go(e.state)===go(t.state)}import Qh from"node:path";q();import Kh from"node:path";function Yh(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Xh(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:Yh(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:Yh(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>Kh.relative(t.projectRoot,Kh.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}A();function wC(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function yC(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function NC(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:kC(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:SC(i,r)}))]:[]]}function bC(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Zh(e,t,r=W(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:Qh.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function em(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=Xh(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...jr(t),disposition:"blocked",action:"archive",commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the reported Git blocker; do not treat this archived change as complete until it succeeds."},runnerAction:{...jr(t).runnerAction,kind:"none"}}:jr(t),c=e.details?NC(t,null,[]):[],l=yC(e.cursor,t.state_version,0),d=c.slice(l,l+32),u=l+d.length<c.length?wC(t.state_version,0,l+d.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:Gt(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:Qh.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:bC(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:d,nextCursor:u,nextPageArgs:u?["comet","native","status",t.name,"--details","--cursor",u,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function tm(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function kC(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:tm(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function SC(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:tm(e.summary,t)??""}}D();Ea();Ie();import{accessSync as fW,constants as pW,promises as jl}from"node:fs";import im from"node:path";Za();Ea();var rm="comet.native.workspace-finish.v1",nm="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",am=new RegExp(`^${nm}$`,"u"),EC=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function CC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==rm||typeof t.name!="string"||!am.test(t.name)||typeof t.transactionId!="string"||!EC.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!im.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}return{schema:rm,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function xC(e,t){if(!am.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return im.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function Tl(e,t,r={}){let i=xC(e,t);try{let n=await jl.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=CC(JSON.parse(await jl.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function om(e,t={}){let r;try{r=await jl.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${nm})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await Tl(e,a[1],t);o&&i.push(o)}return i}function wo(e,t){let r=ir.normalize($l(e)),i=ir.normalize($l(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function $l(e){let t=ir.resolve(e);try{return PC.native(t)}catch{return t}}async function sm(e,t){let r=[];for(let i of await Wh(e))t!==void 0&&i!==t||r.push({name:i,kind:await Hr(e,i)?"portable":"legacy"});return r}async function RC(e,t){let r=ir.resolve(e),i=ia(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>wo(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>ir.resolve(l)).sort()){let l=wo(c,r)?r:c,d=$l(l),u=process.platform==="win32"?d.toLowerCase():d;if(s.has(u))continue;s.add(u);let f=await le(l);if(!f)continue;let h=await Be(l,f.native.artifact_root);o.push({projectRoot:l,config:f,paths:h,gitContext:ec(l,i)??W(l),changes:await sm(h,t)})}if(o.length===0){let c=await le(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Be(e,c.native.artifact_root);o.push({projectRoot:ir.resolve(e),config:c,paths:l,gitContext:ec(e,i)??W(e),changes:await sm(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await Jh(c.paths,(d,u)=>c.archiveErrors.push({name:d,message:u}),t),t!==void 0&&(c.archives=c.archives.filter(({state:d})=>d.name===t),c.archiveErrors=c.archiveErrors.filter(({name:d})=>d===t));let l=(d,u)=>c.finishJournalErrors.push({name:d,message:u});c.finishJournals=t?[await Tl(c.paths,t,{onError:l})].filter(d=>d!==null):await om(c.paths,{onError:l})}return o}function cm(e,t){return e.workspace.bindingState==="aligned"?0:wo(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function _C(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:u,kind:f})=>{let h=u.finishJournalErrors?.find(({name:m})=>m===n);if(f==="portable")try{let m=await $e(u.paths,n);return{source:u,name:n,kind:f,workspace:Zh(u.paths,m,u.gitContext),portableStatus:null,inspectionError:h?.message??null,finishJournal:u.finishJournals?.find(({name:p})=>p===n)??null}}catch(m){return{source:u,name:n,kind:f,workspace:{projectRoot:u.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:u,name:n,kind:f,workspace:a.length>1?await Gc(u.paths,n):{projectRoot:u.projectRoot,currentBranch:u.gitContext.currentBranch,isSecondaryWorktree:u.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:h?.message??null}})),s=t.flatMap(u=>(u.archives??[]).filter(({state:f})=>f.name===n).map(f=>{let h=em({paths:u.paths,...f,finishJournal:u.finishJournals?.find(({name:m})=>m===n)??null});return{source:u,name:n,kind:"portable",workspace:h.workspace,portableStatus:h,inspectionError:u.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:f,finishJournal:u.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(u=>(u.archiveErrors??[]).filter(f=>f.name===n).map(f=>({source:u,error:f})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(u=>(u.finishJournalErrors??[]).filter(f=>f.name===n).map(f=>({source:u,error:f})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let u=t.find(h=>h.finishJournals?.some(({name:m})=>m===n)),f=u?.finishJournals?.find(({name:h})=>h===n);if(u&&f){i.push({source:u,name:n,kind:"portable",portableStatus:null,inspectionError:f.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:u.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:f.result?.message??"Native workspace finish record is orphaned."},finishJournal:f});continue}}if(s.length>0){for(let f of o)if(f.kind==="portable")try{f.record=await Il(f.source.paths,ir.join(f.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let u=s.find(f=>[...o,...s.filter(h=>!Uh(f.record,h.record))].every(h=>h.record&&Gh(f.record,h.record)));if(u){i.push(u);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((u,f)=>cm(u,e)-cm(f,e)||u.source.projectRoot.localeCompare(f.source.projectRoot));let d=o.filter(u=>u.workspace.bindingState==="aligned");d.length>1?i.push(...d):d.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(d[0]??o[0])}if(i.length>rn.maxChanges)throw new Error(`Native status discovery exceeds ${rn.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function AC(e,t){let r=await RC(e,t),i=(await _C(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}async function lm(e){let{sources:t,candidates:r}=await AC(e.projectRoot,e.name);return r.length>0?r[0].source.projectRoot:(t.find(i=>wo(i.projectRoot,e.projectRoot))??t[0]).projectRoot}async function um(e,t){let r=Dh(e,"change name");Hh(e);let i=await lm({projectRoot:t,name:r}),{paths:n}=await Fh(i);if(await Hr(n,r)){let u=await co({paths:n,name:r}),f=u.state,h=at(n,r),m=await H({root:h,ref:f.brief,maxBytes:null,includeHash:!1}),p=[];for(let v of f.spec_changes){if(v.source===null)continue;let b=await H({root:h,ref:v.source,maxBytes:null,includeHash:!1});p.push({capability:v.capability,operation:v.operation,source:v.source,content:b.text})}let g={state:f,artifacts:Gt(n,f.name),brief:m.text,proposedSpecs:p,continuation:jr(f,await Ir({paths:n,state:f}),{verifierExecutionRef:vl(f,u.local),...u.local?{verificationCheckPlans:Nl(u.local,u.local.workspace.projectRoot)}:{}})};return{...mo("show",g),executionCwd:i}}let a=await Xc(n,r);if(a.status==="migration-required")return{...mo("show",{name:r,artifacts:Gt(n,r),schema:a.schema,minimumRuntimeVersion:a.minimumRuntimeVersion,migrationRequired:!0,message:a.message}),executionCwd:i};if(a.status!=="current"||!a.state)throw new Me(a.schema,a.minimumRuntimeVersion);let o=a.state,s=te(n,r),c=await nh(n,r),l=await H({root:s,ref:o.brief,maxBytes:null}),d={state:o,artifacts:Gt(n,o.name),brief:l.text,proposedSpecs:c};if(Buffer.byteLength(JSON.stringify(d),"utf8")>$h)throw new Error("Native show output exceeds its serialized byte budget");return{...mo("show",d),executionCwd:i}}async function dm(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Rl(n,"--json"),Rl(n,"--verbose"),c=Oh(n,"--project-root");let u=[...n,...a],f=await qh(c);l={executionCwd:f,...await t(u,f)}}catch(u){l=Bh(e,u)}let d=Vh(l,o,s);return d.stdout&&process.stdout.write(d.stdout),d.stderr&&process.stderr.write(d.stderr+(d.stderr.endsWith(`
172
+ `}:{exitCode:e.exitCode,stdout:e.text}}function hx(e,t,r=!1){let i=px(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function Vh(e,t,r=!1){return hx(e,t,r).output}A();import ir from"node:path";import{realpathSync as Px}from"node:fs";q();fe();import{promises as vx}from"fs";$i();q();A();Rr();A();A();Ot();Ki();er();Ot();ge();A();var rn=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function Wh(e){let t;try{t=await Li({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await vx.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>rn.maxChanges))throw new Error(`Native status exceeds ${rn.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}A();var Al=Je(De(),1);Ie();q();oe();Pe();import{promises as gx}from"node:fs";import _l from"node:path";var vo=class extends Error{};async function Il(e,t){let r=await H({root:e.nativeRoot,ref:_l.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,Al.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new vo("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:ue(i)}}async function Jh(e,t,r){let i;try{i=await gx.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=_l.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await Il(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof vo)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function go(e){return T("comet.native.status-record.v1",e)}function zh(e){let t=_l.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=pe(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=ue((0,Al.parse)(pe(e.projectRoot,["show",`${r}:${t}`])));return go(i)===go(e.state)?r:null}catch{return null}}function Gh(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=zh(e),i=zh(t);if(!r||!i)return!1;try{return pe(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function Uh(e,t){return e.state.archived&&t.state.archived&&go(e.state)===go(t.state)}import Qh from"node:path";q();import Kh from"node:path";function Yh(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Xh(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:Yh(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:Yh(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>Kh.relative(t.projectRoot,Kh.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}A();function wx(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function yx(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function Nx(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:kx(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:Sx(i,r)}))]:[]]}function bx(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Zh(e,t,r=W(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:Qh.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function em(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=Xh(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...jr(t),disposition:"blocked",action:"archive",commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the reported Git blocker; do not treat this archived change as complete until it succeeds."},runnerAction:{...jr(t).runnerAction,kind:"none"}}:jr(t),c=e.details?Nx(t,null,[]):[],l=yx(e.cursor,t.state_version,0),d=c.slice(l,l+32),u=l+d.length<c.length?wx(t.state_version,0,l+d.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:Gt(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:Qh.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:bx(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:d,nextCursor:u,nextPageArgs:u?["comet","native","status",t.name,"--details","--cursor",u,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function tm(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function kx(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:tm(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function Sx(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:tm(e.summary,t)??""}}D();Ea();Ie();import{accessSync as fW,constants as pW,promises as jl}from"node:fs";import im from"node:path";Za();Ea();var rm="comet.native.workspace-finish.v1",nm="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",am=new RegExp(`^${nm}$`,"u"),Ex=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function xx(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==rm||typeof t.name!="string"||!am.test(t.name)||typeof t.transactionId!="string"||!Ex.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!im.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}return{schema:rm,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function Cx(e,t){if(!am.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return im.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function Tl(e,t,r={}){let i=Cx(e,t);try{let n=await jl.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=xx(JSON.parse(await jl.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function om(e,t={}){let r;try{r=await jl.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${nm})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await Tl(e,a[1],t);o&&i.push(o)}return i}function wo(e,t){let r=ir.normalize($l(e)),i=ir.normalize($l(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function $l(e){let t=ir.resolve(e);try{return Px.native(t)}catch{return t}}async function sm(e,t){let r=[];for(let i of await Wh(e))t!==void 0&&i!==t||r.push({name:i,kind:await Hr(e,i)?"portable":"legacy"});return r}async function Rx(e,t){let r=ir.resolve(e),i=ia(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>wo(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>ir.resolve(l)).sort()){let l=wo(c,r)?r:c,d=$l(l),u=process.platform==="win32"?d.toLowerCase():d;if(s.has(u))continue;s.add(u);let f=await le(l);if(!f)continue;let h=await Be(l,f.native.artifact_root);o.push({projectRoot:l,config:f,paths:h,gitContext:ec(l,i)??W(l),changes:await sm(h,t)})}if(o.length===0){let c=await le(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Be(e,c.native.artifact_root);o.push({projectRoot:ir.resolve(e),config:c,paths:l,gitContext:ec(e,i)??W(e),changes:await sm(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await Jh(c.paths,(d,u)=>c.archiveErrors.push({name:d,message:u}),t),t!==void 0&&(c.archives=c.archives.filter(({state:d})=>d.name===t),c.archiveErrors=c.archiveErrors.filter(({name:d})=>d===t));let l=(d,u)=>c.finishJournalErrors.push({name:d,message:u});c.finishJournals=t?[await Tl(c.paths,t,{onError:l})].filter(d=>d!==null):await om(c.paths,{onError:l})}return o}function cm(e,t){return e.workspace.bindingState==="aligned"?0:wo(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function _x(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:u,kind:f})=>{let h=u.finishJournalErrors?.find(({name:m})=>m===n);if(f==="portable")try{let m=await $e(u.paths,n);return{source:u,name:n,kind:f,workspace:Zh(u.paths,m,u.gitContext),portableStatus:null,inspectionError:h?.message??null,finishJournal:u.finishJournals?.find(({name:p})=>p===n)??null}}catch(m){return{source:u,name:n,kind:f,workspace:{projectRoot:u.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:u,name:n,kind:f,workspace:a.length>1?await Gc(u.paths,n):{projectRoot:u.projectRoot,currentBranch:u.gitContext.currentBranch,isSecondaryWorktree:u.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:h?.message??null}})),s=t.flatMap(u=>(u.archives??[]).filter(({state:f})=>f.name===n).map(f=>{let h=em({paths:u.paths,...f,finishJournal:u.finishJournals?.find(({name:m})=>m===n)??null});return{source:u,name:n,kind:"portable",workspace:h.workspace,portableStatus:h,inspectionError:u.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:f,finishJournal:u.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(u=>(u.archiveErrors??[]).filter(f=>f.name===n).map(f=>({source:u,error:f})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(u=>(u.finishJournalErrors??[]).filter(f=>f.name===n).map(f=>({source:u,error:f})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let u=t.find(h=>h.finishJournals?.some(({name:m})=>m===n)),f=u?.finishJournals?.find(({name:h})=>h===n);if(u&&f){i.push({source:u,name:n,kind:"portable",portableStatus:null,inspectionError:f.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:u.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:f.result?.message??"Native workspace finish record is orphaned."},finishJournal:f});continue}}if(s.length>0){for(let f of o)if(f.kind==="portable")try{f.record=await Il(f.source.paths,ir.join(f.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let u=s.find(f=>[...o,...s.filter(h=>!Uh(f.record,h.record))].every(h=>h.record&&Gh(f.record,h.record)));if(u){i.push(u);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((u,f)=>cm(u,e)-cm(f,e)||u.source.projectRoot.localeCompare(f.source.projectRoot));let d=o.filter(u=>u.workspace.bindingState==="aligned");d.length>1?i.push(...d):d.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(d[0]??o[0])}if(i.length>rn.maxChanges)throw new Error(`Native status discovery exceeds ${rn.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function Ax(e,t){let r=await Rx(e,t),i=(await _x(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}async function lm(e){let{sources:t,candidates:r}=await Ax(e.projectRoot,e.name);return r.length>0?r[0].source.projectRoot:(t.find(i=>wo(i.projectRoot,e.projectRoot))??t[0]).projectRoot}async function um(e,t){let r=Dh(e,"change name");Hh(e);let i=await lm({projectRoot:t,name:r}),{paths:n}=await Fh(i);if(await Hr(n,r)){let u=await co({paths:n,name:r}),f=u.state,h=at(n,r),m=await H({root:h,ref:f.brief,maxBytes:null,includeHash:!1}),p=[];for(let v of f.spec_changes){if(v.source===null)continue;let b=await H({root:h,ref:v.source,maxBytes:null,includeHash:!1});p.push({capability:v.capability,operation:v.operation,source:v.source,content:b.text})}let g={state:f,artifacts:Gt(n,f.name),brief:m.text,proposedSpecs:p,continuation:jr(f,await Ir({paths:n,state:f}),{verifierExecutionRef:vl(f,u.local),...u.local?{verificationCheckPlans:Nl(u.local,u.local.workspace.projectRoot)}:{}})};return{...mo("show",g),executionCwd:i}}let a=await Xc(n,r);if(a.status==="migration-required")return{...mo("show",{name:r,artifacts:Gt(n,r),schema:a.schema,minimumRuntimeVersion:a.minimumRuntimeVersion,migrationRequired:!0,message:a.message}),executionCwd:i};if(a.status!=="current"||!a.state)throw new Me(a.schema,a.minimumRuntimeVersion);let o=a.state,s=te(n,r),c=await nh(n,r),l=await H({root:s,ref:o.brief,maxBytes:null}),d={state:o,artifacts:Gt(n,o.name),brief:l.text,proposedSpecs:c};if(Buffer.byteLength(JSON.stringify(d),"utf8")>$h)throw new Error("Native show output exceeds its serialized byte budget");return{...mo("show",d),executionCwd:i}}async function dm(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Rl(n,"--json"),Rl(n,"--verbose"),c=Oh(n,"--project-root");let u=[...n,...a],f=await qh(c);l={executionCwd:f,...await t(u,f)}}catch(u){l=Bh(e,u)}let d=Vh(l,o,s);return d.stdout&&process.stdout.write(d.stdout),d.stderr&&process.stderr.write(d.stderr+(d.stderr.endsWith(`
173
173
  `)?"":`
174
174
  `)),d.exitCode}process.exitCode=await dm("show",um);