@rpamis/comet 0.4.0-rc.1 → 0.4.0-rc.2

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 (132) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +3 -650
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-archive.mjs +74 -74
  5. package/assets/skills/comet/scripts/comet-guard.mjs +100 -100
  6. package/assets/skills/comet/scripts/comet-handoff.mjs +77 -77
  7. package/assets/skills/comet/scripts/comet-hook-guard.mjs +58 -59
  8. package/assets/skills/comet/scripts/comet-hook-router.mjs +103 -104
  9. package/assets/skills/comet/scripts/comet-intent.mjs +6 -6
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +2 -2
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +174 -175
  12. package/assets/skills/comet/scripts/comet-state.mjs +105 -105
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +2 -2
  14. package/assets/skills/comet-native/SKILL.md +5 -4
  15. package/assets/skills/comet-native/reference/commands.md +4 -4
  16. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +108 -102
  17. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +130 -124
  18. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +96 -89
  19. package/assets/skills/comet-native/scripts/comet-native-init.mjs +120 -114
  20. package/assets/skills/comet-native/scripts/comet-native-new.mjs +112 -106
  21. package/assets/skills/comet-native/scripts/comet-native-next.mjs +121 -115
  22. package/assets/skills/comet-native/scripts/comet-native-root.mjs +100 -94
  23. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +164 -157
  24. package/assets/skills/comet-native/scripts/comet-native-select.mjs +113 -107
  25. package/assets/skills/comet-native/scripts/comet-native-show.mjs +106 -100
  26. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +94 -88
  27. package/assets/skills/comet-native/scripts/comet-native-status.mjs +110 -104
  28. package/assets/skills-zh/comet-native/SKILL.md +5 -4
  29. package/assets/skills-zh/comet-native/reference/commands.md +4 -4
  30. package/dist/app/commands/status.d.ts.map +1 -1
  31. package/dist/app/commands/status.js +49 -9
  32. package/dist/app/commands/status.js.map +1 -1
  33. package/dist/app/commands/update.d.ts.map +1 -1
  34. package/dist/app/commands/update.js +1 -44
  35. package/dist/app/commands/update.js.map +1 -1
  36. package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
  37. package/dist/domains/comet-classic/classic-archive.js +15 -0
  38. package/dist/domains/comet-classic/classic-archive.js.map +1 -1
  39. package/dist/domains/comet-classic/classic-cli.d.ts +8 -0
  40. package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
  41. package/dist/domains/comet-classic/classic-cli.js +10 -0
  42. package/dist/domains/comet-classic/classic-cli.js.map +1 -1
  43. package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
  44. package/dist/domains/comet-classic/classic-guard.js +20 -0
  45. package/dist/domains/comet-classic/classic-guard.js.map +1 -1
  46. package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
  47. package/dist/domains/comet-classic/classic-handoff.js +13 -0
  48. package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
  49. package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
  50. package/dist/domains/comet-classic/classic-hook-guard.js +14 -15
  51. package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
  52. package/dist/domains/comet-classic/classic-output-language.d.ts +73 -0
  53. package/dist/domains/comet-classic/classic-output-language.d.ts.map +1 -0
  54. package/dist/domains/comet-classic/classic-output-language.js +175 -0
  55. package/dist/domains/comet-classic/classic-output-language.js.map +1 -0
  56. package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
  57. package/dist/domains/comet-classic/classic-script-entry.js +10 -0
  58. package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
  59. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  60. package/dist/domains/comet-classic/classic-state-command.js +43 -4
  61. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  62. package/dist/domains/comet-entry/project-status.d.ts.map +1 -1
  63. package/dist/domains/comet-entry/project-status.js +15 -3
  64. package/dist/domains/comet-entry/project-status.js.map +1 -1
  65. package/dist/domains/comet-entry/types.d.ts +5 -1
  66. package/dist/domains/comet-entry/types.d.ts.map +1 -1
  67. package/dist/domains/comet-native/native-children.d.ts +16 -0
  68. package/dist/domains/comet-native/native-children.d.ts.map +1 -1
  69. package/dist/domains/comet-native/native-children.js +73 -7
  70. package/dist/domains/comet-native/native-children.js.map +1 -1
  71. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  72. package/dist/domains/comet-native/native-cli-help.js +2 -1
  73. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  74. package/dist/domains/comet-native/native-cli-shared.d.ts +7 -1
  75. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  76. package/dist/domains/comet-native/native-cli-shared.js +51 -4
  77. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  78. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  79. package/dist/domains/comet-native/native-cli.js +4 -2
  80. package/dist/domains/comet-native/native-cli.js.map +1 -1
  81. package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -1
  82. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  83. package/dist/domains/comet-native/native-loop-runtime.js +18 -3
  84. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  85. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  86. package/dist/domains/comet-native/native-next-command.js +1 -0
  87. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  88. package/dist/domains/comet-native/native-output-language.d.ts +69 -0
  89. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -0
  90. package/dist/domains/comet-native/native-output-language.js +369 -0
  91. package/dist/domains/comet-native/native-output-language.js.map +1 -0
  92. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  93. package/dist/domains/comet-native/native-portable-continuation.js +44 -0
  94. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  95. package/dist/domains/comet-native/native-portable-runtime.d.ts +1 -0
  96. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  97. package/dist/domains/comet-native/native-portable-runtime.js +1 -1
  98. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  99. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  100. package/dist/domains/comet-native/native-portable-state.js +5 -0
  101. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  102. package/dist/domains/comet-native/native-portable-types.d.ts +3 -0
  103. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  104. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  105. package/dist/domains/comet-native/native-runner-input.d.ts +30 -28
  106. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  107. package/dist/domains/comet-native/native-runner-input.js +5 -0
  108. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  109. package/dist/domains/comet-native/native-script-entry.d.ts +5 -4
  110. package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
  111. package/dist/domains/comet-native/native-script-entry.js +8 -16
  112. package/dist/domains/comet-native/native-script-entry.js.map +1 -1
  113. package/dist/domains/comet-native/native-status-discovery.d.ts +31 -1
  114. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -1
  115. package/dist/domains/comet-native/native-status-discovery.js +46 -8
  116. package/dist/domains/comet-native/native-status-discovery.js.map +1 -1
  117. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  118. package/dist/domains/dashboard/native-collector.js +2 -0
  119. package/dist/domains/dashboard/native-collector.js.map +1 -1
  120. package/dist/domains/dashboard/web/index.html +14 -14
  121. package/dist/domains/workflow-contract/output-envelope.d.ts +59 -0
  122. package/dist/domains/workflow-contract/output-envelope.d.ts.map +1 -0
  123. package/dist/domains/workflow-contract/output-envelope.js +108 -0
  124. package/dist/domains/workflow-contract/output-envelope.js.map +1 -0
  125. package/dist/platform/version/version.d.ts +8 -0
  126. package/dist/platform/version/version.d.ts.map +1 -1
  127. package/dist/platform/version/version.js +58 -8
  128. package/dist/platform/version/version.js.map +1 -1
  129. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +2 -0
  130. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +1 -0
  131. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +37 -0
  132. package/package.json +1 -1
@@ -1,146 +1,146 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var Pm=Object.create;var Cl=Object.defineProperty;var Cm=Object.getOwnPropertyDescriptor;var Rm=Object.getOwnPropertyNames;var Am=Object.getPrototypeOf,_m=Object.prototype.hasOwnProperty;var tn=(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 b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Im=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rm(t))!_m.call(e,n)&&n!==r&&Cl(e,n,{get:()=>t[n],enumerable:!(i=Cm(t,n))||i.enumerable});return e};var Hr=(e,t,r)=>(r=e!=null?Pm(Am(e)):{},Im(t||!e||!e.__esModule?Cl(r,"default",{value:e,enumerable:!0}):r,e));var R=b(te=>{"use strict";var go=Symbol.for("yaml.alias"),Rl=Symbol.for("yaml.document"),rn=Symbol.for("yaml.map"),Al=Symbol.for("yaml.pair"),wo=Symbol.for("yaml.scalar"),nn=Symbol.for("yaml.seq"),it=Symbol.for("yaml.node.type"),Tm=e=>!!e&&typeof e=="object"&&e[it]===go,jm=e=>!!e&&typeof e=="object"&&e[it]===Rl,$m=e=>!!e&&typeof e=="object"&&e[it]===rn,Om=e=>!!e&&typeof e=="object"&&e[it]===Al,_l=e=>!!e&&typeof e=="object"&&e[it]===wo,Hm=e=>!!e&&typeof e=="object"&&e[it]===nn;function Il(e){if(e&&typeof e=="object")switch(e[it]){case rn:case nn:return!0}return!1}function Dm(e){if(e&&typeof e=="object")switch(e[it]){case go:case rn:case wo:case nn:return!0}return!1}var Bm=e=>(_l(e)||Il(e))&&!!e.anchor;te.ALIAS=go;te.DOC=Rl;te.MAP=rn;te.NODE_TYPE=it;te.PAIR=Al;te.SCALAR=wo;te.SEQ=nn;te.hasAnchor=Bm;te.isAlias=Tm;te.isCollection=Il;te.isDocument=jm;te.isMap=$m;te.isNode=Dm;te.isPair=Om;te.isScalar=_l;te.isSeq=Hm});var Dr=b(yo=>{"use strict";var z=R(),fe=Symbol("break visit"),Tl=Symbol("skip children"),qe=Symbol("remove node");function an(e,t){let r=jl(t);z.isDocument(e)?rr(null,e.contents,r,Object.freeze([e]))===qe&&(e.contents=null):rr(null,e,r,Object.freeze([]))}an.BREAK=fe;an.SKIP=Tl;an.REMOVE=qe;function rr(e,t,r,i){let n=$l(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Ol(e,i,n),rr(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=rr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=rr("key",t.key,r,i);if(a===fe)return fe;a===qe&&(t.key=null);let o=rr("value",t.value,r,i);if(o===fe)return fe;o===qe&&(t.value=null)}}return n}async function on(e,t){let r=jl(t);z.isDocument(e)?await ir(null,e.contents,r,Object.freeze([e]))===qe&&(e.contents=null):await ir(null,e,r,Object.freeze([]))}on.BREAK=fe;on.SKIP=Tl;on.REMOVE=qe;async function ir(e,t,r,i){let n=await $l(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Ol(e,i,n),ir(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ir(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=await ir("key",t.key,r,i);if(a===fe)return fe;a===qe&&(t.key=null);let o=await ir("value",t.value,r,i);if(o===fe)return fe;o===qe&&(t.value=null)}}return n}function jl(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 $l(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(z.isMap(t))return r.Map?.(e,t,i);if(z.isSeq(t))return r.Seq?.(e,t,i);if(z.isPair(t))return r.Pair?.(e,t,i);if(z.isScalar(t))return r.Scalar?.(e,t,i);if(z.isAlias(t))return r.Alias?.(e,t,i)}function Ol(e,t,r){let i=t[t.length-1];if(z.isCollection(i))i.items[e]=r;else if(z.isPair(i))e==="key"?i.key=r:i.value=r;else if(z.isDocument(i))i.contents=r;else{let n=z.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}yo.visit=an;yo.visitAsync=on});var No=b(Dl=>{"use strict";var Hl=R(),Lm=Dr(),Vm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Mm=e=>e.replace(/[!,[\]{}]/g,t=>Vm[t]),Br=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+Mm(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&&Hl.isNode(t.contents)){let a={};Lm.visit(t.contents,(o,s)=>{Hl.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
- `)}};Br.defaultYaml={explicit:!1,version:"1.2"};Br.defaultTags={"!!":"tag:yaml.org,2002:"};Dl.Directives=Br});var sn=b(Lr=>{"use strict";var Bl=R(),Fm=Dr();function qm(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 Ll(e){let t=new Set;return Fm.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Vl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Wm(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Ll(e));let o=Vl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Bl.isScalar(o.node)||Bl.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}}Lr.anchorIsValid=qm;Lr.anchorNames=Ll;Lr.createNodeAnchors=Wm;Lr.findNewAnchor=Vl});var bo=b(Ml=>{"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)}Ml.applyReviver=Vr});var mt=b(ql=>{"use strict";var zm=R();function Fl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Fl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!zm.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}ql.toJS=Fl});var cn=b(zl=>{"use strict";var Jm=bo(),Wl=R(),Gm=mt(),ko=class{constructor(t){Object.defineProperty(this,Wl.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(!Wl.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=Gm.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Jm.applyReviver(a,{"":s},"",s):s}};zl.NodeBase=ko});var Mr=b(Jl=>{"use strict";var Um=sn(),Km=Dr(),nr=R(),Ym=cn(),Xm=mt(),So=class extends Ym.NodeBase{constructor(t){super(nr.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=[],Km.visit(t,{Node:(a,o)=>{(nr.isAlias(o)||nr.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||(Xm.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=ln(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(Um.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 ln(e,t,r){if(nr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(nr.isCollection(t)){let i=0;for(let n of t.items){let a=ln(e,n,r);a>i&&(i=a)}return i}else if(nr.isPair(t)){let i=ln(e,t.key,r),n=ln(e,t.value,r);return Math.max(i,n)}return 1}Jl.Alias=So});var W=b(Eo=>{"use strict";var Qm=R(),Zm=cn(),ev=mt(),tv=e=>!e||typeof e!="function"&&typeof e!="object",vt=class extends Zm.NodeBase{constructor(t){super(Qm.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:ev.toJS(this.value,t,r)}toString(){return String(this.value)}};vt.BLOCK_FOLDED="BLOCK_FOLDED";vt.BLOCK_LITERAL="BLOCK_LITERAL";vt.PLAIN="PLAIN";vt.QUOTE_DOUBLE="QUOTE_DOUBLE";vt.QUOTE_SINGLE="QUOTE_SINGLE";Eo.Scalar=vt;Eo.isScalarValue=tv});var Fr=b(Ul=>{"use strict";var rv=Mr(),Bt=R(),Gl=W(),iv="tag:yaml.org,2002:";function nv(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 av(e,t,r){if(Bt.isDocument(e)&&(e=e.contents),Bt.isNode(e))return e;if(Bt.isPair(e)){let d=r.schema[Bt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 rv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=iv+t.slice(2));let l=nv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Gl.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Bt.MAP]:Symbol.iterator in Object(e)?o[Bt.SEQ]:o[Bt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Gl.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Ul.createNode=av});var dn=b(un=>{"use strict";var ov=Fr(),We=R(),sv=cn();function xo(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 ov.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 Kl=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Po=class extends sv.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=>We.isNode(i)||We.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Kl(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(We.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,xo(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(We.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&&We.isScalar(a)?a.value:a:We.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!We.isPair(r))return!1;let i=r.value;return i==null||t&&We.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 We.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(We.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,xo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};un.Collection=Po;un.collectionFromPath=xo;un.isEmptyPath=Kl});var qr=b(fn=>{"use strict";var cv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Co(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var lv=(e,t,r)=>e.endsWith(`
6
- `)?Co(r,t):r.includes(`
4
+ var Wm=Object.create;var Tl=Object.defineProperty;var zm=Object.getOwnPropertyDescriptor;var Jm=Object.getOwnPropertyNames;var Gm=Object.getPrototypeOf,Um=Object.prototype.hasOwnProperty;var an=(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 b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Km=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jm(t))!Um.call(e,n)&&n!==r&&Tl(e,n,{get:()=>t[n],enumerable:!(i=zm(t,n))||i.enumerable});return e};var Br=(e,t,r)=>(r=e!=null?Wm(Gm(e)):{},Km(t||!e||!e.__esModule?Tl(r,"default",{value:e,enumerable:!0}):r,e));var A=b(re=>{"use strict";var yo=Symbol.for("yaml.alias"),jl=Symbol.for("yaml.document"),on=Symbol.for("yaml.map"),$l=Symbol.for("yaml.pair"),No=Symbol.for("yaml.scalar"),sn=Symbol.for("yaml.seq"),at=Symbol.for("yaml.node.type"),Ym=e=>!!e&&typeof e=="object"&&e[at]===yo,Xm=e=>!!e&&typeof e=="object"&&e[at]===jl,Qm=e=>!!e&&typeof e=="object"&&e[at]===on,Zm=e=>!!e&&typeof e=="object"&&e[at]===$l,Ol=e=>!!e&&typeof e=="object"&&e[at]===No,ev=e=>!!e&&typeof e=="object"&&e[at]===sn;function Hl(e){if(e&&typeof e=="object")switch(e[at]){case on:case sn:return!0}return!1}function tv(e){if(e&&typeof e=="object")switch(e[at]){case yo:case on:case No:case sn:return!0}return!1}var rv=e=>(Ol(e)||Hl(e))&&!!e.anchor;re.ALIAS=yo;re.DOC=jl;re.MAP=on;re.NODE_TYPE=at;re.PAIR=$l;re.SCALAR=No;re.SEQ=sn;re.hasAnchor=rv;re.isAlias=Ym;re.isCollection=Hl;re.isDocument=Xm;re.isMap=Qm;re.isNode=tv;re.isPair=Zm;re.isScalar=Ol;re.isSeq=ev});var Lr=b(bo=>{"use strict";var G=A(),pe=Symbol("break visit"),Dl=Symbol("skip children"),We=Symbol("remove node");function cn(e,t){let r=Bl(t);G.isDocument(e)?nr(null,e.contents,r,Object.freeze([e]))===We&&(e.contents=null):nr(null,e,r,Object.freeze([]))}cn.BREAK=pe;cn.SKIP=Dl;cn.REMOVE=We;function nr(e,t,r,i){let n=Ll(e,t,r,i);if(G.isNode(n)||G.isPair(n))return Vl(e,i,n),nr(e,n,r,i);if(typeof n!="symbol"){if(G.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===pe)return pe;o===We&&(t.items.splice(a,1),a-=1)}}}else if(G.isPair(t)){i=Object.freeze(i.concat(t));let a=nr("key",t.key,r,i);if(a===pe)return pe;a===We&&(t.key=null);let o=nr("value",t.value,r,i);if(o===pe)return pe;o===We&&(t.value=null)}}return n}async function ln(e,t){let r=Bl(t);G.isDocument(e)?await ar(null,e.contents,r,Object.freeze([e]))===We&&(e.contents=null):await ar(null,e,r,Object.freeze([]))}ln.BREAK=pe;ln.SKIP=Dl;ln.REMOVE=We;async function ar(e,t,r,i){let n=await Ll(e,t,r,i);if(G.isNode(n)||G.isPair(n))return Vl(e,i,n),ar(e,n,r,i);if(typeof n!="symbol"){if(G.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===pe)return pe;o===We&&(t.items.splice(a,1),a-=1)}}}else if(G.isPair(t)){i=Object.freeze(i.concat(t));let a=await ar("key",t.key,r,i);if(a===pe)return pe;a===We&&(t.key=null);let o=await ar("value",t.value,r,i);if(o===pe)return pe;o===We&&(t.value=null)}}return n}function Bl(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 Ll(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(G.isMap(t))return r.Map?.(e,t,i);if(G.isSeq(t))return r.Seq?.(e,t,i);if(G.isPair(t))return r.Pair?.(e,t,i);if(G.isScalar(t))return r.Scalar?.(e,t,i);if(G.isAlias(t))return r.Alias?.(e,t,i)}function Vl(e,t,r){let i=t[t.length-1];if(G.isCollection(i))i.items[e]=r;else if(G.isPair(i))e==="key"?i.key=r:i.value=r;else if(G.isDocument(i))i.contents=r;else{let n=G.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}bo.visit=cn;bo.visitAsync=ln});var ko=b(Fl=>{"use strict";var Ml=A(),iv=Lr(),nv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},av=e=>e.replace(/[!,[\]{}]/g,t=>nv[t]),Vr=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+av(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={};iv.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
+ `)}};Vr.defaultYaml={explicit:!1,version:"1.2"};Vr.defaultTags={"!!":"tag:yaml.org,2002:"};Fl.Directives=Vr});var un=b(Mr=>{"use strict";var ql=A(),ov=Lr();function sv(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 Wl(e){let t=new Set;return ov.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function zl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function cv(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Wl(e));let o=zl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(ql.isScalar(o.node)||ql.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}}Mr.anchorIsValid=sv;Mr.anchorNames=Wl;Mr.createNodeAnchors=cv;Mr.findNewAnchor=zl});var So=b(Jl=>{"use strict";function Fr(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=Fr(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=Fr(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=Fr(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=Fr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Jl.applyReviver=Fr});var wt=b(Ul=>{"use strict";var lv=A();function Gl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Gl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!lv.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}Ul.toJS=Gl});var dn=b(Yl=>{"use strict";var uv=So(),Kl=A(),dv=wt(),Eo=class{constructor(t){Object.defineProperty(this,Kl.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(!Kl.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=dv.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?uv.applyReviver(a,{"":s},"",s):s}};Yl.NodeBase=Eo});var qr=b(Xl=>{"use strict";var fv=un(),pv=Lr(),or=A(),hv=dn(),mv=wt(),xo=class extends hv.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=[],pv.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||(mv.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=fn(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(fv.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 fn(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=fn(e,n,r);a>i&&(i=a)}return i}else if(or.isPair(t)){let i=fn(e,t.key,r),n=fn(e,t.value,r);return Math.max(i,n)}return 1}Xl.Alias=xo});var z=b(Co=>{"use strict";var vv=A(),gv=dn(),wv=wt(),yv=e=>!e||typeof e!="function"&&typeof e!="object",yt=class extends gv.NodeBase{constructor(t){super(vv.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:wv.toJS(this.value,t,r)}toString(){return String(this.value)}};yt.BLOCK_FOLDED="BLOCK_FOLDED";yt.BLOCK_LITERAL="BLOCK_LITERAL";yt.PLAIN="PLAIN";yt.QUOTE_DOUBLE="QUOTE_DOUBLE";yt.QUOTE_SINGLE="QUOTE_SINGLE";Co.Scalar=yt;Co.isScalarValue=yv});var Wr=b(Zl=>{"use strict";var Nv=qr(),Vt=A(),Ql=z(),bv="tag:yaml.org,2002:";function kv(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 Sv(e,t,r){if(Vt.isDocument(e)&&(e=e.contents),Vt.isNode(e))return e;if(Vt.isPair(e)){let d=r.schema[Vt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 Nv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=bv+t.slice(2));let l=kv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Ql.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Vt.MAP]:Symbol.iterator in Object(e)?o[Vt.SEQ]:o[Vt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Ql.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Zl.createNode=Sv});var hn=b(pn=>{"use strict";var Ev=Wr(),ze=A(),xv=dn();function Po(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 Ev.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 eu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ro=class extends xv.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=>ze.isNode(i)||ze.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(eu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(ze.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Po(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(ze.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&&ze.isScalar(a)?a.value:a:ze.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!ze.isPair(r))return!1;let i=r.value;return i==null||t&&ze.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 ze.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(ze.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Po(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};pn.Collection=Ro;pn.collectionFromPath=Po;pn.isEmptyPath=eu});var zr=b(mn=>{"use strict";var Cv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ao(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Pv=(e,t,r)=>e.endsWith(`
6
+ `)?Ao(r,t):r.includes(`
7
7
  `)?`
8
- `+Co(r,t):(e.endsWith(" ")?"":" ")+r;fn.indentComment=Co;fn.lineComment=lv;fn.stringifyComment=cv});var Xl=b(Wr=>{"use strict";var uv="flow",Ro="block",hn="quoted";function dv(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=[],f={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let u,h,v=!1,m=-1,p=-1,y=-1;r===Ro&&(m=Yl(e,m,t.length),m!==-1&&(d=m+c));for(let w;w=e[m+=1];){if(r===hn&&w==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if(w===`
9
- `)r===Ro&&(m=Yl(e,m,t.length)),d=m+t.length+c,u=void 0;else{if(w===" "&&h&&h!==" "&&h!==`
10
- `&&h!==" "){let k=e[m+1];k&&k!==" "&&k!==`
11
- `&&k!==" "&&(u=m)}if(m>=d)if(u)l.push(u),d=u+c,u=void 0;else if(r===hn){for(;h===" "||h===" ";)h=w,w=e[m+=1],v=!0;let k=m>y+1?m-2:p-1;if(f[k])return e;l.push(k),f[k]=!0,d=k+c,u=void 0}else v=!0}h=w}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let w=0;w<l.length;++w){let k=l[w],S=l[w+1]||e.length;k===0?g=`
12
- ${t}${e.slice(0,S)}`:(r===hn&&f[k]&&(g+=`${e[k]}\\`),g+=`
13
- ${t}${e.slice(k+1,S)}`)}return g}function Yl(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);i=t,n=t+1,a=e[n]}return i}Wr.FOLD_BLOCK=Ro;Wr.FOLD_FLOW=uv;Wr.FOLD_QUOTED=hn;Wr.foldFlowLines=dv});var Jr=b(Ql=>{"use strict";var _e=W(),gt=Xl(),mn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),vn=e=>/^(%|---|\.\.\.)/m.test(e);function fv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
- `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function zr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(vn(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
8
+ `+Ao(r,t):(e.endsWith(" ")?"":" ")+r;mn.indentComment=Ao;mn.lineComment=Pv;mn.stringifyComment=Cv});var ru=b(Jr=>{"use strict";var Rv="flow",_o="block",vn="quoted";function Av(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=[],f={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let u,p,v=!1,m=-1,h=-1,w=-1;r===_o&&(m=tu(e,m,t.length),m!==-1&&(d=m+c));for(let y;y=e[m+=1];){if(r===vn&&y==="\\"){switch(h=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}w=m}if(y===`
9
+ `)r===_o&&(m=tu(e,m,t.length)),d=m+t.length+c,u=void 0;else{if(y===" "&&p&&p!==" "&&p!==`
10
+ `&&p!==" "){let k=e[m+1];k&&k!==" "&&k!==`
11
+ `&&k!==" "&&(u=m)}if(m>=d)if(u)l.push(u),d=u+c,u=void 0;else if(r===vn){for(;p===" "||p===" ";)p=y,y=e[m+=1],v=!0;let k=m>w+1?m-2:h-1;if(f[k])return e;l.push(k),f[k]=!0,d=k+c,u=void 0}else v=!0}p=y}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let k=l[y],S=l[y+1]||e.length;k===0?g=`
12
+ ${t}${e.slice(0,S)}`:(r===vn&&f[k]&&(g+=`${e[k]}\\`),g+=`
13
+ ${t}${e.slice(k+1,S)}`)}return g}function tu(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);i=t,n=t+1,a=e[n]}return i}Jr.FOLD_BLOCK=_o;Jr.FOLD_FLOW=Rv;Jr.FOLD_QUOTED=vn;Jr.foldFlowLines=Av});var Ur=b(iu=>{"use strict";var Ie=z(),Nt=ru(),wn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),yn=e=>/^(%|---|\.\.\.)/m.test(e);function _v(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Gr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(yn(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
16
16
 
17
17
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:gt.foldFlowLines(o,a,gt.FOLD_QUOTED,mn(t,!1))}function Ao(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return zr(e,t);let r=t.indent||(vn(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return t.implicitKey?i:gt.foldFlowLines(i,r,gt.FOLD_FLOW,mn(t,!1))}function ar(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=zr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Ao:a&&!n?i=zr:i=r?Ao:zr}return i(e,t)}var _o;try{_o=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Nt.foldFlowLines(o,a,Nt.FOLD_QUOTED,wn(t,!1))}function Io(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Gr(e,t);let r=t.indent||(yn(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return t.implicitKey?i:Nt.foldFlowLines(i,r,Nt.FOLD_FLOW,wn(t,!1))}function sr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Gr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Io:a&&!n?i=Gr:i=r?Io:Gr}return i(e,t)}var To;try{To=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{_o=/\n+(?!\n|$)/g}function pn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return ar(r,i);let l=i.indent||(i.forceBlockIndent||vn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===_e.Scalar.BLOCK_FOLDED?!1:t===_e.Scalar.BLOCK_LITERAL?!0:!fv(r,c,l.length);if(!r)return f?`|
23
+ |$)`,"g")}catch{To=/\n+(?!\n|$)/g}function gn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return sr(r,i);let l=i.indent||(i.forceBlockIndent||yn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===Ie.Scalar.BLOCK_FOLDED?!1:t===Ie.Scalar.BLOCK_LITERAL?!0:!_v(r,c,l.length);if(!r)return f?`|
24
24
  `:`>
25
25
  `;let d,u;for(u=r.length;u>0;--u){let S=r[u-1];if(S!==`
26
- `&&S!==" "&&S!==" ")break}let h=r.substring(u),v=h.indexOf(`
27
- `);v===-1?d="-":r===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
28
- `&&(h=h.slice(0,-1)),h=h.replace(_o,`$&${l}`));let m=!1,p,y=-1;for(p=0;p<r.length;++p){let S=r[p];if(S===" ")m=!0;else if(S===`
29
- `)y=p;else break}let g=r.substring(0,y<p?y+1:p);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let k=(m?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let S=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,x=mn(i,!0);o!=="folded"&&t!==_e.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{E=!0});let N=gt.foldFlowLines(`${g}${S}${h}`,l,gt.FOLD_BLOCK,x);if(!E)return`>${k}
26
+ `&&S!==" "&&S!==" ")break}let p=r.substring(u),v=p.indexOf(`
27
+ `);v===-1?d="-":r===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
28
+ `&&(p=p.slice(0,-1)),p=p.replace(To,`$&${l}`));let m=!1,h,w=-1;for(h=0;h<r.length;++h){let S=r[h];if(S===" ")m=!0;else if(S===`
29
+ `)w=h;else break}let g=r.substring(0,w<h?w+1:h);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let k=(m?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let S=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,x=wn(i,!0);o!=="folded"&&t!==Ie.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{E=!0});let N=Nt.foldFlowLines(`${g}${S}${p}`,l,Nt.FOLD_BLOCK,x);if(!E)return`>${k}
31
31
  ${l}${N}`}return r=r.replace(/\n+/g,`$&${l}`),`|${k}
32
- ${l}${g}${r}${h}`}function hv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
- `)||f&&/[[\]{},]/.test(a))return ar(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
- `)?ar(a,t):pn(e,t,r,i);if(!s&&!f&&n!==_e.Scalar.PLAIN&&a.includes(`
35
- `))return pn(e,t,r,i);if(vn(a)){if(c==="")return t.forceBlockIndent=!0,pn(e,t,r,i);if(s&&c===l)return ar(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let u=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(u)||h?.some(u))return ar(a,t)}return s?d:gt.foldFlowLines(d,c,gt.FOLD_FLOW,mn(t,!1))}function pv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==_e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=_e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case _e.Scalar.BLOCK_FOLDED:case _e.Scalar.BLOCK_LITERAL:return n||a?ar(o.value,t):pn(o,t,r,i);case _e.Scalar.QUOTE_DOUBLE:return zr(o.value,t);case _e.Scalar.QUOTE_SINGLE:return Ao(o.value,t);case _e.Scalar.PLAIN:return hv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Ql.stringifyString=pv});var Gr=b(Io=>{"use strict";var mv=sn(),wt=R(),vv=qr(),gv=Jr();function wv(e,t){let r=Object.assign({blockQuote:!0,commentString:vv.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function yv(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(wt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Nv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(wt.isScalar(e)||wt.isCollection(e))&&e.anchor;a&&mv.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function bv(e,t,r,i){if(wt.isPair(e))return e.toString(t,r,i);if(wt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=wt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=yv(t.doc.schema.tags,a));let o=Nv(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):wt.isScalar(a)?gv.stringifyString(a,t,r,i):a.toString(t,r,i);return o?wt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Io.createStringifyContext=wv;Io.stringify=bv});var ru=b(tu=>{"use strict";var nt=R(),Zl=W(),eu=Gr(),Ur=qr();function kv({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=r,u=nt.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(nt.isCollection(e)||!nt.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!d&&(!e||u&&t==null&&!r.inFlow||nt.isCollection(e)||(nt.isScalar(e)?e.type===Zl.Scalar.BLOCK_FOLDED||e.type===Zl.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=eu.stringify(e,r,()=>v=!0,()=>m=!0);if(!h&&!r.inFlow&&p.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,u&&!v?p+=Ur.lineComment(p,r.indent,l(u)):m&&n&&n(),p;v&&(u=null),h?(u&&(p+=Ur.lineComment(p,r.indent,l(u))),p=`? ${p}
38
- ${s}:`):(p=`${p}:`,u&&(p+=Ur.lineComment(p,r.indent,l(u))));let y,g,w;nt.isNode(t)?(y=!!t.spaceBefore,g=t.commentBefore,w=t.comment):(y=!1,g=null,w=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!h&&!u&&nt.isScalar(t)&&(r.indentAtStart=p.length+1),m=!1,!f&&c.length>=2&&!r.inFlow&&!h&&nt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let k=!1,S=eu.stringify(t,r,()=>k=!0,()=>m=!0),E=" ";if(u||y||g){if(E=y?`
32
+ ${l}${g}${r}${p}`}function Iv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
+ `)||f&&/[[\]{},]/.test(a))return sr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
+ `)?sr(a,t):gn(e,t,r,i);if(!s&&!f&&n!==Ie.Scalar.PLAIN&&a.includes(`
35
+ `))return gn(e,t,r,i);if(yn(a)){if(c==="")return t.forceBlockIndent=!0,gn(e,t,r,i);if(s&&c===l)return sr(a,t)}let d=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let u=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(u)||p?.some(u))return sr(a,t)}return s?d:Nt.foldFlowLines(d,c,Nt.FOLD_FLOW,wn(t,!1))}function Tv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Ie.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ie.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ie.Scalar.BLOCK_FOLDED:case Ie.Scalar.BLOCK_LITERAL:return n||a?sr(o.value,t):gn(o,t,r,i);case Ie.Scalar.QUOTE_DOUBLE:return Gr(o.value,t);case Ie.Scalar.QUOTE_SINGLE:return Io(o.value,t);case Ie.Scalar.PLAIN:return Iv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}iu.stringifyString=Tv});var Kr=b(jo=>{"use strict";var jv=un(),bt=A(),$v=zr(),Ov=Ur();function Hv(e,t){let r=Object.assign({blockQuote:!0,commentString:$v.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function Dv(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(bt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Bv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(bt.isScalar(e)||bt.isCollection(e))&&e.anchor;a&&jv.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Lv(e,t,r,i){if(bt.isPair(e))return e.toString(t,r,i);if(bt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=bt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Dv(t.doc.schema.tags,a));let o=Bv(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):bt.isScalar(a)?Ov.stringifyString(a,t,r,i):a.toString(t,r,i);return o?bt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}jo.createStringifyContext=Hv;jo.stringify=Lv});var su=b(ou=>{"use strict";var ot=A(),nu=z(),au=Kr(),Yr=zr();function Vv({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=r,u=ot.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(ot.isCollection(e)||!ot.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||u&&t==null&&!r.inFlow||ot.isCollection(e)||(ot.isScalar(e)?e.type===nu.Scalar.BLOCK_FOLDED||e.type===nu.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,m=!1,h=au.stringify(e,r,()=>v=!0,()=>m=!0);if(!p&&!r.inFlow&&h.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),h===""?"?":p?`? ${h}`:h}else if(a&&!d||t==null&&p)return h=`? ${h}`,u&&!v?h+=Yr.lineComment(h,r.indent,l(u)):m&&n&&n(),h;v&&(u=null),p?(u&&(h+=Yr.lineComment(h,r.indent,l(u))),h=`? ${h}
38
+ ${s}:`):(h=`${h}:`,u&&(h+=Yr.lineComment(h,r.indent,l(u))));let w,g,y;ot.isNode(t)?(w=!!t.spaceBefore,g=t.commentBefore,y=t.comment):(w=!1,g=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!u&&ot.isScalar(t)&&(r.indentAtStart=h.length+1),m=!1,!f&&c.length>=2&&!r.inFlow&&!p&&ot.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let k=!1,S=au.stringify(t,r,()=>k=!0,()=>m=!0),E=" ";if(u||w||g){if(E=w?`
39
39
  `:"",g){let x=l(g);E+=`
40
- ${Ur.indentComment(x,r.indent)}`}S===""&&!r.inFlow?E===`
41
- `&&w&&(E=`
40
+ ${Yr.indentComment(x,r.indent)}`}S===""&&!r.inFlow?E===`
41
+ `&&y&&(E=`
42
42
 
43
43
  `):E+=`
44
- ${r.indent}`}else if(!h&&nt.isCollection(t)){let x=S[0],N=S.indexOf(`
45
- `),_=N!==-1,Y=r.inFlow??t.flow??t.items.length===0;if(_||!Y){let ee=!1;if(_&&(x==="&"||x==="!")){let $=S.indexOf(" ");x==="&"&&$!==-1&&$<N&&S[$+1]==="!"&&($=S.indexOf(" ",$+1)),($===-1||N<$)&&(ee=!0)}ee||(E=`
44
+ ${r.indent}`}else if(!p&&ot.isCollection(t)){let x=S[0],N=S.indexOf(`
45
+ `),I=N!==-1,X=r.inFlow??t.flow??t.items.length===0;if(I||!X){let te=!1;if(I&&(x==="&"||x==="!")){let O=S.indexOf(" ");x==="&"&&O!==-1&&O<N&&S[O+1]==="!"&&(O=S.indexOf(" ",O+1)),(O===-1||N<O)&&(te=!0)}te||(E=`
46
46
  ${r.indent}`)}}else(S===""||S[0]===`
47
- `)&&(E="");return p+=E+S,r.inFlow?k&&i&&i():w&&!k?p+=Ur.lineComment(p,r.indent,l(w)):m&&n&&n(),p}tu.stringifyPair=kv});var jo=b(To=>{"use strict";var iu=tn("process");function Sv(e,...t){e==="debug"&&console.log(...t)}function Ev(e,t){(e==="debug"||e==="warn")&&(typeof iu.emitWarning=="function"?iu.emitWarning(t):console.warn(t))}To.debug=Sv;To.warn=Ev});var bn=b(Nn=>{"use strict";var yn=R(),nu=W(),gn="<<",wn={identify:e=>e===gn||typeof e=="symbol"&&e.description===gn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new nu.Scalar(Symbol(gn)),{addToJSMap:au}),stringify:()=>gn},xv=(e,t)=>(wn.identify(t)||yn.isScalar(t)&&(!t.type||t.type===nu.Scalar.PLAIN)&&wn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===wn.tag&&r.default);function au(e,t,r){let i=ou(e,r);if(yn.isSeq(i))for(let n of i.items)$o(e,t,n);else if(Array.isArray(i))for(let n of i)$o(e,t,n);else $o(e,t,i)}function $o(e,t,r){let i=ou(e,r);if(!yn.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 ou(e,t){return e&&yn.isAlias(t)?t.resolve(e.doc,e):t}Nn.addMergeToJSMap=au;Nn.isMergeKey=xv;Nn.merge=wn});var Ho=b(lu=>{"use strict";var Pv=jo(),su=bn(),Cv=Gr(),cu=R(),Oo=mt();function Rv(e,t,{key:r,value:i}){if(cu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(su.isMergeKey(e,r))su.addMergeToJSMap(e,t,i);else{let n=Oo.toJS(r,"",e);if(t instanceof Map)t.set(n,Oo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Av(r,n,e),o=Oo.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 Av(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(cu.isNode(e)&&r?.doc){let i=Cv.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)}lu.addPairToJSMap=Rv});var yt=b(Do=>{"use strict";var uu=Fr(),_v=ru(),Iv=Ho(),kn=R();function Tv(e,t,r){let i=uu.createNode(e,void 0,r),n=uu.createNode(t,void 0,r);return new Sn(i,n)}var Sn=class e{constructor(t,r=null){Object.defineProperty(this,kn.NODE_TYPE,{value:kn.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return kn.isNode(r)&&(r=r.clone(t)),kn.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Iv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?_v.stringifyPair(this,t,r,i):JSON.stringify(this)}};Do.Pair=Sn;Do.createPair=Tv});var Bo=b(fu=>{"use strict";var Lt=R(),du=Gr(),En=qr();function jv(e,t,r){return(t.inFlow??e.flow?Ov:$v)(e,t,r)}function $v({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),d=!1,u=[];for(let v=0;v<t.length;++v){let m=t[v],p=null;if(Lt.isNode(m))!d&&m.spaceBefore&&u.push(""),xn(r,u,m.commentBefore,d),m.comment&&(p=m.comment);else if(Lt.isPair(m)){let g=Lt.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&u.push(""),xn(r,u,g.commentBefore,d))}d=!1;let y=du.stringify(m,f,()=>p=null,()=>d=!0);p&&(y+=En.lineComment(y,a,l(p))),d&&p&&(d=!1),u.push(i+y)}let h;if(u.length===0)h=n.start+n.end;else{h=u[0];for(let v=1;v<u.length;++v){let m=u[v];h+=m?`
47
+ `)&&(E="");return h+=E+S,r.inFlow?k&&i&&i():y&&!k?h+=Yr.lineComment(h,r.indent,l(y)):m&&n&&n(),h}ou.stringifyPair=Vv});var Oo=b($o=>{"use strict";var cu=an("process");function Mv(e,...t){e==="debug"&&console.log(...t)}function Fv(e,t){(e==="debug"||e==="warn")&&(typeof cu.emitWarning=="function"?cu.emitWarning(t):console.warn(t))}$o.debug=Mv;$o.warn=Fv});var En=b(Sn=>{"use strict";var kn=A(),lu=z(),Nn="<<",bn={identify:e=>e===Nn||typeof e=="symbol"&&e.description===Nn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new lu.Scalar(Symbol(Nn)),{addToJSMap:uu}),stringify:()=>Nn},qv=(e,t)=>(bn.identify(t)||kn.isScalar(t)&&(!t.type||t.type===lu.Scalar.PLAIN)&&bn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===bn.tag&&r.default);function uu(e,t,r){let i=du(e,r);if(kn.isSeq(i))for(let n of i.items)Ho(e,t,n);else if(Array.isArray(i))for(let n of i)Ho(e,t,n);else Ho(e,t,i)}function Ho(e,t,r){let i=du(e,r);if(!kn.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 du(e,t){return e&&kn.isAlias(t)?t.resolve(e.doc,e):t}Sn.addMergeToJSMap=uu;Sn.isMergeKey=qv;Sn.merge=bn});var Bo=b(hu=>{"use strict";var Wv=Oo(),fu=En(),zv=Kr(),pu=A(),Do=wt();function Jv(e,t,{key:r,value:i}){if(pu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(fu.isMergeKey(e,r))fu.addMergeToJSMap(e,t,i);else{let n=Do.toJS(r,"",e);if(t instanceof Map)t.set(n,Do.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Gv(r,n,e),o=Do.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 Gv(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(pu.isNode(e)&&r?.doc){let i=zv.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)+'..."'),Wv.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)}hu.addPairToJSMap=Jv});var kt=b(Lo=>{"use strict";var mu=Wr(),Uv=su(),Kv=Bo(),xn=A();function Yv(e,t,r){let i=mu.createNode(e,void 0,r),n=mu.createNode(t,void 0,r);return new Cn(i,n)}var Cn=class e{constructor(t,r=null){Object.defineProperty(this,xn.NODE_TYPE,{value:xn.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return xn.isNode(r)&&(r=r.clone(t)),xn.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Kv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?Uv.stringifyPair(this,t,r,i):JSON.stringify(this)}};Lo.Pair=Cn;Lo.createPair=Yv});var Vo=b(gu=>{"use strict";var Mt=A(),vu=Kr(),Pn=zr();function Xv(e,t,r){return(t.inFlow??e.flow?Zv:Qv)(e,t,r)}function Qv({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),d=!1,u=[];for(let v=0;v<t.length;++v){let m=t[v],h=null;if(Mt.isNode(m))!d&&m.spaceBefore&&u.push(""),Rn(r,u,m.commentBefore,d),m.comment&&(h=m.comment);else if(Mt.isPair(m)){let g=Mt.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&u.push(""),Rn(r,u,g.commentBefore,d))}d=!1;let w=vu.stringify(m,f,()=>h=null,()=>d=!0);h&&(w+=Pn.lineComment(w,a,l(h))),d&&h&&(d=!1),u.push(i+w)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v<u.length;++v){let m=u[v];p+=m?`
48
48
  ${c}${m}`:`
49
- `}}return e?(h+=`
50
- `+En.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function Ov({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,f=0,d=[];for(let v=0;v<e.length;++v){let m=e[v],p=null;if(Lt.isNode(m))m.spaceBefore&&d.push(""),xn(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Lt.isPair(m)){let g=Lt.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),xn(t,d,g.commentBefore,!1),g.comment&&(l=!0));let w=Lt.isNode(m.value)?m.value:null;w?(w.comment&&(p=w.comment),w.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let y=du.stringify(m,c,()=>p=null);l||(l=d.length>f||y.includes(`
51
- `)),v<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,w)=>g+w.length+2,2)+(y.length+2)>t.options.lineWidth)),l&&(y+=",")),p&&(y+=En.lineComment(y,i,s(p))),d.push(y),f=d.length}let{start:u,end:h}=r;if(d.length===0)return u+h;if(!l){let v=d.reduce((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=u;for(let m of d)v+=m?`
49
+ `}}return e?(p+=`
50
+ `+Pn.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Zv({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,f=0,d=[];for(let v=0;v<e.length;++v){let m=e[v],h=null;if(Mt.isNode(m))m.spaceBefore&&d.push(""),Rn(t,d,m.commentBefore,!1),m.comment&&(h=m.comment);else if(Mt.isPair(m)){let g=Mt.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),Rn(t,d,g.commentBefore,!1),g.comment&&(l=!0));let y=Mt.isNode(m.value)?m.value:null;y?(y.comment&&(h=y.comment),y.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(h=g.comment)}h&&(l=!0);let w=vu.stringify(m,c,()=>h=null);l||(l=d.length>f||w.includes(`
51
+ `)),v<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,y)=>g+y.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),h&&(w+=Pn.lineComment(w,i,s(h))),d.push(w),f=d.length}let{start:u,end:p}=r;if(d.length===0)return u+p;if(!l){let v=d.reduce((m,h)=>m+h.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=u;for(let m of d)v+=m?`
52
52
  ${a}${n}${m}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${u}${o}${d.join(" ")}${o}${h}`}function xn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=En.indentComment(t(i),e);r.push(a.trimStart())}}fu.stringifyCollection=jv});var bt=b(Vo=>{"use strict";var Hv=Bo(),Dv=Ho(),Bv=dn(),Nt=R(),Pn=yt(),Lv=W();function Kr(e,t){let r=Nt.isScalar(t)?t.value:t;for(let i of e)if(Nt.isPair(i)&&(i.key===t||i.key===r||Nt.isScalar(i.key)&&i.key.value===r))return i}var Lo=class extends Bv.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Nt.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(Pn.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;Nt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Pn.Pair(t,t?.value):i=new Pn.Pair(t.key,t.value);let n=Kr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Nt.isScalar(n.value)&&Lv.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=Kr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Kr(this.items,t)?.value;return(!r&&Nt.isScalar(n)?n.value:n)??void 0}has(t){return!!Kr(this.items,t)}set(t,r){this.add(new Pn.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)Dv.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Nt.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})),Hv.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Vo.YAMLMap=Lo;Vo.findPair=Kr});var or=b(pu=>{"use strict";var Vv=R(),hu=bt(),Mv={collection:"map",default:!0,nodeClass:hu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Vv.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>hu.YAMLMap.from(e,t,r)};pu.map=Mv});var kt=b(mu=>{"use strict";var Fv=Fr(),qv=Bo(),Wv=dn(),Rn=R(),zv=W(),Jv=mt(),Mo=class extends Wv.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Rn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Cn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Cn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Rn.isScalar(n)?n.value:n}has(t){let r=Cn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Cn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Rn.isScalar(n)&&zv.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(Jv.toJS(a,String(n++),r));return i}toString(t,r,i){return t?qv.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(Fv.createNode(s,void 0,i))}}return a}};function Cn(e){let t=Rn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}mu.YAMLSeq=Mo});var sr=b(gu=>{"use strict";var Gv=R(),vu=kt(),Uv={collection:"seq",default:!0,nodeClass:vu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Gv.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>vu.YAMLSeq.from(e,t,r)};gu.seq=Uv});var Yr=b(wu=>{"use strict";var Kv=Jr(),Yv={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),Kv.stringifyString(e,t,r,i)}};wu.string=Yv});var An=b(bu=>{"use strict";var yu=W(),Nu={identify:e=>e==null,createNode:()=>new yu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new yu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Nu.test.test(e)?e:t.options.nullStr};bu.nullTag=Nu});var Fo=b(Su=>{"use strict";var Xv=W(),ku={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Xv.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&ku.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Su.boolTag=ku});var cr=b(Eu=>{"use strict";function Qv({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}Eu.stringifyNumber=Qv});var Wo=b(_n=>{"use strict";var Zv=W(),qo=cr(),eg={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:qo.stringifyNumber},tg={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():qo.stringifyNumber(e)}},rg={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 Zv.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:qo.stringifyNumber};_n.float=rg;_n.floatExp=tg;_n.floatNaN=eg});var Jo=b(Tn=>{"use strict";var xu=cr(),In=e=>typeof e=="bigint"||Number.isInteger(e),zo=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Pu(e,t,r){let{value:i}=e;return In(i)&&i>=0?r+i.toString(t):xu.stringifyNumber(e)}var ig={identify:e=>In(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>zo(e,2,8,r),stringify:e=>Pu(e,8,"0o")},ng={identify:In,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>zo(e,0,10,r),stringify:xu.stringifyNumber},ag={identify:e=>In(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>zo(e,2,16,r),stringify:e=>Pu(e,16,"0x")};Tn.int=ng;Tn.intHex=ag;Tn.intOct=ig});var Ru=b(Cu=>{"use strict";var og=or(),sg=An(),cg=sr(),lg=Yr(),ug=Fo(),Go=Wo(),Uo=Jo(),dg=[og.map,cg.seq,lg.string,sg.nullTag,ug.boolTag,Uo.intOct,Uo.int,Uo.intHex,Go.floatNaN,Go.floatExp,Go.float];Cu.schema=dg});var Iu=b(_u=>{"use strict";var fg=W(),hg=or(),pg=sr();function Au(e){return typeof e=="bigint"||Number.isInteger(e)}var jn=({value:e})=>JSON.stringify(e),mg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:jn},{identify:e=>e==null,createNode:()=>new fg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:jn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:jn},{identify:Au,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})=>Au(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:jn}],vg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},gg=[hg.map,pg.seq].concat(mg,vg);_u.schema=gg});var Yo=b(Tu=>{"use strict";var Xr=tn("buffer"),Ko=W(),wg=Jr(),yg={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Xr.Buffer=="function")return Xr.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 Xr.Buffer=="function")s=o instanceof Xr.Buffer?o.toString("base64"):Xr.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=Ko.Scalar.BLOCK_LITERAL),t!==Ko.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let d=0,u=0;d<l;++d,u+=c)f[d]=s.substr(u,c);s=f.join(t===Ko.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return wg.stringifyString({comment:e,type:t,value:s},i,n,a)}};Tu.binary=yg});var Hn=b(On=>{"use strict";var $n=R(),Xo=yt(),Ng=W(),bg=kt();function ju(e,t){if($n.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!$n.isPair(i)){if($n.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Xo.Pair(new Ng.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
54
+ ${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function Rn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Pn.indentComment(t(i),e);r.push(a.trimStart())}}gu.stringifyCollection=Xv});var Et=b(Fo=>{"use strict";var eg=Vo(),tg=Bo(),rg=hn(),St=A(),An=kt(),ig=z();function Xr(e,t){let r=St.isScalar(t)?t.value:t;for(let i of e)if(St.isPair(i)&&(i.key===t||i.key===r||St.isScalar(i.key)&&i.key.value===r))return i}var Mo=class extends rg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(St.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(An.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;St.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new An.Pair(t,t?.value):i=new An.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`);St.isScalar(n.value)&&ig.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&&St.isScalar(n)?n.value:n)??void 0}has(t){return!!Xr(this.items,t)}set(t,r){this.add(new An.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)tg.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!St.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})),eg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Fo.YAMLMap=Mo;Fo.findPair=Xr});var cr=b(yu=>{"use strict";var ng=A(),wu=Et(),ag={collection:"map",default:!0,nodeClass:wu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ng.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>wu.YAMLMap.from(e,t,r)};yu.map=ag});var xt=b(Nu=>{"use strict";var og=Wr(),sg=Vo(),cg=hn(),In=A(),lg=z(),ug=wt(),qo=class extends cg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(In.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&&In.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];In.isScalar(n)&&lg.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(ug.toJS(a,String(n++),r));return i}toString(t,r,i){return t?sg.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(og.createNode(s,void 0,i))}}return a}};function _n(e){let t=In.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Nu.YAMLSeq=qo});var lr=b(ku=>{"use strict";var dg=A(),bu=xt(),fg={collection:"seq",default:!0,nodeClass:bu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return dg.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>bu.YAMLSeq.from(e,t,r)};ku.seq=fg});var Qr=b(Su=>{"use strict";var pg=Ur(),hg={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),pg.stringifyString(e,t,r,i)}};Su.string=hg});var Tn=b(Cu=>{"use strict";var Eu=z(),xu={identify:e=>e==null,createNode:()=>new Eu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Eu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&xu.test.test(e)?e:t.options.nullStr};Cu.nullTag=xu});var Wo=b(Ru=>{"use strict";var mg=z(),Pu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new mg.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Pu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Ru.boolTag=Pu});var ur=b(Au=>{"use strict";function vg({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}Au.stringifyNumber=vg});var Jo=b(jn=>{"use strict";var gg=z(),zo=ur(),wg={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:zo.stringifyNumber},yg={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():zo.stringifyNumber(e)}},Ng={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 gg.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:zo.stringifyNumber};jn.float=Ng;jn.floatExp=yg;jn.floatNaN=wg});var Uo=b(On=>{"use strict";var _u=ur(),$n=e=>typeof e=="bigint"||Number.isInteger(e),Go=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Iu(e,t,r){let{value:i}=e;return $n(i)&&i>=0?r+i.toString(t):_u.stringifyNumber(e)}var bg={identify:e=>$n(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Go(e,2,8,r),stringify:e=>Iu(e,8,"0o")},kg={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Go(e,0,10,r),stringify:_u.stringifyNumber},Sg={identify:e=>$n(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Go(e,2,16,r),stringify:e=>Iu(e,16,"0x")};On.int=kg;On.intHex=Sg;On.intOct=bg});var ju=b(Tu=>{"use strict";var Eg=cr(),xg=Tn(),Cg=lr(),Pg=Qr(),Rg=Wo(),Ko=Jo(),Yo=Uo(),Ag=[Eg.map,Cg.seq,Pg.string,xg.nullTag,Rg.boolTag,Yo.intOct,Yo.int,Yo.intHex,Ko.floatNaN,Ko.floatExp,Ko.float];Tu.schema=Ag});var Hu=b(Ou=>{"use strict";var _g=z(),Ig=cr(),Tg=lr();function $u(e){return typeof e=="bigint"||Number.isInteger(e)}var Hn=({value:e})=>JSON.stringify(e),jg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Hn},{identify:e=>e==null,createNode:()=>new _g.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Hn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Hn},{identify:$u,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})=>$u(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:Hn}],$g={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Og=[Ig.map,Tg.seq].concat(jg,$g);Ou.schema=Og});var Qo=b(Du=>{"use strict";var Zr=an("buffer"),Xo=z(),Hg=Ur(),Dg={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=Xo.Scalar.BLOCK_LITERAL),t!==Xo.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let d=0,u=0;d<l;++d,u+=c)f[d]=s.substr(u,c);s=f.join(t===Xo.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return Hg.stringifyString({comment:e,type:t,value:s},i,n,a)}};Du.binary=Dg});var Ln=b(Bn=>{"use strict";var Dn=A(),Zo=kt(),Bg=z(),Lg=xt();function Bu(e,t){if(Dn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Dn.isPair(i)){if(Dn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Zo.Pair(new Bg.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]=$n.isPair(i)?i:new Xo.Pair(i)}}else t("Expected a sequence for this tag");return e}function $u(e,t,r){let{replacer:i}=r,n=new bg.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(Xo.createPair(s,c,r))}return n}var kg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ju,createNode:$u};On.createPairs=$u;On.pairs=kg;On.resolvePairs=ju});var es=b(Zo=>{"use strict";var Ou=R(),Qo=mt(),Qr=bt(),Sg=kt(),Hu=Hn(),Vt=class e extends Sg.YAMLSeq{constructor(){super(),this.add=Qr.YAMLMap.prototype.add.bind(this),this.delete=Qr.YAMLMap.prototype.delete.bind(this),this.get=Qr.YAMLMap.prototype.get.bind(this),this.has=Qr.YAMLMap.prototype.has.bind(this),this.set=Qr.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(Ou.isPair(n)?(a=Qo.toJS(n.key,"",r),o=Qo.toJS(n.value,a,r)):a=Qo.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=Hu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Vt.tag="tag:yaml.org,2002:omap";var Eg={collection:"seq",identify:e=>e instanceof Map,nodeClass:Vt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Hu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Ou.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Vt,r)},createNode:(e,t,r)=>Vt.from(e,t,r)};Zo.YAMLOMap=Vt;Zo.omap=Eg});var Mu=b(ts=>{"use strict";var Du=W();function Bu({value:e,source:t},r){return t&&(e?Lu:Vu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Lu={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 Du.Scalar(!0),stringify:Bu},Vu={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 Du.Scalar(!1),stringify:Bu};ts.falseTag=Vu;ts.trueTag=Lu});var Fu=b(Dn=>{"use strict";var xg=W(),rs=cr(),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:rs.stringifyNumber},Cg={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():rs.stringifyNumber(e)}},Rg={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 xg.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:rs.stringifyNumber};Dn.float=Rg;Dn.floatExp=Cg;Dn.floatNaN=Pg});var Wu=b(ei=>{"use strict";var qu=cr(),Zr=e=>typeof e=="bigint"||Number.isInteger(e);function Bn(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 is(e,t,r){let{value:i}=e;if(Zr(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return qu.stringifyNumber(e)}var Ag={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Bn(e,2,2,r),stringify:e=>is(e,2,"0b")},_g={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Bn(e,1,8,r),stringify:e=>is(e,8,"0")},Ig={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Bn(e,0,10,r),stringify:qu.stringifyNumber},Tg={identify:Zr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Bn(e,2,16,r),stringify:e=>is(e,16,"0x")};ei.int=Ig;ei.intBin=Ag;ei.intHex=Tg;ei.intOct=_g});var as=b(ns=>{"use strict";var Mn=R(),Ln=yt(),Vn=bt(),Mt=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 Ln.Pair(t.key,null):r=new Ln.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 Ln.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(Ln.createPair(o,null,i));return a}};Mt.tag="tag:yaml.org,2002:set";var jg={collection:"map",identify:e=>e instanceof Set,nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Mt.from(e,t,r),resolve(e,t){if(Mn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Mt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ns.YAMLSet=Mt;ns.set=jg});var ss=b(Fn=>{"use strict";var $g=cr();function os(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 zu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return $g.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 Og={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})=>os(e,r),stringify:zu},Hg={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=>os(e,!1),stringify:zu},Ju={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(Ju.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),f=t[8];if(f&&f!=="Z"){let d=os(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Fn.floatTime=Hg;Fn.intTime=Og;Fn.timestamp=Ju});var Ku=b(Uu=>{"use strict";var Dg=or(),Bg=An(),Lg=sr(),Vg=Yr(),Mg=Yo(),Gu=Mu(),cs=Fu(),qn=Wu(),Fg=bn(),qg=es(),Wg=Hn(),zg=as(),ls=ss(),Jg=[Dg.map,Lg.seq,Vg.string,Bg.nullTag,Gu.trueTag,Gu.falseTag,qn.intBin,qn.intOct,qn.int,qn.intHex,cs.floatNaN,cs.floatExp,cs.float,Mg.binary,Fg.merge,qg.omap,Wg.pairs,zg.set,ls.intTime,ls.floatTime,ls.timestamp];Uu.schema=Jg});var ad=b(fs=>{"use strict";var Zu=or(),Gg=An(),ed=sr(),Ug=Yr(),Kg=Fo(),us=Wo(),ds=Jo(),Yg=Ru(),Xg=Iu(),td=Yo(),ti=bn(),rd=es(),id=Hn(),Yu=Ku(),nd=as(),Wn=ss(),Xu=new Map([["core",Yg.schema],["failsafe",[Zu.map,ed.seq,Ug.string]],["json",Xg.schema],["yaml11",Yu.schema],["yaml-1.1",Yu.schema]]),Qu={binary:td.binary,bool:Kg.boolTag,float:us.float,floatExp:us.floatExp,floatNaN:us.floatNaN,floatTime:Wn.floatTime,int:ds.int,intHex:ds.intHex,intOct:ds.intOct,intTime:Wn.intTime,map:Zu.map,merge:ti.merge,null:Gg.nullTag,omap:rd.omap,pairs:id.pairs,seq:ed.seq,set:nd.set,timestamp:Wn.timestamp},Qg={"tag:yaml.org,2002:binary":td.binary,"tag:yaml.org,2002:merge":ti.merge,"tag:yaml.org,2002:omap":rd.omap,"tag:yaml.org,2002:pairs":id.pairs,"tag:yaml.org,2002:set":nd.set,"tag:yaml.org,2002:timestamp":Wn.timestamp};function Zg(e,t,r){let i=Xu.get(t);if(i&&!e)return r&&!i.includes(ti.merge)?i.concat(ti.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Xu.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(ti.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Qu[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Qu).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}fs.coreKnownTags=Qg;fs.getTags=Zg});var ms=b(od=>{"use strict";var hs=R(),ew=or(),tw=sr(),rw=Yr(),zn=ad(),iw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ps=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?zn.getTags(t,"compat"):t?zn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?zn.coreKnownTags:{},this.tags=zn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,hs.MAP,{value:ew.map}),Object.defineProperty(this,hs.SCALAR,{value:rw.string}),Object.defineProperty(this,hs.SEQ,{value:tw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?iw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};od.Schema=ps});var cd=b(sd=>{"use strict";var nw=R(),vs=Gr(),ri=qr();function aw(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=vs.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ri.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(nw.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(ri.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=vs.stringify(e.contents,n,()=>s=null,c);s&&(l+=ri.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(vs.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(r.push("..."),r.push(ri.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(ri.indentComment(a(c),"")))}return r.join(`
57
+ ${a.comment}`:i.comment}i=n}e.items[r]=Dn.isPair(i)?i:new Zo.Pair(i)}}else t("Expected a sequence for this tag");return e}function Lu(e,t,r){let{replacer:i}=r,n=new Lg.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(Zo.createPair(s,c,r))}return n}var Vg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bu,createNode:Lu};Bn.createPairs=Lu;Bn.pairs=Vg;Bn.resolvePairs=Bu});var rs=b(ts=>{"use strict";var Vu=A(),es=wt(),ei=Et(),Mg=xt(),Mu=Ln(),Ft=class e extends Mg.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=es.toJS(n.key,"",r),o=es.toJS(n.value,a,r)):a=es.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 Fg={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)};ts.YAMLOMap=Ft;ts.omap=Fg});var Ju=b(is=>{"use strict";var Fu=z();function qu({value:e,source:t},r){return t&&(e?Wu:zu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Wu={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 Fu.Scalar(!0),stringify:qu},zu={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 Fu.Scalar(!1),stringify:qu};is.falseTag=zu;is.trueTag=Wu});var Gu=b(Vn=>{"use strict";var qg=z(),ns=ur(),Wg={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:ns.stringifyNumber},zg={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():ns.stringifyNumber(e)}},Jg={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 qg.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:ns.stringifyNumber};Vn.float=Jg;Vn.floatExp=zg;Vn.floatNaN=Wg});var Ku=b(ri=>{"use strict";var Uu=ur(),ti=e=>typeof e=="bigint"||Number.isInteger(e);function Mn(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 as(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 Uu.stringifyNumber(e)}var Gg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Mn(e,2,2,r),stringify:e=>as(e,2,"0b")},Ug={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Mn(e,1,8,r),stringify:e=>as(e,8,"0")},Kg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Mn(e,0,10,r),stringify:Uu.stringifyNumber},Yg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Mn(e,2,16,r),stringify:e=>as(e,16,"0x")};ri.int=Kg;ri.intBin=Gg;ri.intHex=Yg;ri.intOct=Ug});var ss=b(os=>{"use strict";var Wn=A(),Fn=kt(),qn=Et(),qt=class e extends qn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Wn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Fn.Pair(t.key,null):r=new Fn.Pair(t,null),qn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=qn.findPair(this.items,t);return!r&&Wn.isPair(i)?Wn.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=qn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Fn.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(Fn.createPair(o,null,i));return a}};qt.tag="tag:yaml.org,2002:set";var Xg={collection:"map",identify:e=>e instanceof Set,nodeClass:qt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>qt.from(e,t,r),resolve(e,t){if(Wn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new qt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};os.YAMLSet=qt;os.set=Xg});var ls=b(zn=>{"use strict";var Qg=ur();function cs(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 Yu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Qg.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 Zg={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})=>cs(e,r),stringify:Yu},ew={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=>cs(e,!1),stringify:Yu},Xu={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(Xu.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),f=t[8];if(f&&f!=="Z"){let d=cs(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};zn.floatTime=ew;zn.intTime=Zg;zn.timestamp=Xu});var ed=b(Zu=>{"use strict";var tw=cr(),rw=Tn(),iw=lr(),nw=Qr(),aw=Qo(),Qu=Ju(),us=Gu(),Jn=Ku(),ow=En(),sw=rs(),cw=Ln(),lw=ss(),ds=ls(),uw=[tw.map,iw.seq,nw.string,rw.nullTag,Qu.trueTag,Qu.falseTag,Jn.intBin,Jn.intOct,Jn.int,Jn.intHex,us.floatNaN,us.floatExp,us.float,aw.binary,ow.merge,sw.omap,cw.pairs,lw.set,ds.intTime,ds.floatTime,ds.timestamp];Zu.schema=uw});var ud=b(hs=>{"use strict";var nd=cr(),dw=Tn(),ad=lr(),fw=Qr(),pw=Wo(),fs=Jo(),ps=Uo(),hw=ju(),mw=Hu(),od=Qo(),ii=En(),sd=rs(),cd=Ln(),td=ed(),ld=ss(),Gn=ls(),rd=new Map([["core",hw.schema],["failsafe",[nd.map,ad.seq,fw.string]],["json",mw.schema],["yaml11",td.schema],["yaml-1.1",td.schema]]),id={binary:od.binary,bool:pw.boolTag,float:fs.float,floatExp:fs.floatExp,floatNaN:fs.floatNaN,floatTime:Gn.floatTime,int:ps.int,intHex:ps.intHex,intOct:ps.intOct,intTime:Gn.intTime,map:nd.map,merge:ii.merge,null:dw.nullTag,omap:sd.omap,pairs:cd.pairs,seq:ad.seq,set:ld.set,timestamp:Gn.timestamp},vw={"tag:yaml.org,2002:binary":od.binary,"tag:yaml.org,2002:merge":ii.merge,"tag:yaml.org,2002:omap":sd.omap,"tag:yaml.org,2002:pairs":cd.pairs,"tag:yaml.org,2002:set":ld.set,"tag:yaml.org,2002:timestamp":Gn.timestamp};function gw(e,t,r){let i=rd.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(rd.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"?id[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(id).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}hs.coreKnownTags=vw;hs.getTags=gw});var gs=b(dd=>{"use strict";var ms=A(),ww=cr(),yw=lr(),Nw=Qr(),Un=ud(),bw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,vs=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Un.getTags(t,"compat"):t?Un.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Un.coreKnownTags:{},this.tags=Un.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,ms.MAP,{value:ww.map}),Object.defineProperty(this,ms.SCALAR,{value:Nw.string}),Object.defineProperty(this,ms.SEQ,{value:yw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?bw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};dd.Schema=vs});var pd=b(fd=>{"use strict";var kw=A(),ws=Kr(),ni=zr();function Sw(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=ws.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(kw.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(ni.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ws.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(ws.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
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
- `}sd.stringifyDocument=aw});var ii=b(ld=>{"use strict";var ow=Mr(),lr=dn(),Se=R(),sw=yt(),cw=mt(),lw=ms(),uw=cd(),gs=sn(),dw=bo(),fw=Fr(),ws=No(),ys=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Se.NODE_TYPE,{value:Se.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 ws.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,{[Se.NODE_TYPE]:{value:Se.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=Se.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){ur(this.contents)&&this.contents.add(t)}addIn(t,r){ur(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=gs.anchorNames(this);t.anchor=!r||i.has(r)?gs.findNewAnchor(r||"a",i):r}return new ow.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 p=g=>typeof g=="number"||g instanceof String||g instanceof Number,y=r.filter(p).map(String);y.length>0&&(r=r.concat(y)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:d,setAnchors:u,sourceObjects:h}=gs.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=fw.createNode(t,f,v);return s&&Se.isCollection(m)&&(m.flow=!0),u(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new sw.Pair(n,a)}delete(t){return ur(this.contents)?this.contents.delete(t):!1}deleteIn(t){return lr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):ur(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Se.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return lr.isEmptyPath(t)?!r&&Se.isScalar(this.contents)?this.contents.value:this.contents:Se.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Se.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return lr.isEmptyPath(t)?this.contents!==void 0:Se.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=lr.collectionFromPath(this.schema,[t],r):ur(this.contents)&&this.contents.set(t,r)}setIn(t,r){lr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=lr.collectionFromPath(this.schema,Array.from(t),r):ur(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 ws.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 ws.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 lw.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=cw.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?dw.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 uw.stringifyDocument(this,t)}};function ur(e){if(Se.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ld.Document=ys});var oi=b(ai=>{"use strict";var ni=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Ns=class extends ni{constructor(t,r,i){super("YAMLParseError",t,r,i)}},bs=class extends ni{constructor(t,r,i){super("YAMLWarning",t,r,i)}},hw=(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)+`…
60
+ `}fd.stringifyDocument=Sw});var ai=b(hd=>{"use strict";var Ew=qr(),dr=hn(),Ee=A(),xw=kt(),Cw=wt(),Pw=gs(),Rw=pd(),ys=un(),Aw=So(),_w=Wr(),Ns=ko(),bs=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ee.NODE_TYPE,{value:Ee.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 Ns.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,{[Ee.NODE_TYPE]:{value:Ee.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=Ee.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=ys.anchorNames(this);t.anchor=!r||i.has(r)?ys.findNewAnchor(r||"a",i):r}return new Ew.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 h=g=>typeof g=="number"||g instanceof String||g instanceof Number,w=r.filter(h).map(String);w.length>0&&(r=r.concat(w)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=ys.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},m=_w.createNode(t,f,v);return s&&Ee.isCollection(m)&&(m.flow=!0),u(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new xw.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 Ee.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return dr.isEmptyPath(t)?!r&&Ee.isScalar(this.contents)?this.contents.value:this.contents:Ee.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Ee.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return dr.isEmptyPath(t)?this.contents!==void 0:Ee.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 Ns.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 Ns.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 Pw.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=Cw.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Aw.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 Rw.stringifyDocument(this,t)}};function fr(e){if(Ee.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}hd.Document=bs});var ci=b(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}},ks=class extends oi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ss=class extends oi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Iw=(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)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};ai.YAMLError=ni;ai.YAMLParseError=Ns;ai.YAMLWarning=bs;ai.prettifyError=hw});var si=b(ud=>{"use strict";function pw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",h=!1,v=!1,m=null,p=null,y=null,g=null,w=null,k=null,S=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),f=!0;break;case"comment":{f||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=N.source.substring(1)||" ";d?d+=u+_:d=_,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||r!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,h=!0,(p||y)&&(g=N),f=!0;break;case"anchor":p&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{y&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),y=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case r:(p||y)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),k=N,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){w&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=e[e.length-1],x=E?E.offset+E.source.length:n;return v&&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"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:k,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:y,newlineAfterProp:g,end:x,start:S??x}}ud.resolveProps=pw});var Jn=b(dd=>{"use strict";function ks(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(ks(t.key)||ks(t.value))return!0}return!1;default:return!0}}dd.containsNewline=ks});var Ss=b(fd=>{"use strict";var mw=Jn();function vw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&mw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}fd.flowIndentCheck=vw});var Es=b(pd=>{"use strict";var hd=R();function gw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||hd.isScalar(a)&&hd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}pd.mapIncludes=gw});var Nd=b(yd=>{"use strict";var md=yt(),ww=bt(),vd=si(),yw=Jn(),gd=Ss(),Nw=Es(),wd="All mapping items must start at the same column";function bw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??ww.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:d,key:u,sep:h,value:v}=f,m=vd.resolveProps(d,{indicator:"explicit-key-ind",next:u??h?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),p=!m.found;if(p){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==i.indent&&n(c,"BAD_INDENT",wd)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
67
- `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||yw.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",wd);r.atKey=!0;let y=m.end,g=u?e(r,u,m,n):t(r,y,d,null,m,n);r.schema.compat&&gd.flowIndentCheck(i.indent,u,n),r.atKey=!1,Nw.mapIncludes(r,s.items,g)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let w=vd.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=w.end,w.found){p&&(v?.type==="block-map"&&!w.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<w.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(r,v,w,n):t(r,c,h,null,w,n);r.schema.compat&&gd.flowIndentCheck(i.indent,v,n),c=k.range[2];let S=new md.Pair(g,k);r.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(g.comment?g.comment+=`
68
- `+w.comment:g.comment=w.comment);let k=new md.Pair(g);r.options.keepSourceTokens&&(k.srcToken=f),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}yd.resolveBlockMap=bw});var kd=b(bd=>{"use strict";var kw=kt(),Sw=si(),Ew=Ss();function xw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??kw.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:f,value:d}of i.items){let u=Sw.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let h=d?e(r,d,u,n):t(r,u.end,f,null,u,n);r.schema.compat&&Ew.flowIndentCheck(i.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[i.offset,c,l??c],s}bd.resolveBlockSeq=xw});var dr=b(Sd=>{"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 f=c.substring(1)||" ";n?n+=o+f:n=f,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}}Sd.resolveEnd=Pw});var Cd=b(Pd=>{"use strict";var Cw=R(),Rw=yt(),Ed=bt(),Aw=kt(),_w=dr(),xd=si(),Iw=Jn(),Tw=Es(),xs="Block collections are not allowed within flow collections",Ps=e=>e&&(e.type==="block-map"||e.type==="block-seq");function jw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ed.YAMLMap:Aw.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let p=0;p<i.items.length;++p){let y=i.items[p],{start:g,key:w,sep:k,value:S}=y,E=xd.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:w??k?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
- `+E.comment:l.comment=E.comment),d=E.end;continue}!o&&r.options.strict&&Iw.containsNewline(w)&&n(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let x="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":x=N.source.substring(1);break e;default:break e}if(x){let N=l.items[l.items.length-1];Cw.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
- `+x:N.comment=x,E.comment=E.comment.substring(x.length+1)}}if(!o&&!k&&!E.found){let x=S?e(r,S,E,n):t(r,E.end,k,null,E,n);l.items.push(x),d=x.range[2],Ps(S)&&n(x.range,"BLOCK_IN_FLOW",xs)}else{r.atKey=!0;let x=E.end,N=w?e(r,w,E,n):t(r,x,g,null,E,n);Ps(w)&&n(N.range,"BLOCK_IN_FLOW",xs),r.atKey=!1;let _=xd.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(_.found){if(!o&&!E.found&&r.options.strict){if(k)for(let $ of k){if($===_.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<_.found.offset-1024&&n(_.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(_.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Y=S?e(r,S,_,n):_.found?t(r,_.end,k,null,_,n):null;Y?Ps(S)&&n(Y.range,"BLOCK_IN_FLOW",xs):_.comment&&(N.comment?N.comment+=`
71
- `+_.comment:N.comment=_.comment);let ee=new Rw.Pair(N,Y);if(r.options.keepSourceTokens&&(ee.srcToken=y),o){let $=l;Tw.mapIncludes(r,$.items,N)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(ee)}else{let $=new Ed.YAMLMap(r.schema);$.flow=!0,$.items.push(ee);let Pl=(Y??N).range;$.range=[N.range[0],Pl[1],Pl[2]],l.items.push($)}d=Y?Y.range[2]:_.end}}let u=o?"}":"]",[h,...v]=i.end,m=d;if(h?.source===u)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),y=f?`${p} must end with a ${u}`:`${p} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let p=_w.resolveEnd(v,m,r.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
- `+p.comment:l.comment=p.comment),l.range=[i.offset,m,p.offset]}else l.range=[i.offset,m,m];return l}Pd.resolveFlowCollection=jw});var Ad=b(Rd=>{"use strict";var $w=R(),Ow=W(),Hw=bt(),Dw=kt(),Bw=Nd(),Lw=kd(),Vw=Cd();function Cs(e,t,r,i,n,a){let o=r.type==="block-map"?Bw.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Lw.resolveBlockSeq(e,t,r,i,a):Vw.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 Mw(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(r.type==="block-seq"){let{anchor:u,newlineAfterProp:h}=i,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!h||h.offset<v.offset)&&n(v,"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===Hw.YAMLMap.tagName&&s==="map"||o===Dw.YAMLSeq.tagName&&s==="seq")return Cs(e,t,r,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Cs(e,t,r,n,o)}let l=Cs(e,t,r,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=$w.isNode(f)?f:new Ow.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Rd.composeCollection=Mw});var As=b(_d=>{"use strict";var Rs=W();function Fw(e,t,r){let i=t.offset,n=qw(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Rs.Scalar.BLOCK_FOLDED:Rs.Scalar.BLOCK_LITERAL,o=t.source?Ww(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",p=i+n.length;return t.source&&(p+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let m=0;m<s;++m){let[p,y]=o[m];if(y===""||y==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&r(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),f=m,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+y.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",u="",h=!1;for(let m=0;m<f;++m)d+=o[m][0].slice(c)+`
74
- `;for(let m=f;m<s;++m){let[p,y]=o[m];l+=p.length+y.length+1;let g=y[y.length-1]==="\r";if(g&&(y=y.slice(0,-1)),y&&p.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(g?2:1),"BAD_INDENT",k),p=""}a===Rs.Scalar.BLOCK_LITERAL?(d+=u+p.slice(c)+y,u=`
75
- `):p.length>c||y[0]===" "?(u===" "?u=`
76
- `:!h&&u===`
65
+ `}};si.YAMLError=oi;si.YAMLParseError=ks;si.YAMLWarning=Ss;si.prettifyError=Iw});var li=b(md=>{"use strict";function Tw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,v=!1,m=null,h=null,w=null,g=null,y=null,k=null,S=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),f=!0;break;case"comment":{f||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=N.source.substring(1)||" ";d?d+=u+I:d=I,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||r!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,p=!0,(h||w)&&(g=N),f=!0;break;case"anchor":h&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),w=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case r:(h||w)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),k=N,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){y&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=e[e.length-1],x=E?E.offset+E.source.length:n;return v&&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"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:h,tag:w,newlineAfterProp:g,end:x,start:S??x}}md.resolveProps=Tw});var Kn=b(vd=>{"use strict";function Es(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(Es(t.key)||Es(t.value))return!0}return!1;default:return!0}}vd.containsNewline=Es});var xs=b(gd=>{"use strict";var jw=Kn();function $w(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&jw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}gd.flowIndentCheck=$w});var Cs=b(yd=>{"use strict";var wd=A();function Ow(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||wd.isScalar(a)&&wd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}yd.mapIncludes=Ow});var xd=b(Ed=>{"use strict";var Nd=kt(),Hw=Et(),bd=li(),Dw=Kn(),kd=xs(),Bw=Cs(),Sd="All mapping items must start at the same column";function Lw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Hw.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:d,key:u,sep:p,value:v}=f,m=bd.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),h=!m.found;if(h){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==i.indent&&n(c,"BAD_INDENT",Sd)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(s.comment?s.comment+=`
67
+ `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||Dw.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",Sd);r.atKey=!0;let w=m.end,g=u?e(r,u,m,n):t(r,w,d,null,m,n);r.schema.compat&&kd.flowIndentCheck(i.indent,u,n),r.atKey=!1,Bw.mapIncludes(r,s.items,g)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let y=bd.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=y.end,y.found){h&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(r,v,y,n):t(r,c,p,null,y,n);r.schema.compat&&kd.flowIndentCheck(i.indent,v,n),c=k.range[2];let S=new Nd.Pair(g,k);r.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}else{h&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
68
+ `+y.comment:g.comment=y.comment);let k=new Nd.Pair(g);r.options.keepSourceTokens&&(k.srcToken=f),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Ed.resolveBlockMap=Lw});var Pd=b(Cd=>{"use strict";var Vw=xt(),Mw=li(),Fw=xs();function qw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Vw.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:f,value:d}of i.items){let u=Mw.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?e(r,d,u,n):t(r,u.end,f,null,u,n);r.schema.compat&&Fw.flowIndentCheck(i.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}Cd.resolveBlockSeq=qw});var pr=b(Rd=>{"use strict";function Ww(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 f=c.substring(1)||" ";n?n+=o+f:n=f,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}}Rd.resolveEnd=Ww});var Td=b(Id=>{"use strict";var zw=A(),Jw=kt(),Ad=Et(),Gw=xt(),Uw=pr(),_d=li(),Kw=Kn(),Yw=Cs(),Ps="Block collections are not allowed within flow collections",Rs=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Xw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ad.YAMLMap:Gw.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let h=0;h<i.items.length;++h){let w=i.items[h],{start:g,key:y,sep:k,value:S}=w,E=_d.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??k?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){h===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):h<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
+ `+E.comment:l.comment=E.comment),d=E.end;continue}!o&&r.options.strict&&Kw.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let x="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":x=N.source.substring(1);break e;default:break e}if(x){let N=l.items[l.items.length-1];zw.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
+ `+x:N.comment=x,E.comment=E.comment.substring(x.length+1)}}if(!o&&!k&&!E.found){let x=S?e(r,S,E,n):t(r,E.end,k,null,E,n);l.items.push(x),d=x.range[2],Rs(S)&&n(x.range,"BLOCK_IN_FLOW",Ps)}else{r.atKey=!0;let x=E.end,N=y?e(r,y,E,n):t(r,x,g,null,E,n);Rs(y)&&n(N.range,"BLOCK_IN_FLOW",Ps),r.atKey=!1;let I=_d.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(I.found){if(!o&&!E.found&&r.options.strict){if(k)for(let O of k){if(O===I.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.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 S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(I.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let X=S?e(r,S,I,n):I.found?t(r,I.end,k,null,I,n):null;X?Rs(S)&&n(X.range,"BLOCK_IN_FLOW",Ps):I.comment&&(N.comment?N.comment+=`
71
+ `+I.comment:N.comment=I.comment);let te=new Jw.Pair(N,X);if(r.options.keepSourceTokens&&(te.srcToken=w),o){let O=l;Yw.mapIncludes(r,O.items,N)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(te)}else{let O=new Ad.YAMLMap(r.schema);O.flow=!0,O.items.push(te);let Il=(X??N).range;O.range=[N.range[0],Il[1],Il[2]],l.items.push(O)}d=X?X.range[2]:I.end}}let u=o?"}":"]",[p,...v]=i.end,m=d;if(p?.source===u)m=p.offset+p.source.length;else{let h=s[0].toUpperCase()+s.substring(1),w=f?`${h} must end with a ${u}`:`${h} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let h=Uw.resolveEnd(v,m,r.options.strict,n);h.comment&&(l.comment?l.comment+=`
72
+ `+h.comment:l.comment=h.comment),l.range=[i.offset,m,h.offset]}else l.range=[i.offset,m,m];return l}Id.resolveFlowCollection=Xw});var $d=b(jd=>{"use strict";var Qw=A(),Zw=z(),ey=Et(),ty=xt(),ry=xd(),iy=Pd(),ny=Td();function As(e,t,r,i,n,a){let o=r.type==="block-map"?ry.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?iy.resolveBlockSeq(e,t,r,i,a):ny.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 ay(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(r.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=i,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offset<v.offset)&&n(v,"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===ey.YAMLMap.tagName&&s==="map"||o===ty.YAMLSeq.tagName&&s==="seq")return As(e,t,r,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),As(e,t,r,n,o)}let l=As(e,t,r,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=Qw.isNode(f)?f:new Zw.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}jd.composeCollection=ay});var Is=b(Od=>{"use strict";var _s=z();function oy(e,t,r){let i=t.offset,n=sy(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?_s.Scalar.BLOCK_FOLDED:_s.Scalar.BLOCK_LITERAL,o=t.source?cy(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let h=o[m][1];if(h===""||h==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",h=i+n.length;return t.source&&(h+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,h,h]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let m=0;m<s;++m){let[h,w]=o[m];if(w===""||w==="\r")n.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&r(l+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=h.length),f=m,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=h.length+w.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",u="",p=!1;for(let m=0;m<f;++m)d+=o[m][0].slice(c)+`
74
+ `;for(let m=f;m<s;++m){let[h,w]=o[m];l+=h.length+w.length+1;let g=w[w.length-1]==="\r";if(g&&(w=w.slice(0,-1)),w&&h.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(g?2:1),"BAD_INDENT",k),h=""}a===_s.Scalar.BLOCK_LITERAL?(d+=u+h.slice(c)+w,u=`
75
+ `):h.length>c||w[0]===" "?(u===" "?u=`
76
+ `:!p&&u===`
77
77
  `&&(u=`
78
78
 
79
- `),d+=u+p.slice(c)+y,u=`
80
- `,h=!0):y===""?u===`
79
+ `),d+=u+h.slice(c)+w,u=`
80
+ `,p=!0):w===""?u===`
81
81
  `?d+=`
82
82
  `:u=`
83
- `:(d+=u+y,u=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)d+=`
83
+ `:(d+=u+w,u=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)d+=`
84
84
  `+o[m][0].slice(c);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let v=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,v,v]}}function qw({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let u=1;u<n.length;++u){let h=n[u];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+u)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",d=n.length;for(let u=1;u<t.length;++u){let h=t[u];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":r&&!l&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,f=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",v);let m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:d}}function Ww(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}_d.resolveBlockScalar=Fw});var Is=b(Td=>{"use strict";var _s=W(),zw=dr();function Jw(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(u,h,v)=>r(i+u,h,v);switch(n){case"scalar":s=_s.Scalar.PLAIN,c=Gw(a,l);break;case"single-quoted-scalar":s=_s.Scalar.QUOTE_SINGLE,c=Uw(a,l);break;case"double-quoted-scalar":s=_s.Scalar.QUOTE_DOUBLE,c=Kw(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,d=zw.resolveEnd(o,f,t,r);return{value:c,type:s,comment:d.comment,range:[i,f,d.offset]}}function Gw(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Id(e)}function Uw(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Id(e.slice(1,-1)).replace(/''/g,"'")}function Id(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,v,v]}}function sy({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let u=1;u<n.length;++u){let p=n[u];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+u)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",d=n.length;for(let u=1;u<t.length;++u){let p=t[u];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":r&&!l&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,f=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",v);let m=p.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:d}}function cy(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Od.resolveBlockScalar=oy});var js=b(Dd=>{"use strict";var Ts=z(),ly=pr();function uy(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(u,p,v)=>r(i+u,p,v);switch(n){case"scalar":s=Ts.Scalar.PLAIN,c=dy(a,l);break;case"single-quoted-scalar":s=Ts.Scalar.QUOTE_SINGLE,c=fy(a,l);break;case"double-quoted-scalar":s=Ts.Scalar.QUOTE_DOUBLE,c=py(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,d=ly.resolveEnd(o,f,t,r);return{value:c,type:s,comment:d.comment,range:[i,f,d.offset]}}function dy(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Hd(e)}function fy(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Hd(e.slice(1,-1)).replace(/''/g,"'")}function Hd(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function Kw(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
91
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function py(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=Yw(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Xw[a];if(o)r+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=hy(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=my[a];if(o)r+=o;else if(a===`
94
94
  `)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
95
- `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Qw(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
95
+ `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=vy(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
96
96
  `&&!(o==="\r"&&e[i+2]===`
97
- `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function Yw(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
97
+ `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function hy(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
98
98
  `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
99
99
  `);)i===`
100
100
  `&&(r+=`
101
- `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Xw={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Qw(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Td.resolveFlowScalar=Jw});var Od=b($d=>{"use strict";var Ft=R(),jd=W(),Zw=As(),ey=Is();function ty(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Zw.resolveBlockScalar(e,t,i):ey.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Ft.SCALAR]:c?l=ry(e.schema,n,c,r,i):t.type==="scalar"?l=iy(e,n,t,i):l=e.schema[Ft.SCALAR];let f;try{let d=l.resolve(n,u=>i(r??t,"TAG_RESOLVE_FAILED",u),e.options);f=Ft.isScalar(d)?d:new jd.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",u),f=new jd.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function ry(e,t,r,i,n){if(r==="!")return e[Ft.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Ft.SCALAR])}function iy({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Ft.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Ft.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}$d.composeScalar=ty});var Dd=b(Hd=>{"use strict";function ny(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Hd.emptyScalarPosition=ny});var Vd=b(js=>{"use strict";var ay=Mr(),oy=R(),sy=Ad(),Bd=Od(),cy=dr(),ly=Dd(),uy={composeNode:Ld,composeEmptyNode:Ts};function Ld(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=dy(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Bd.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=sy.composeCollection(uy,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",u)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=Ts(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!oy.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Ts(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:ly.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Bd.composeScalar(e,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function dy({options:e},{offset:t,source:r,end:i},n){let a=new ay.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=cy.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}js.composeEmptyNode=Ts;js.composeNode=Ld});var qd=b(Fd=>{"use strict";var fy=ii(),Md=Vd(),hy=dr(),py=si();function my(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new fy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=py.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Md.composeNode(l,n,f,o):Md.composeEmptyNode(l,f.end,i,null,f,o);let d=c.contents.range[2],u=hy.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[r,d,u.offset],c}Fd.composeDoc=my});var Os=b(Jd=>{"use strict";var vy=tn("process"),gy=No(),wy=ii(),ci=oi(),Wd=R(),yy=qd(),Ny=dr();function li(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function zd(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
101
+ `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var my={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function vy(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Dd.resolveFlowScalar=uy});var Vd=b(Ld=>{"use strict";var Wt=A(),Bd=z(),gy=Is(),wy=js();function yy(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?gy.resolveBlockScalar(e,t,i):wy.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Wt.SCALAR]:c?l=Ny(e.schema,n,c,r,i):t.type==="scalar"?l=by(e,n,t,i):l=e.schema[Wt.SCALAR];let f;try{let d=l.resolve(n,u=>i(r??t,"TAG_RESOLVE_FAILED",u),e.options);f=Wt.isScalar(d)?d:new Bd.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",u),f=new Bd.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Ny(e,t,r,i,n){if(r==="!")return e[Wt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Wt.SCALAR])}function by({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Wt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Wt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Ld.composeScalar=yy});var Fd=b(Md=>{"use strict";function ky(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Md.emptyScalarPosition=ky});var zd=b(Os=>{"use strict";var Sy=qr(),Ey=A(),xy=$d(),qd=Vd(),Cy=pr(),Py=Fd(),Ry={composeNode:Wd,composeEmptyNode:$s};function Wd(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=Ay(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=qd.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=xy.composeCollection(Ry,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",u)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=$s(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Ey.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function $s(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Py.emptyScalarPosition(t,r,i),indent:-1,source:""},d=qd.composeScalar(e,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Ay({options:e},{offset:t,source:r,end:i},n){let a=new Sy.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=Cy.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Os.composeEmptyNode=$s;Os.composeNode=Wd});var Ud=b(Gd=>{"use strict";var _y=ai(),Jd=zd(),Iy=pr(),Ty=li();function jy(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new _y.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Ty.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Jd.composeNode(l,n,f,o):Jd.composeEmptyNode(l,f.end,i,null,f,o);let d=c.contents.range[2],u=Iy.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[r,d,u.offset],c}Gd.composeDoc=jy});var Ds=b(Xd=>{"use strict";var $y=an("process"),Oy=ko(),Hy=ai(),ui=ci(),Kd=A(),Dy=Ud(),By=pr();function di(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function Yd(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var $s=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=li(r);a?this.warnings.push(new ci.YAMLWarning(o,i,n)):this.errors.push(new ci.YAMLParseError(o,i,n))},this.directives=new gy.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=zd(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
- ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Wd.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Wd.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
105
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var Hs=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=di(r);a?this.warnings.push(new ui.YAMLWarning(o,i,n)):this.errors.push(new ui.YAMLParseError(o,i,n))},this.directives=new Oy.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Yd(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
+ ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Kd.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Kd.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
107
107
  ${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
108
- ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:zd(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(vy.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=li(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=yy.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new ci.YAMLParseError(li(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new ci.YAMLParseError(li(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=Ny.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
- ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new ci.YAMLParseError(li(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new wy.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};Jd.Composer=$s});var Kd=b(Gn=>{"use strict";var by=As(),ky=Is(),Sy=oi(),Gd=Jr();function Ey(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new Sy.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ky.resolveFlowScalar(e,t,i);case"block-scalar":return by.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function xy(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Gd.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
108
+ ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Yd(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch($y.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=di(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=Dy.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new ui.YAMLParseError(di(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new ui.YAMLParseError(di(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=By.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new ui.YAMLParseError(di(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new Hy.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};Xd.Composer=Hs});var ef=b(Yn=>{"use strict";var Ly=Is(),Vy=js(),My=ci(),Qd=Ur();function Fy(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new My.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Vy.resolveFlowScalar(e,t,i);case"block-scalar":return Ly.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function qy(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Qd.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),f=s.substring(0,l),d=s.substring(l+1)+`
112
- `,u=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return Ud(u,c)||u.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:u,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function Py(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Gd.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Cy(e,c);break;case'"':Hs(e,c,"double-quoted-scalar");break;case"'":Hs(e,c,"single-quoted-scalar");break;default:Hs(e,c,"scalar")}}function Cy(e,t){let r=t.indexOf(`
112
+ `,u=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return Zd(u,c)||u.push({type:"newline",offset:-1,indent:i,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:i,props:u,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function Wy(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Qd.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":zy(e,c);break;case'"':Bs(e,c,"double-quoted-scalar");break;case"'":Bs(e,c,"single-quoted-scalar");break;default:Bs(e,c,"scalar")}}function zy(e,t){let r=t.indexOf(`
114
114
  `),i=t.substring(0,r),n=t.substring(r+1)+`
115
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Ud(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Ud(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Hs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Gn.createScalarToken=xy;Gn.resolveAsScalar=Ey;Gn.setScalarValue=Py});var Xd=b(Yd=>{"use strict";var Ry=e=>"type"in e?Kn(e):Un(e);function Kn(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Kn(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Un(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Un(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Un(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Un({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Kn(t)),r)for(let a of r)n+=a.source;return i&&(n+=Kn(i)),n}Yd.stringify=Ry});var tf=b(ef=>{"use strict";var Ds=Symbol("break visit"),Ay=Symbol("skip children"),Qd=Symbol("remove item");function qt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Zd(Object.freeze([]),e,t)}qt.BREAK=Ds;qt.SKIP=Ay;qt.REMOVE=Qd;qt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};qt.parentCollection=(e,t)=>{let r=qt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Zd(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Zd(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Ds)return Ds;s===Qd&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}ef.visit=qt});var Yn=b(he=>{"use strict";var Bs=Kd(),_y=Xd(),Iy=tf(),Ls="\uFEFF",Vs="",Ms="",Fs="",Ty=e=>!!e&&"items"in e,jy=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function $y(e){switch(e){case Ls:return"<BOM>";case Vs:return"<DOC>";case Ms:return"<FLOW_END>";case Fs:return"<SCALAR>";default:return JSON.stringify(e)}}function Oy(e){switch(e){case Ls:return"byte-order-mark";case Vs:return"doc-mode";case Ms:return"flow-error-end";case Fs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
115
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Zd(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Zd(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Bs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Yn.createScalarToken=qy;Yn.resolveAsScalar=Fy;Yn.setScalarValue=Wy});var rf=b(tf=>{"use strict";var Jy=e=>"type"in e?Qn(e):Xn(e);function Qn(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Qn(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Xn(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Xn(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Xn(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Xn({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Qn(t)),r)for(let a of r)n+=a.source;return i&&(n+=Qn(i)),n}tf.stringify=Jy});var sf=b(of=>{"use strict";var Ls=Symbol("break visit"),Gy=Symbol("skip children"),nf=Symbol("remove item");function zt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),af(Object.freeze([]),e,t)}zt.BREAK=Ls;zt.SKIP=Gy;zt.REMOVE=nf;zt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};zt.parentCollection=(e,t)=>{let r=zt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function af(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=af(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Ls)return Ls;s===nf&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}of.visit=zt});var Zn=b(he=>{"use strict";var Vs=ef(),Uy=rf(),Ky=sf(),Ms="\uFEFF",Fs="",qs="",Ws="",Yy=e=>!!e&&"items"in e,Xy=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Qy(e){switch(e){case Ms:return"<BOM>";case Fs:return"<DOC>";case qs:return"<FLOW_END>";case Ws:return"<SCALAR>";default:return JSON.stringify(e)}}function Zy(e){switch(e){case Ms:return"byte-order-mark";case Fs:return"doc-mode";case qs:return"flow-error-end";case Ws:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}he.createScalarToken=Bs.createScalarToken;he.resolveAsScalar=Bs.resolveAsScalar;he.setScalarValue=Bs.setScalarValue;he.stringify=_y.stringify;he.visit=Iy.visit;he.BOM=Ls;he.DOCUMENT=Vs;he.FLOW_END=Ms;he.SCALAR=Fs;he.isCollection=Ty;he.isScalar=jy;he.prettyToken=$y;he.tokenType=Oy});var zs=b(nf=>{"use strict";var ui=Yn();function Ie(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var rf=new Set("0123456789ABCDEFabcdef"),Hy=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Xn=new Set(",[]{}"),Dy=new Set(` ,[]{}
121
- \r `),qs=e=>!e||Dy.has(e),Ws=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}he.createScalarToken=Vs.createScalarToken;he.resolveAsScalar=Vs.resolveAsScalar;he.setScalarValue=Vs.setScalarValue;he.stringify=Uy.stringify;he.visit=Ky.visit;he.BOM=Ms;he.DOCUMENT=Fs;he.FLOW_END=qs;he.SCALAR=Ws;he.isCollection=Yy;he.isScalar=Xy;he.prettyToken=Qy;he.tokenType=Zy});var Gs=b(lf=>{"use strict";var fi=Zn();function Te(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var cf=new Set("0123456789ABCDEFabcdef"),eN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ea=new Set(",[]{}"),tN=new Set(` ,[]{}
121
+ \r `),zs=e=>!e||tN.has(e),Js=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+i+1}return r===`
125
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ie(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===ui.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield ui.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Ie(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ie(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ie(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(qs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Ie(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield ui.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(qs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ie(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
125
+ `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Te(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===fi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield fi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Te(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Te(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Te(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(zs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Te(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield fi.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(zs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Te(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
- `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Ie(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
128
+ `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Te(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
129
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
130
  `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
131
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
132
132
  `;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield ui.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Ie(a)||t&&Xn.has(a))break;r=i}else if(Ie(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield fi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Te(a)||t&&ea.has(a))break;r=i}else if(Te(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
134
  `?(i+=1,n=`
135
- `,a=this.buffer[i+1]):r=i),a==="#"||t&&Xn.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Xn.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ui.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(qs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ie(i)||r&&Xn.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(;!Ie(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(Hy.has(r))r=this.buffer[++t];else if(r==="%"&&rf.has(this.buffer[t+1])&&rf.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===`
135
+ `,a=this.buffer[i+1]):r=i),a==="#"||t&&ea.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&ea.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(zs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Te(i)||r&&ea.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(;!Te(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(eN.has(r))r=this.buffer[++t];else if(r==="%"&&cf.has(this.buffer[t+1])&&cf.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)}};nf.Lexer=Ws});var Gs=b(af=>{"use strict";var Js=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}}}};af.LineCounter=Js});var Ks=b(uf=>{"use strict";var By=tn("process"),of=Yn(),Ly=zs();function St(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function sf(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 lf(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 Qn(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 fr(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 Zn(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 cf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!St(t.start,"explicit-key-ind")&&!St(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,lf(t.value)?t.value.end?Zn(t.value.end,t.sep):t.value.end=t.sep:Zn(t.start,t.sep),delete t.sep)}var Us=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 Ly.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,By.env.LOG_TOKENS&&console.log("|",of.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=of.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"&&cf(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&&sf(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":{sf(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=Qn(this.peek(2)),i=fr(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)}};lf.Lexer=Js});var Ks=b(uf=>{"use strict";var Us=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}}}};uf.LineCounter=Us});var Xs=b(mf=>{"use strict";var rN=an("process"),df=Zn(),iN=Gs();function Ct(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function ff(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 hf(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 ta(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 ra(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 pf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ct(t.start,"explicit-key-ind")&&!Ct(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,hf(t.value)?t.value.end?ra(t.value.end,t.sep):t.value.end=t.sep:ra(t.start,t.sep),delete t.sep)}var Ys=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 iN.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,rN.env.LOG_TOKENS&&console.log("|",df.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=df.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"&&pf(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&&ff(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":{ff(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=ta(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
- `,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)){Zn(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(St(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(lf(r.key)&&!St(r.sep,"newline")){let o=fr(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(St(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=fr(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]}):St(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&&!St(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)){Zn(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||St(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=Qn(i),a=fr(n);cf(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(`
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)){ra(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(Ct(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(hf(r.key)&&!Ct(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(Ct(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]}):Ct(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&&!Ct(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)){ra(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||Ct(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=ta(i),a=hr(n);pf(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=Qn(t),i=fr(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=Qn(t),i=fr(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())}}};uf.Parser=Us});var mf=b(fi=>{"use strict";var df=Os(),Vy=ii(),di=oi(),My=jo(),Fy=R(),qy=Gs(),ff=Ks();function hf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qy.LineCounter||null,prettyErrors:t}}function Wy(e,t={}){let{lineCounter:r,prettyErrors:i}=hf(t),n=new ff.Parser(r?.addNewLine),a=new df.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(di.prettifyError(e,r)),s.warnings.forEach(di.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function pf(e,t={}){let{lineCounter:r,prettyErrors:i}=hf(t),n=new ff.Parser(r?.addNewLine),a=new df.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 di.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(di.prettifyError(e,r)),o.warnings.forEach(di.prettifyError(e,r))),o}function zy(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=pf(e,r);if(!n)return null;if(n.warnings.forEach(a=>My.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 Jy(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 Fy.isDocument(e)&&!i?e.toString(r):new Vy.Document(e,i,r).toString(r)}fi.parse=zy;fi.parseAllDocuments=Wy;fi.parseDocument=pf;fi.stringify=Jy});var hr=b(I=>{"use strict";var Gy=Os(),Uy=ii(),Ky=ms(),Ys=oi(),Yy=Mr(),Et=R(),Xy=yt(),Qy=W(),Zy=bt(),eN=kt(),tN=Yn(),rN=zs(),iN=Gs(),nN=Ks(),ea=mf(),vf=Dr();I.Composer=Gy.Composer;I.Document=Uy.Document;I.Schema=Ky.Schema;I.YAMLError=Ys.YAMLError;I.YAMLParseError=Ys.YAMLParseError;I.YAMLWarning=Ys.YAMLWarning;I.Alias=Yy.Alias;I.isAlias=Et.isAlias;I.isCollection=Et.isCollection;I.isDocument=Et.isDocument;I.isMap=Et.isMap;I.isNode=Et.isNode;I.isPair=Et.isPair;I.isScalar=Et.isScalar;I.isSeq=Et.isSeq;I.Pair=Xy.Pair;I.Scalar=Qy.Scalar;I.YAMLMap=Zy.YAMLMap;I.YAMLSeq=eN.YAMLSeq;I.CST=tN;I.Lexer=rN.Lexer;I.LineCounter=iN.LineCounter;I.Parser=nN.Parser;I.parse=ea.parse;I.parseAllDocuments=ea.parseAllDocuments;I.parseDocument=ea.parseDocument;I.stringify=ea.stringify;I.visit=vf.visit;I.visitAsync=vf.visitAsync});var Qc=Hr(hr(),1);import{promises as tp}from"node:fs";import Ae from"node:path";import{execFileSync as aN}from"child_process";import hi from"path";function xt(e,t){return aN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function oN(e,t){let r=hi.normalize(e),i=hi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function F(e){try{let t=hi.resolve(xt(e,["rev-parse","--show-toplevel"])),i=xt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?hi.resolve(i.slice(9)):t,a=null;try{a=xt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!oN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ta(e){try{xt(e,["rev-parse","--is-inside-work-tree"]);let t=xt(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:hi.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 ta(e).map(t=>t.root)}function pr(e,t){try{return xt(e,["check-ref-format","--branch",t]),xt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function mr(e,t){try{let r=xt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as sN}from"node:child_process";var cN=3e4,lN=8*1024*1024,Xs=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};function uN(e,t){try{return sN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:cN,maxBuffer:lN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Xs(e,t,i)}}function A(e,t){return uN(e,t).trim()}function at(e){return A(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Qs(e,t){A(e,["check-ref-format","--branch",t])}import{createHash as pN}from"node:crypto";import{promises as Te}from"node:fs";import Ee from"node:path";import{TextDecoder as mN}from"node:util";var dN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),fN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function hN(e){return e.toLowerCase().startsWith(".env")}function pi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>hN(i))?"environment-file":r.some(i=>fN.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>dN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function Pt(e){return e!==0&&e!==0n&&e!=="0"}function ze(e,t){return Pt(e.dev)&&Pt(t.dev)&&Pt(e.ino)&&Pt(t.ino)}function V(e,t){let r=Pt(e.dev)&&Pt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Pt(e.ino)&&Pt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var ia=1024*1024;function Zs(e,t){let r=Ee.relative(e,t);return r===""||!Ee.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ee.sep}`)}function vN(e){let t=Ee.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})||Ee.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=pi(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 gN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function wN(e,t){return V({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ra(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return ze(r,i)?V(r,i):V(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function gf(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function yN(e,t){let r=Ee.resolve(e),i=Ee.resolve(t);if(!Zs(r,i))throw new Error("Native artifact path is outside its root");let n=[await gf(r)],a=r;for(let o of Ee.relative(r,i).split(Ee.sep).filter(Boolean)){a=Ee.join(a,o);let s=await gf(a);if(!Zs(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function wf(e){for(let t of e){let r=await Te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!wN(t,r)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function J(e){let t=vN(e.ref),r=e.maxBytes===null?null:gN(e.maxBytes??ia),i=Ee.resolve(e.root,...t.split("/")),n=await yN(e.root,Ee.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Te.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 Te.realpath(i);if(!Zs(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Te.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),Te.lstat(i),Te.realpath(i)]);if(await wf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!ra(a,c)||!ra(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let w=r===null?h.length:r+1-u,k=await s.read(h,0,Math.min(h.length,w),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Te.lstat(i),Te.realpath(i)]);if(await wf(n),!m.isFile()||m.isSymbolicLink()||p!==o||!ra(c,v)||!ra(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let y=Buffer.concat(d,u),g;try{g=new mN("utf-8",{fatal:!0}).decode(y)}catch(w){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:w})}return{ref:t,size:u,hash:e.includeHash===!1?null:pN("sha256").update(y).digest("hex"),text:g}}finally{await s.close()}}import{createHash as NN}from"crypto";function je(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function bN(e,t){t.has(e)&&je("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)||je("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&je("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&je("symbol properties are not supported"),`[${e.map(i=>ec(i,t)).join(",")}]`}finally{t.delete(e)}}function kN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&je("only plain objects are supported"),t.has(e)&&je("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&je("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))&&je("accessor properties are not supported"),`${JSON.stringify(o)}:${ec(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ec(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)||je("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?bN(e,t):kN(e,t);case"bigint":case"function":case"symbol":case"undefined":return je(`${typeof e} values are not supported`)}return je("unsupported value type")}function tc(e){return ec(e,new Set)}function pe(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 NN("sha256").update(`${e}
143
- ${tc(t)}`).digest("hex")}import ab from"path";var vi=Hr(hr(),1);import Ct from"path";var gi=64*1024,na=1024,aa=64,yf=1024,Nf=64,ic=5,mi={learning:!0,retrieval:!0},nc={provider:"local"},SN=12e4,bf=6e5,EN=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/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/**"],xN=["**/.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"],PN=[...EN,...xN].sort((e,t)=>e.localeCompare(t,"en"));var ye={include:["**/*"],exclude:[...PN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},vr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
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=ta(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=ta(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())}}};mf.Parser=Ys});var Nf=b(hi=>{"use strict";var vf=Ds(),nN=ai(),pi=ci(),aN=Oo(),oN=A(),sN=Ks(),gf=Xs();function wf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new sN.LineCounter||null,prettyErrors:t}}function cN(e,t={}){let{lineCounter:r,prettyErrors:i}=wf(t),n=new gf.Parser(r?.addNewLine),a=new vf.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 yf(e,t={}){let{lineCounter:r,prettyErrors:i}=wf(t),n=new gf.Parser(r?.addNewLine),a=new vf.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 lN(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=yf(e,r);if(!n)return null;if(n.warnings.forEach(a=>aN.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 uN(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 oN.isDocument(e)&&!i?e.toString(r):new nN.Document(e,i,r).toString(r)}hi.parse=lN;hi.parseAllDocuments=cN;hi.parseDocument=yf;hi.stringify=uN});var mr=b(T=>{"use strict";var dN=Ds(),fN=ai(),pN=gs(),Qs=ci(),hN=qr(),Pt=A(),mN=kt(),vN=z(),gN=Et(),wN=xt(),yN=Zn(),NN=Gs(),bN=Ks(),kN=Xs(),ia=Nf(),bf=Lr();T.Composer=dN.Composer;T.Document=fN.Document;T.Schema=pN.Schema;T.YAMLError=Qs.YAMLError;T.YAMLParseError=Qs.YAMLParseError;T.YAMLWarning=Qs.YAMLWarning;T.Alias=hN.Alias;T.isAlias=Pt.isAlias;T.isCollection=Pt.isCollection;T.isDocument=Pt.isDocument;T.isMap=Pt.isMap;T.isNode=Pt.isNode;T.isPair=Pt.isPair;T.isScalar=Pt.isScalar;T.isSeq=Pt.isSeq;T.Pair=mN.Pair;T.Scalar=vN.Scalar;T.YAMLMap=gN.YAMLMap;T.YAMLSeq=wN.YAMLSeq;T.CST=yN;T.Lexer=NN.Lexer;T.LineCounter=bN.LineCounter;T.Parser=kN.Parser;T.parse=ia.parse;T.parseAllDocuments=ia.parseAllDocuments;T.parseDocument=ia.parseDocument;T.stringify=ia.stringify;T.visit=bf.visit;T.visitAsync=bf.visitAsync});var el=Br(mr(),1);import{promises as ch}from"node:fs";import _e from"node:path";import{execFileSync as SN}from"child_process";import mi from"path";function Rt(e,t){return SN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function EN(e,t){let r=mi.normalize(e),i=mi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function q(e){try{let t=mi.resolve(Rt(e,["rev-parse","--show-toplevel"])),i=Rt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?mi.resolve(i.slice(9)):t,a=null;try{a=Rt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!EN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function na(e){try{Rt(e,["rev-parse","--is-inside-work-tree"]);let t=Rt(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:mi.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 Jt(e){return na(e).map(t=>t.root)}function vr(e,t){try{return Rt(e,["check-ref-format","--branch",t]),Rt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function gr(e,t){try{let r=Rt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as xN}from"node:child_process";var CN=3e4,PN=8*1024*1024,Zs=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};function RN(e,t){try{return xN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:CN,maxBuffer:PN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Zs(e,t,i)}}function _(e,t){return RN(e,t).trim()}function st(e){return _(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function ec(e,t){_(e,["check-ref-format","--branch",t])}import{createHash as TN}from"node:crypto";import{promises as je}from"node:fs";import xe from"node:path";import{TextDecoder as jN}from"node:util";var AN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),_N=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function IN(e){return e.toLowerCase().startsWith(".env")}function vi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>IN(i))?"environment-file":r.some(i=>_N.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>AN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function At(e){return e!==0&&e!==0n&&e!=="0"}function Je(e,t){return At(e.dev)&&At(t.dev)&&At(e.ino)&&At(t.ino)}function M(e,t){let r=At(e.dev)&&At(t.dev);if(r&&e.dev!==t.dev)return!1;let i=At(e.ino)&&At(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var oa=1024*1024;function tc(e,t){let r=xe.relative(e,t);return r===""||!xe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xe.sep}`)}function $N(e){let t=xe.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})||xe.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 ON(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function HN(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aa(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kf(e){let t=await je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function DN(e,t){let r=xe.resolve(e),i=xe.resolve(t);if(!tc(r,i))throw new Error("Native artifact path is outside its root");let n=[await kf(r)],a=r;for(let o of xe.relative(r,i).split(xe.sep).filter(Boolean)){a=xe.join(a,o);let s=await kf(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 Sf(e){for(let t of e){let r=await je.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!HN(t,r)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function U(e){let t=$N(e.ref),r=e.maxBytes===null?null:ON(e.maxBytes??oa),i=xe.resolve(e.root,...t.split("/")),n=await DN(e.root,xe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await je.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 je.realpath(i);if(!tc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await je.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),je.lstat(i),je.realpath(i)]);if(await Sf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!aa(a,c)||!aa(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?p.length:r+1-u,k=await s.read(p,0,Math.min(p.length,y),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([s.stat(),je.lstat(i),je.realpath(i)]);if(await Sf(n),!m.isFile()||m.isSymbolicLink()||h!==o||!aa(c,v)||!aa(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(d,u),g;try{g=new jN("utf-8",{fatal:!0}).decode(w)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:u,hash:e.includeHash===!1?null:TN("sha256").update(w).digest("hex"),text:g}}finally{await s.close()}}import{createHash as BN}from"crypto";function $e(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function LN(e,t){t.has(e)&&$e("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)||$e("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&$e("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&$e("symbol properties are not supported"),`[${e.map(i=>rc(i,t)).join(",")}]`}finally{t.delete(e)}}function VN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&$e("only plain objects are supported"),t.has(e)&&$e("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&$e("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))&&$e("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)||$e("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?LN(e,t):VN(e,t);case"bigint":case"function":case"symbol":case"undefined":return $e(`${typeof e} values are not supported`)}return $e("unsupported value type")}function ic(e){return rc(e,new Set)}function me(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 BN("sha256").update(`${e}
143
+ ${ic(t)}`).digest("hex")}import Sb from"path";var wi=Br(mr(),1);import _t from"path";var yi=64*1024,sa=1024,ca=64,Ef=1024,xf=64,ac=5,gi={learning:!0,retrieval:!0},oc={provider:"local"},MN=12e4,Cf=6e5,FN=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/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/**"],qN=["**/.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=[...FN,...qN].sort((e,t)=>e.localeCompare(t,"en"));var be={include:["**/*"],exclude:[...WN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},wr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
144
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
145
145
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
146
146
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -164,28 +164,28 @@ ${tc(t)}`).digest("hex")}import ab from"path";var vi=Hr(hr(),1);import Ct from"p
164
164
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
165
165
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
166
166
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
167
- # 可选值:true | false`}};function Sf(e,t){return vr[t][e]}function CN(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in vr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in vr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in vr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in vr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in vr.en)return s}return null}function wi(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,vi.stringify)(e).trimEnd().split(`
168
- `)){let s=CN(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Sf(s,t).split(`
167
+ # 可选值:true | false`}};function Rf(e,t){return wr[t][e]}function zN(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in wr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in wr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in wr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in wr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in wr.en)return s}return null}function Ni(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,wi.stringify)(e).trimEnd().split(`
168
+ `)){let s=zN(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Rf(s,t).split(`
169
169
  `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
170
- `)}function RN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ct.posix.isAbsolute(r)||Ct.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 zt(e){let t=RN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ef(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 oa(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||Ct.posix.isAbsolute(i)||Ct.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 ot(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=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function ac(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>na)throw new Error(`${t} exceeds ${na} 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>aa)throw new Error(`${t} contains more than ${aa} wildcard tokens`);return e}function kf(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=>ac(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function rc(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 AN(e){if(e===void 0)return{...ye,include:[...ye.include],exclude:[...ye.exclude]};let t=ot(e,"native.snapshot");return{include:kf(t.include,"native.snapshot.include",ye.include),exclude:kf(t.exclude,"native.snapshot.exclude",ye.exclude),max_files:rc(t.max_files,ye.max_files,"native.snapshot.max_files"),max_total_bytes:rc(t.max_total_bytes,ye.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:rc(t.max_duration_ms,ye.max_duration_ms,"native.snapshot.max_duration_ms")}}function _N(e){if(e===void 0)return;let t=ot(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=ot(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:zt(i),toArtifactRoot:zt(n),stage:a,...o?{cleanup:o}:{}}}function IN(e){if(e===void 0)return;let t=ot(e,"native.finish");if(t.pull_request===void 0)return{};let r=ot(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(Ct.posix.isAbsolute(i[0])||Ct.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??SN;if(!Number.isSafeInteger(n)||n<1||n>bf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${bf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function TN(e,t={}){let r=ot(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??ic;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=_N(r.pending_root_move),c=IN(r.finish);return{artifact_root:zt(i),language:xf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:AN(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function jN(e){let t=ot(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");return{artifact_layout:Ef(t.artifact_layout),language:xf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function $N(e){let r=ot(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)=>oa(i,`hook.allow_paths[${n}]`)))]}}function ON(e){if(e===void 0)return{...mi};let t=ot(e,"memory"),r=t.learning??mi.learning,i=t.retrieval??mi.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 oc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function HN(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")||Ct.posix.isAbsolute(r)||Ct.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>yf)throw new Error(`${t} exceeds ${yf} 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>Nf)throw new Error(`${t} contains more than ${Nf} wildcard tokens`);return r}function DN(e){let r=oc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>HN(i,`knowledge.local.include[${n}]`)))]}}function BN(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 LN(e){let t=oc(e,"knowledge.remote"),r=BN(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 VN(e){if(e===void 0)return{...nc};let t=oc(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:DN(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:LN(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 MN(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function FN(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 f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(f)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function gr(e,t={}){let r=(0,vi.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=MN(n.ambient_resume),o=n.hook===void 0?void 0:$N(n.hook),s=ON(n.memory),c=VN(n.knowledge),l=n.native===void 0?void 0:TN(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:jN(n.classic),d=FN(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Pf(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Cf(e){let t=e.knowledge??{...nc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...mi},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Pf(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function we(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function yi(e,t){let r=Cf(t),i=gr((0,vi.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...we(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=we(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=we(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...we(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...we(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=we(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=we(a.finish);o.finish={...s,pull_request:{...we(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...we(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=we(a.pending_root_move),c=Pf(i.native.pending_root_move),l=we(s.cleanup),f=we(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...we(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function sa(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...mi},knowledge:{...nc},native:{artifact_root:zt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ic,snapshot:{...ye,include:[...ye.include],exclude:[...ye.exclude]}}}}import{createHash as WN}from"crypto";import{promises as ua}from"fs";import Rt from"path";import{constants as ca,promises as Jt}from"fs";var $e=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function sc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Rf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ni(e){return{dev:e.dev,ino:e.ino,birthtime:sc(e)}}function la(e,t){let r=Ni(e),i=Ni(t);return ze(r,i)?V(r,i):V(r,i)&&sc(e)===sc(t)&&Rf(e)===Rf(t)&&e.size===t.size}async function wr(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 Jt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new $e("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new $e("too-large",`${i} exceeds ${t} bytes`);let o=await Jt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ni(a)});let s=process.platform==="win32"?ca.O_RDONLY:ca.O_RDONLY|ca.O_NOFOLLOW|ca.O_NONBLOCK,c;try{c=await Jt.open(e,s)}catch(l){throw l.code==="ELOOP"?new $e("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Jt.lstat(e,{bigint:n}),Jt.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!la(a,l)||!la(a,f))throw new $e("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Ni(l)}),await r.hooks?.afterOpen?.();let u=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:w}=await c.read(v,0,Math.min(v.length,g),null);if(w===0)break;if(h+=w,h>t)throw new $e("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(v.subarray(0,w)))}await r.hooks?.beforeFinalCheck?.();let[m,p,y]=await Promise.all([c.stat({bigint:n}),Jt.lstat(e,{bigint:n}),Jt.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!la(a,m)||!la(a,p))throw new $e("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:Ni(m)}),{bytes:Buffer.concat(u,h),stat:m,realPath:y}}finally{await c.close()}}function qN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function cc(e,t){let r=Rt.relative(e,t);return r===""||!Rt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Rt.sep}`)}async function Af(e,t){let r=Rt.resolve(e),i=await ua.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ua.realpath(r)}async function _f(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Rt.join(n,r[a]);let o;try{o=await ua.lstat(n)}catch(f){if(qN(f))return{exists:!1,kind:"missing"};throw f}let s=Rt.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 ua.realpath(n);if(!cc(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 yr(e,t,r){let i=oa(t,r.label),n=Rt.resolve(e),a=await Af(n,r.label),o=i.split("/"),s=Rt.resolve(n,...o);if(!cc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await _f(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function At(e,t,r,i){let n=await yr(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 Af(n.projectRoot,i.label);return wr(n.target,r,{...i,verify:async(o,s)=>{if(!cc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await _f(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var bi=".comet/config.yaml";function lc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function zN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function da(e,t={}){return(await ki(e,t)).document}async function If(e){try{return(await At(e,bi,gi,{label:bi})).bytes}catch(t){if(zN(t))return null;throw t}}function Tf(e){return e?{exists:!0,sha256:WN("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fa(e){return Tf(await If(e))}async function ki(e,t={}){let r=await If(e);return{document:r?gr(r.toString("utf8"),t):null,identity:Tf(r)}}async function uc(e){return(await da(e))?.config??null}var iR=16*1024;async function dc(e,t){if(!t)return;let r=await fa(e);if(!lc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as KN}from"crypto";import{promises as ie}from"fs";import Oe from"path";function fc(e,t){let r=Oe.relative(e,t);return r===""||!Oe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Oe.sep}`)}function YN(e,t){return V({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hc(e,t){return V({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function XN(e,t){return hc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function jf(e){let t=await ie.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 ie.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ei(e){for(let t of e){let r=await ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!YN(t,r)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function QN(e,t){let r=Oe.resolve(e),i=Oe.resolve(t);if(!fc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await jf(r)],a=Oe.relative(r,i).split(Oe.sep).filter(Boolean),o=r;for(let s of a){await Ei(n),o=Oe.join(o,s);try{await ie.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await jf(o);if(!fc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ei(n),n}async function ZN(e){let t;try{t=await ie.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 eb(e,t,r={}){let i=Oe.dirname(e),n=r.containedRoot?await QN(r.containedRoot,i):null;n||await ie.mkdir(i,{recursive:!0});let a=Oe.join(i,`.${Oe.basename(e)}.${KN()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ie.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Ei(n),!l.isFile()||l.isSymbolicLink()||!hc(s,l)||!fc(n[0].realPath,f))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(),!hc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),n){await Ei(n);let l=await ie.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!XN(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await ie.link(a,e),await ie.unlink(a)):await ie.rename(a,e),await ZN(i)}catch(l){if(await o?.close(),!n)await ie.rm(a,{force:!0});else try{await Ei(n),await ie.rm(a,{force:!0})}catch{}throw l}}async function xe(e,t,r={}){await eb(e,t,r)}async function me(e,t,r={}){await xe(e,JSON.stringify(t,null,2)+`
171
- `,r)}import{existsSync as $f,promises as Gt}from"fs";import T from"path";import tb from"os";var xi=".comet/config.yaml",rb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function pc(e){try{return await Gt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ib(e){try{let t=await Gt.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=T.relative(e,t);return r===""||!T.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${T.sep}`)}async function Nr(e){let t=[],r=e;for(;!await pc(r);){let n=T.dirname(r);if(n===r)break;t.push(T.basename(r)),r=n}let i=await Gt.realpath(r);return T.resolve(i,...t.reverse())}async function mc(e){try{return(await Gt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ha(e){let t=T.resolve(e);try{(await Gt.stat(t)).isDirectory()||(t=T.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=T.resolve(tb.homedir());for(;;){if(!(t===i&&r!==i)){let o=T.join(t,...xi.split("/")),s=t===r||await ib(o);if(await pc(o)&&s)return t}if(await pc(T.join(t,".git")))return t;let a=T.dirname(t);if(a===t)return r;t=a}}function pa(e){return zt(e)}async function nb(e,t){let r=pa(t),i=T.resolve(e,...r.split("/")),n=await Gt.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 _t(e,t){let r=pa(t),i=await nb(e,r),n=T.join(i,"comet");if(await mc(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=T.resolve(e),c=T.join(s,".comet","runtime","native");if(await mc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Gt.realpath(s),Nr(c)]);if(!br(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:T.join(e,...xi.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:T.join(n,"specs"),changesDir:T.join(n,"changes"),archiveDir:T.join(n,"archive"),runtimeDir:c,changesRuntimeDir:T.join(c,"changes"),locksDir:T.join(c,"locks"),transactionsDir:T.join(c,"transactions")}}function Of(e){if(!rb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function He(e,t){Of(t);let r=T.join(e.changesRuntimeDir,t);if(!se(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function vc(e,t){Of(t);let r=T.join(e.changesDir,t,"runtime");if(!se(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Je(e,t){let r=He(e,t);if($f(r))return r;let i=vc(e,t);return $f(i)?i:r}function Ge(e,t){let r=T.resolve(t);if(se(e.runtimeDir,r))return e.runtimeDir;if(se(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function se(e,t){return br(T.resolve(e),T.resolve(t))}async function q(e,t){let r=T.resolve(e),i=T.resolve(t);if(!br(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await mc(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}function ob(e="docs",t="en"){return sa(e,t)}async function ve(e){let t=(await da(e))?.config??null;return t?.native?t:null}async function ma(e){let t=await ve(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function va(e,t,r={}){let i=await ki(e,{allowPartialProject:!0}),n=yi(i.document?.value??{},t),a=ab.join(e,...xi.split("/"));await xe(a,wi(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await dc(e,i.identity)}})}async function Hf(e){let t=await ha(e.startPath),r=await ve(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${xi} 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?pa(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??ob(i??"docs"),a=await _t(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Na=Hr(hr(),1);import{promises as sb}from"node:fs";var kr="comet.native.v4",Pi="comet.native.local-execution.v4";var ga=["multi-session","single-session"];function gc(){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 cb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ub=/^A[1-9][0-9]*$/u,db=/^[a-f0-9]{64}$/u,fb=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ya=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"};function ce(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function le(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 X(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 yc(e,t){return e===null?null:X(e,t)}function hb(e,t){let r=X(e,t);if(!db.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Sr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function M(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 pb(e,t){return e===null?null:M(e,t,Number.MIN_SAFE_INTEGER)}function G(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ue(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function ba(e,t){return Ue(e,t,(r,i)=>X(r,`${t}[${i}]`))}function Ut(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Er(e,t){let r=X(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Nc(e,t,r=!1){let i=X(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 Pe(e,t){let r=ce(e,t);return le(r,new Set(["text","truncated"]),t),{text:X(r.text,`${t}.text`,{empty:!0}),truncated:Sr(r.truncated,`${t}.truncated`)}}function mb(e,t){let r=`Native spec_changes[${t}]`,i=ce(e,r);le(i,new Set(["capability","operation","source"]),r);let n=X(i.capability,`${r}.capability`);if(!lb.test(n))throw new Error(`${r}.capability is invalid`);let a=G(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Nc(i.source,`${r}.source`);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`);return{capability:n,operation:a,source:o}}function vb(e){let t="Native workspace",r=ce(e,t);le(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=G(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=yc(r.change_branch,`${t}.change_branch`),a=yc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:G(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 gb(e){let t="Native loop",r=ce(e,t);le(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=ba(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Ut(i,`${t}.previous_unresolved_ids`),{stage:G(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:M(r.goal_cycle,`${t}.goal_cycle`,1),iteration:M(r.iteration,`${t}.iteration`),attempt:M(r.attempt,`${t}.attempt`),retry_epoch:M(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:M(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:M(r.no_progress_count,`${t}.no_progress_count`),execution_failure_count:M(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:yc(r.next_action,`${t}.next_action`)}}function wb(e,t){let r=`Native acceptance[${t}]`,i=ce(e,r);le(i,new Set(["id","source","text","result","reason"]),r);let n=X(i.id,`${r}.id`);if(!ub.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Nc(i.source,`${r}.source`),text:X(i.text,`${r}.text`),result:G(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Pe(i.reason,`${r}.reason`)}}function yb(e,t){let r=`Native builder_handoff.checks[${t}]`,i=ce(e,r);return le(i,new Set(["name","result","note"]),r),{name:Pe(i.name,`${r}.name`),result:G(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Pe(i.note,`${r}.note`)}}function Nb(e){let t="Native builder_handoff",r=ce(e,t);le(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=ba(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ut(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ce(r.review,`${t}.review`);return n&&le(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:X(r.candidate_id,`${t}.candidate_id`),identity_provider:X(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:X(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:M(r.iteration,`${t}.iteration`,1),summary:Pe(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ue(r.checks,`${t}.checks`,yb),checks_truncated:Sr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ue(r.known_limits,`${t}.known_limits`,(a,o)=>Pe(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Sr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:G(n.status,["passed"],`${t}.review.status`),summary:Pe(n.summary,`${t}.review.summary`),reviewer_execution_ref:X(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Er(r.submitted_at,`${t}.submitted_at`)}}function bb(e,t){let r=`Native blockers[${t}]`,i=ce(e,r);le(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ba(i.acceptance_ids,`${r}.acceptance_ids`);return Ut(n,`${r}.acceptance_ids`),{owner:G(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Pe(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:G(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function kb(e,t){let r=`Native verification.checks[${t}]`,i=ce(e,r);return le(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:X(i.id,`${r}.id`),name:Pe(i.name,`${r}.name`),argv_display:Ue(i.argv_display,`${r}.argv_display`,(n,a)=>Pe(n,`${r}.argv_display[${a}]`)),argv_truncated:Sr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Nc(i.cwd_ref,`${r}.cwd_ref`,!0),status:G(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:pb(i.exit_code,`${r}.exit_code`),duration_ms:M(i.duration_ms,`${r}.duration_ms`)}}function Sb(e){let t="Native verification",r=ce(e,t);le(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ue(r.checks,`${t}.checks`,kb);Ut(i.map(a=>a.id),`${t}.checks IDs`);let n=X(r.identity_provider,`${t}.identity_provider`);return{candidate_id:X(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:X(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:M(r.iteration,`${t}.iteration`,1),attempt:M(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":G(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:G(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Pe(r.summary,`${t}.summary`),risks:Ue(r.risks,`${t}.risks`,(a,o)=>Pe(a,`${t}.risks[${o}]`)),risks_truncated:Sr(r.risks_truncated,`${t}.risks_truncated`),completed_at:Er(r.completed_at,`${t}.completed_at`)}}function Df(e,t){let r=`Native history[${t}]`,i=ce(e,r);le(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ba(i.unresolved_ids,`${r}.unresolved_ids`);return Ut(n,`${r}.unresolved_ids`),{goal_cycle:M(i.goal_cycle,`${r}.goal_cycle`,1),iteration:M(i.iteration,`${r}.iteration`),attempt:M(i.attempt,`${r}.attempt`),outcome:G(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Pe(i.summary,`${r}.summary`),completed_at:Er(i.completed_at,`${r}.completed_at`)}}function Eb(e){let t="Native history_overflow.outcome_counts",r=ce(e,t),i=["pass","fail","blocked","execution-error","recovery"];return le(r,new Set(i),t),{pass:M(r.pass,`${t}.pass`),fail:M(r.fail,`${t}.fail`),blocked:M(r.blocked,`${t}.blocked`),"execution-error":M(r["execution-error"],`${t}.execution-error`),recovery:M(r.recovery,`${t}.recovery`)}}function xb(e){let t="Native history_overflow",r=ce(e,t);le(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=M(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Er(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Er(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=Eb(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 Pb(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 Cb(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 C(e){let t=ce(e,"Native portable state");if(le(t,fb,"Native portable state"),t.schema!==kr)throw new Error(`Native portable state schema must be ${kr}`);let r=X(t.name,"Native state name");if(!cb.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=Ue(t.spec_changes,"Native spec_changes",mb);Ut(i.map(s=>s.capability),"Native spec change capabilities");let n=Ue(t.acceptance,"Native acceptance",wb);Ut(n.map(s=>s.id),"Native acceptance IDs");let a=Ue(t.history,"Native history",Df);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:kr,name:r,language:G(t.language,["en","zh-CN"],"Native state language"),phase:G(t.phase,["shape","build","verify","archive"],"Native state phase"),status:G(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:M(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:hb(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:G(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:vb(t.workspace),loop:gb(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Nb(t.builder_handoff),blockers:Ue(t.blockers,"Native blockers",bb),verification:t.verification===null?null:Sb(t.verification),history:a,history_overflow:xb(t.history_overflow),verification_result:G(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:G(t.verification_report,["verification.md"],"Native verification_report"),archived:Sr(t.archived,"Native archived"),created_at:Er(t.created_at,"Native created_at")};return Pb(o),Cb(o),o}function Ne(e,t){let r=C(e),i=Df(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 C({...r,history:n,history_overflow:a})}function Rb(e,t){let r=(0,Na.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 De(e){let t=await sb.readFile(e,"utf8");return C(Rb(t,"Native portable state"))}async function ka(e,t,r={}){let i=C(t);await xe(e,(0,Na.stringify)(i),r)}var wa=new Map;async function Ab(e,t){let r=wa.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);wa.set(e,a),await r;try{return await t()}finally{i(),wa.get(e)===a&&wa.delete(e)}}async function Ci(e){return Ab(e.file,async()=>{let t=M(e.expectedStateVersion,"Native expected state version",1),r=C(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await De(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ya(t,i.state_version);return await ka(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await De(e.file);if(n.state_version!==t)throw new ya(t,n.state_version)}}),r})}import Xt from"node:path";import{randomUUID as kS}from"node:crypto";import{promises as Bh}from"node:fs";import{promises as mS}from"fs";import vS from"path";import{AsyncLocalStorage as _b}from"async_hooks";import{randomUUID as Vf}from"crypto";import{promises as Ce}from"fs";import Mf from"os";import Q from"path";var Bf=16*1024,Ff=".coordinator",Ib=5e3,Lf=new _b,Sa=new Map;function Tb(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function jb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function qf(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function bc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ze(r,i)?V(r,i):V(r,i)&&e.size===t.size}function kc(e,t){return bc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function st(e){let t,r;try{let i=await wr(e,Bf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof $e?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Bf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:jb(JSON.parse(t.toString("utf8")),e),identity:qf(r)}}async function $b(e){return(await st(e))?.owner??null}function Wf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Mf.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Vb(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Ob(e,t){try{await Ce.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Ce.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Sc(e,t){let r=await st(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!kc(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ce.mkdir(t,{recursive:!0});let i=Q.join(t,`${Q.basename(e.file)}.${e.owner.id}.${Vf()}.removed`);try{await Ce.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await st(i);if(!n||n.owner.id!==e.owner.id||!bc(n.identity,e.identity))throw await Ob(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ce.rm(i,{force:!0}),"removed"}function zf(e){return{id:Vf(),pid:process.pid,hostname:Mf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Jf(e,t){let r;try{r=await Ce.open(e,"wx")}catch(i){if(i.code==="EEXIST"){let n=await $b(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:i})}throw i}try{return await r.writeFile(JSON.stringify(t,null,2)+`
172
- `,"utf8"),await r.sync(),qf(await r.stat({bigint:!0}))}finally{await r.close()}}async function Hb(e,t){let r=await q(e.runtimeDir,e.locksDir);await Ce.mkdir(r,{recursive:!0});let i=await q(e.runtimeDir,Q.join(r,Ff));await Ce.mkdir(i,{recursive:!0});let n=zf(t),a=Q.join(i,`.${n.id}.tmp`),o=Q.join(i,`${n.id}.claim`);try{let s=await Jf(a,n);await Ce.rename(a,o);let c=await st(o);if(!c||!bc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Ce.rm(a,{force:!0})}}async function Db(e){let t=Q.dirname(e.file),r=!1,i=Q.basename(e.file);for(let n of await Ce.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Q.join(t,n.name);if(Q.resolve(a)!==Q.resolve(e.file))try{let o=await st(a),s=Wf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Sc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Gf(e){let t=await st(e.file);if(t){if(t.owner.id!==e.owner.id||!kc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Sc(t,Q.dirname(e.file))}}async function Bb(e,t){let r=Date.now()+Ib;for(;;){let i=await Hb(e,t);if(!await Db(i))return i;if(await Gf(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Lb(e){let t=Sa.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Sa.set(e,n),await t,()=>{r(),Sa.get(e)===n&&Sa.delete(e)}}async function Ec(e,t,r){let i=Q.resolve(e.locksDir),n=Lf.getStore();if(n?.has(i))return r();let a=await Lb(i);try{let o=await Bb(e,t),s=new Map(n??[]);return s.set(i,o),await Lf.run(s,async()=>{try{return await r()}finally{await Gf(o)}})}finally{a()}}async function Uf(e,t,r){let i=[...new Map(e.map(a=>[Q.resolve(a.locksDir),a])).values()].sort((a,o)=>Q.resolve(a.locksDir).localeCompare(Q.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Ec(o,t,()=>n(a+1)):r()};return n(0)}async function Ea(e,t,r){return Ec(e,`acquire ${t}`,async()=>{let i=await q(e.runtimeDir,e.locksDir);await Ce.mkdir(i,{recursive:!0});let n=await q(e.runtimeDir,Q.join(i,Tb(t))),a=zf(r),o=await Jf(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function xa(e){await st(e.file)&&await Ec({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Q.basename(e.file)}`,async()=>{let t=await st(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!kc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Q.join(e.locksDir,Ff);await Sc(t,r)})}function Vb(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Kf(e){return Wf(await st(e))}import Vc from"node:path";import $k from"node:path";var $c=Hr(hr(),1);import Cr from"path";var xc={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:"验证预期"}},Xf={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:"结论"}},Qf={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:"结论"}},Zf=new Map,Yf=new Map;for(let e of Object.keys(xc)){for(let[t,r]of Object.entries(xc[e]))Zf.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Xf[e]))Yf.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Qf[e]))Yf.set(r.toLocaleLowerCase("en-US"),t)}function Mb(e,t){return xc[e][t]}function Pc(e,t){return Xf[e][t]??Qf[e][t]}function Cc(e){return Zf.get(e.trim().toLocaleLowerCase("en-US"))??null}function Pa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Mb(e,r)}
170
+ `)}function JN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||_t.posix.isAbsolute(r)||_t.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 Gt(e){let t=JN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Af(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 la(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||_t.posix.isAbsolute(i)||_t.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 ct(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _f(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 sc(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>sa)throw new Error(`${t} exceeds ${sa} 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>ca)throw new Error(`${t} contains more than ${ca} wildcard tokens`);return e}function Pf(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=>sc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function nc(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 GN(e){if(e===void 0)return{...be,include:[...be.include],exclude:[...be.exclude]};let t=ct(e,"native.snapshot");return{include:Pf(t.include,"native.snapshot.include",be.include),exclude:Pf(t.exclude,"native.snapshot.exclude",be.exclude),max_files:nc(t.max_files,be.max_files,"native.snapshot.max_files"),max_total_bytes:nc(t.max_total_bytes,be.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:nc(t.max_duration_ms,be.max_duration_ms,"native.snapshot.max_duration_ms")}}function UN(e){if(e===void 0)return;let t=ct(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=ct(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:Gt(i),toArtifactRoot:Gt(n),stage:a,...o?{cleanup:o}:{}}}function KN(e){if(e===void 0)return;let t=ct(e,"native.finish");if(t.pull_request===void 0)return{};let r=ct(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(_t.posix.isAbsolute(i[0])||_t.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>Cf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Cf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function YN(e,t={}){let r=ct(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??ac;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=UN(r.pending_root_move),c=KN(r.finish);return{artifact_root:Gt(i),language:_f(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:GN(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function XN(e){let t=ct(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");return{artifact_layout:Af(t.artifact_layout),language:_f(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function QN(e){let r=ct(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)=>la(i,`hook.allow_paths[${n}]`)))]}}function ZN(e){if(e===void 0)return{...gi};let t=ct(e,"memory"),r=t.learning??gi.learning,i=t.retrieval??gi.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 cc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function eb(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")||_t.posix.isAbsolute(r)||_t.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>Ef)throw new Error(`${t} exceeds ${Ef} 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>xf)throw new Error(`${t} contains more than ${xf} wildcard tokens`);return r}function tb(e){let r=cc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>eb(i,`knowledge.local.include[${n}]`)))]}}function rb(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 ib(e){let t=cc(e,"knowledge.remote"),r=rb(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 nb(e){if(e===void 0)return{...oc};let t=cc(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:tb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:ib(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 ab(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function ob(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 f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(f)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function yr(e,t={}){let r=(0,wi.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=ab(n.ambient_resume),o=n.hook===void 0?void 0:QN(n.hook),s=ZN(n.memory),c=nb(n.knowledge),l=n.native===void 0?void 0:YN(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:XN(n.classic),d=ob(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function If(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Tf(e){let t=e.knowledge??{...oc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...gi},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:If(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function Ne(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function bi(e,t){let r=Tf(t),i=yr((0,wi.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...Ne(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Ne(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Ne(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...Ne(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...Ne(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=Ne(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=Ne(a.finish);o.finish={...s,pull_request:{...Ne(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...Ne(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=Ne(a.pending_root_move),c=If(i.native.pending_root_move),l=Ne(s.cleanup),f=Ne(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...Ne(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function ua(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...gi},knowledge:{...oc},native:{artifact_root:Gt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ac,snapshot:{...be,include:[...be.include],exclude:[...be.exclude]}}}}import{createHash as cb}from"crypto";import{promises as pa}from"fs";import It from"path";import{constants as da,promises as Ut}from"fs";var Oe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function lc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function jf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ki(e){return{dev:e.dev,ino:e.ino,birthtime:lc(e)}}function fa(e,t){let r=ki(e),i=ki(t);return Je(r,i)?M(r,i):M(r,i)&&lc(e)===lc(t)&&jf(e)===jf(t)&&e.size===t.size}async function Nr(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 Ut.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Oe("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Oe("too-large",`${i} exceeds ${t} bytes`);let o=await Ut.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ki(a)});let s=process.platform==="win32"?da.O_RDONLY:da.O_RDONLY|da.O_NOFOLLOW|da.O_NONBLOCK,c;try{c=await Ut.open(e,s)}catch(l){throw l.code==="ELOOP"?new Oe("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Ut.lstat(e,{bigint:n}),Ut.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!fa(a,l)||!fa(a,f))throw new Oe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ki(l)}),await r.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-p,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(p+=y,p>t)throw new Oe("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[m,h,w]=await Promise.all([c.stat({bigint:n}),Ut.lstat(e,{bigint:n}),Ut.realpath(e)]);if(!h.isFile()||h.isSymbolicLink()||w!==o||!fa(a,m)||!fa(a,h))throw new Oe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ki(m)}),{bytes:Buffer.concat(u,p),stat:m,realPath:w}}finally{await c.close()}}function sb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function uc(e,t){let r=It.relative(e,t);return r===""||!It.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${It.sep}`)}async function $f(e,t){let r=It.resolve(e),i=await pa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return pa.realpath(r)}async function Of(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=It.join(n,r[a]);let o;try{o=await pa.lstat(n)}catch(f){if(sb(f))return{exists:!1,kind:"missing"};throw f}let s=It.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 pa.realpath(n);if(!uc(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 br(e,t,r){let i=la(t,r.label),n=It.resolve(e),a=await $f(n,r.label),o=i.split("/"),s=It.resolve(n,...o);if(!uc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Of(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Tt(e,t,r,i){let n=await br(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 $f(n.projectRoot,i.label);return Nr(n.target,r,{...i,verify:async(o,s)=>{if(!uc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Of(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Si=".comet/config.yaml";function dc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function lb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ha(e,t={}){return(await Ei(e,t)).document}async function Hf(e){try{return(await Tt(e,Si,yi,{label:Si})).bytes}catch(t){if(lb(t))return null;throw t}}function Df(e){return e?{exists:!0,sha256:cb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ma(e){return Df(await Hf(e))}async function Ei(e,t={}){let r=await Hf(e);return{document:r?yr(r.toString("utf8"),t):null,identity:Df(r)}}async function fc(e){return(await ha(e))?.config??null}var jR=16*1024;async function pc(e,t){if(!t)return;let r=await ma(e);if(!dc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as pb}from"crypto";import{promises as ne}from"fs";import He from"path";function hc(e,t){let r=He.relative(e,t);return r===""||!He.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${He.sep}`)}function hb(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mc(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function mb(e,t){return mc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Bf(e){let t=await ne.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 ne.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ci(e){for(let t of e){let r=await ne.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hb(t,r)||await ne.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function vb(e,t){let r=He.resolve(e),i=He.resolve(t);if(!hc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Bf(r)],a=He.relative(r,i).split(He.sep).filter(Boolean),o=r;for(let s of a){await Ci(n),o=He.join(o,s);try{await ne.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Bf(o);if(!hc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ci(n),n}async function gb(e){let t;try{t=await ne.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 wb(e,t,r={}){let i=He.dirname(e),n=r.containedRoot?await vb(r.containedRoot,i):null;n||await ne.mkdir(i,{recursive:!0});let a=He.join(i,`.${He.basename(e)}.${pb()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ne.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([ne.lstat(a),ne.realpath(a)]);if(await Ci(n),!l.isFile()||l.isSymbolicLink()||!mc(s,l)||!hc(n[0].realPath,f))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(),!mc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),n){await Ci(n);let l=await ne.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!mb(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await ne.link(a,e),await ne.unlink(a)):await ne.rename(a,e),await gb(i)}catch(l){if(await o?.close(),!n)await ne.rm(a,{force:!0});else try{await Ci(n),await ne.rm(a,{force:!0})}catch{}throw l}}async function Ce(e,t,r={}){await wb(e,t,r)}async function ve(e,t,r={}){await Ce(e,JSON.stringify(t,null,2)+`
171
+ `,r)}import{existsSync as Lf,promises as Kt}from"fs";import j from"path";import yb from"os";var Pi=".comet/config.yaml",Nb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function vc(e){try{return await Kt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bb(e){try{let t=await Kt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Sr(e,t){let r=j.relative(e,t);return r===""||!j.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${j.sep}`)}async function kr(e){let t=[],r=e;for(;!await vc(r);){let n=j.dirname(r);if(n===r)break;t.push(j.basename(r)),r=n}let i=await Kt.realpath(r);return j.resolve(i,...t.reverse())}async function gc(e){try{return(await Kt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function va(e){let t=j.resolve(e);try{(await Kt.stat(t)).isDirectory()||(t=j.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=j.resolve(yb.homedir());for(;;){if(!(t===i&&r!==i)){let o=j.join(t,...Pi.split("/")),s=t===r||await bb(o);if(await vc(o)&&s)return t}if(await vc(j.join(t,".git")))return t;let a=j.dirname(t);if(a===t)return r;t=a}}function ga(e){return Gt(e)}async function kb(e,t){let r=ga(t),i=j.resolve(e,...r.split("/")),n=await Kt.realpath(e),a=await kr(i);if(!Sr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function jt(e,t){let r=ga(t),i=await kb(e,r),n=j.join(i,"comet");if(await gc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([kr(i),kr(n)]);if(!Sr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=j.resolve(e),c=j.join(s,".comet","runtime","native");if(await gc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Kt.realpath(s),kr(c)]);if(!Sr(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:j.join(e,...Pi.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:j.join(n,"specs"),changesDir:j.join(n,"changes"),archiveDir:j.join(n,"archive"),runtimeDir:c,changesRuntimeDir:j.join(c,"changes"),locksDir:j.join(c,"locks"),transactionsDir:j.join(c,"transactions")}}function Vf(e){if(!Nb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function De(e,t){Vf(t);let r=j.join(e.changesRuntimeDir,t);if(!ce(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function wc(e,t){Vf(t);let r=j.join(e.changesDir,t,"runtime");if(!ce(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ge(e,t){let r=De(e,t);if(Lf(r))return r;let i=wc(e,t);return Lf(i)?i:r}function Ue(e,t){let r=j.resolve(t);if(ce(e.runtimeDir,r))return e.runtimeDir;if(ce(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ce(e,t){return Sr(j.resolve(e),j.resolve(t))}async function W(e,t){let r=j.resolve(e),i=j.resolve(t);if(!Sr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await gc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([kr(r),kr(i)]);if(!Sr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function Eb(e="docs",t="en"){return ua(e,t)}async function ge(e){let t=(await ha(e))?.config??null;return t?.native?t:null}async function wa(e){let t=await ge(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function ya(e,t,r={}){let i=await Ei(e,{allowPartialProject:!0}),n=bi(i.document?.value??{},t),a=Sb.join(e,...Pi.split("/"));await Ce(a,Ni(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await pc(e,i.identity)}})}async function Mf(e){let t=await va(e.startPath),r=await ge(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Pi} 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?ga(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??Eb(i??"docs"),a=await jt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Sa=Br(mr(),1);import{promises as xb}from"node:fs";var Er="comet.native.v4",Ri="comet.native.local-execution.v4";var Na=["multi-session","single-session"];function yc(){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 Cb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Pb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Rb=/^A[1-9][0-9]*$/u,Ab=/^[a-f0-9]{64}$/u,_b=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ka=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"};function le(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ue(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 Q(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 bc(e,t){return e===null?null:Q(e,t)}function Ib(e,t){let r=Q(e,t);if(!Ab.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function xr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function F(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 Tb(e,t){return e===null?null:F(e,t,Number.MIN_SAFE_INTEGER)}function J(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ke(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ea(e,t){return Ke(e,t,(r,i)=>Q(r,`${t}[${i}]`))}function Yt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Cr(e,t){let r=Q(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function kc(e,t,r=!1){let i=Q(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 Pe(e,t){let r=le(e,t);return ue(r,new Set(["text","truncated"]),t),{text:Q(r.text,`${t}.text`,{empty:!0}),truncated:xr(r.truncated,`${t}.truncated`)}}function jb(e,t){let r=`Native spec_changes[${t}]`,i=le(e,r);ue(i,new Set(["capability","operation","source"]),r);let n=Q(i.capability,`${r}.capability`);if(!Pb.test(n))throw new Error(`${r}.capability is invalid`);let a=J(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:kc(i.source,`${r}.source`);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`);return{capability:n,operation:a,source:o}}function $b(e){let t="Native workspace",r=le(e,t);ue(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=J(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=bc(r.change_branch,`${t}.change_branch`),a=bc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:J(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 Ob(e){let t="Native loop",r=le(e,t);ue(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=Ea(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Yt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:J(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:J(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:F(r.goal_cycle,`${t}.goal_cycle`,1),iteration:F(r.iteration,`${t}.iteration`),attempt:F(r.attempt,`${t}.attempt`),retry_epoch:F(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:F(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:F(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:F(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:bc(r.next_action,`${t}.next_action`)}}function Hb(e,t){let r=`Native acceptance[${t}]`,i=le(e,r);ue(i,new Set(["id","source","text","result","reason"]),r);let n=Q(i.id,`${r}.id`);if(!Rb.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:kc(i.source,`${r}.source`),text:Q(i.text,`${r}.text`),result:J(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Pe(i.reason,`${r}.reason`)}}function Db(e,t){let r=`Native builder_handoff.checks[${t}]`,i=le(e,r);return ue(i,new Set(["name","result","note"]),r),{name:Pe(i.name,`${r}.name`),result:J(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Pe(i.note,`${r}.note`)}}function Bb(e){let t="Native builder_handoff",r=le(e,t);ue(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=Ea(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Yt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:le(r.review,`${t}.review`);return n&&ue(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Q(r.candidate_id,`${t}.candidate_id`),identity_provider:Q(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:Q(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),summary:Pe(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ke(r.checks,`${t}.checks`,Db),checks_truncated:xr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ke(r.known_limits,`${t}.known_limits`,(a,o)=>Pe(a,`${t}.known_limits[${o}]`)),known_limits_truncated:xr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:J(n.status,["passed"],`${t}.review.status`),summary:Pe(n.summary,`${t}.review.summary`),reviewer_execution_ref:Q(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Cr(r.submitted_at,`${t}.submitted_at`)}}function Lb(e,t){let r=`Native blockers[${t}]`,i=le(e,r);ue(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ea(i.acceptance_ids,`${r}.acceptance_ids`);return Yt(n,`${r}.acceptance_ids`),{owner:J(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Pe(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:J(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Vb(e,t){let r=`Native verification.checks[${t}]`,i=le(e,r);return ue(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:Q(i.id,`${r}.id`),name:Pe(i.name,`${r}.name`),argv_display:Ke(i.argv_display,`${r}.argv_display`,(n,a)=>Pe(n,`${r}.argv_display[${a}]`)),argv_truncated:xr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:kc(i.cwd_ref,`${r}.cwd_ref`,!0),status:J(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Tb(i.exit_code,`${r}.exit_code`),duration_ms:F(i.duration_ms,`${r}.duration_ms`)}}function Mb(e){let t="Native verification",r=le(e,t);ue(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ke(r.checks,`${t}.checks`,Vb);Yt(i.map(a=>a.id),`${t}.checks IDs`);let n=Q(r.identity_provider,`${t}.identity_provider`);return{candidate_id:Q(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Q(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),attempt:F(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":J(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:J(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Pe(r.summary,`${t}.summary`),risks:Ke(r.risks,`${t}.risks`,(a,o)=>Pe(a,`${t}.risks[${o}]`)),risks_truncated:xr(r.risks_truncated,`${t}.risks_truncated`),completed_at:Cr(r.completed_at,`${t}.completed_at`)}}function Ff(e,t){let r=`Native history[${t}]`,i=le(e,r);ue(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ea(i.unresolved_ids,`${r}.unresolved_ids`);return Yt(n,`${r}.unresolved_ids`),{goal_cycle:F(i.goal_cycle,`${r}.goal_cycle`,1),iteration:F(i.iteration,`${r}.iteration`),attempt:F(i.attempt,`${r}.attempt`),outcome:J(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Pe(i.summary,`${r}.summary`),completed_at:Cr(i.completed_at,`${r}.completed_at`)}}function Fb(e){let t="Native history_overflow.outcome_counts",r=le(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ue(r,new Set(i),t),{pass:F(r.pass,`${t}.pass`),fail:F(r.fail,`${t}.fail`),blocked:F(r.blocked,`${t}.blocked`),"execution-error":F(r["execution-error"],`${t}.execution-error`),recovery:F(r.recovery,`${t}.recovery`)}}function qb(e){let t="Native history_overflow",r=le(e,t);ue(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=F(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=Fb(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 Wb(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 zb(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 P(e){let t=le(e,"Native portable state");if(ue(t,_b,"Native portable state"),t.schema!==Er)throw new Error(`Native portable state schema must be ${Er}`);let r=Q(t.name,"Native state name");if(!Cb.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=Ke(t.spec_changes,"Native spec_changes",jb);Yt(i.map(s=>s.capability),"Native spec change capabilities");let n=Ke(t.acceptance,"Native acceptance",Hb);Yt(n.map(s=>s.id),"Native acceptance IDs");let a=Ke(t.history,"Native history",Ff);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Er,name:r,language:J(t.language,["en","zh-CN"],"Native state language"),phase:J(t.phase,["shape","build","verify","archive"],"Native state phase"),status:J(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:F(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Ib(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:J(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:$b(t.workspace),loop:Ob(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Bb(t.builder_handoff),blockers:Ke(t.blockers,"Native blockers",Lb),verification:t.verification===null?null:Mb(t.verification),history:a,history_overflow:qb(t.history_overflow),verification_result:J(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:J(t.verification_report,["verification.md"],"Native verification_report"),archived:xr(t.archived,"Native archived"),created_at:Cr(t.created_at,"Native created_at")};return Wb(o),zb(o),o}function we(e,t){let r=P(e),i=Ff(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 P({...r,history:n,history_overflow:a})}function Jb(e,t){let r=(0,Sa.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 Be(e){let t=await xb.readFile(e,"utf8");return P(Jb(t,"Native portable state"))}async function xa(e,t,r={}){let i=P(t);await Ce(e,(0,Sa.stringify)(i),r)}var ba=new Map;async function Gb(e,t){let r=ba.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ba.set(e,a),await r;try{return await t()}finally{i(),ba.get(e)===a&&ba.delete(e)}}async function Ai(e){return Gb(e.file,async()=>{let t=F(e.expectedStateVersion,"Native expected state version",1),r=P(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Be(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ka(t,i.state_version);return await xa(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Be(e.file);if(n.state_version!==t)throw new ka(t,n.state_version)}}),r})}import Zt from"node:path";import{randomUUID as VS}from"node:crypto";import{promises as qp}from"node:fs";import{promises as jS}from"fs";import $S from"path";import{AsyncLocalStorage as Ub}from"async_hooks";import{randomUUID as zf}from"crypto";import{promises as Re}from"fs";import Jf from"os";import Z from"path";var qf=16*1024,Gf=".coordinator",Kb=5e3,Wf=new Ub,Ca=new Map;function Yb(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Xb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Uf(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Sc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Je(r,i)?M(r,i):M(r,i)&&e.size===t.size}function Ec(e,t){return Sc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function lt(e){let t,r;try{let i=await Nr(e,qf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Oe?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${qf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:Xb(JSON.parse(t.toString("utf8")),e),identity:Uf(r)}}async function Qb(e){return(await lt(e))?.owner??null}function Kf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Jf.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=nk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Zb(e,t){try{await Re.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Re.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function xc(e,t){let r=await lt(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ec(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Re.mkdir(t,{recursive:!0});let i=Z.join(t,`${Z.basename(e.file)}.${e.owner.id}.${zf()}.removed`);try{await Re.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await lt(i);if(!n||n.owner.id!==e.owner.id||!Sc(n.identity,e.identity))throw await Zb(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Re.rm(i,{force:!0}),"removed"}function Yf(e){return{id:zf(),pid:process.pid,hostname:Jf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Xf(e,t){let r;try{r=await Re.open(e,"wx")}catch(i){if(i.code==="EEXIST"){let n=await Qb(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:i})}throw i}try{return await r.writeFile(JSON.stringify(t,null,2)+`
172
+ `,"utf8"),await r.sync(),Uf(await r.stat({bigint:!0}))}finally{await r.close()}}async function ek(e,t){let r=await W(e.runtimeDir,e.locksDir);await Re.mkdir(r,{recursive:!0});let i=await W(e.runtimeDir,Z.join(r,Gf));await Re.mkdir(i,{recursive:!0});let n=Yf(t),a=Z.join(i,`.${n.id}.tmp`),o=Z.join(i,`${n.id}.claim`);try{let s=await Xf(a,n);await Re.rename(a,o);let c=await lt(o);if(!c||!Sc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Re.rm(a,{force:!0})}}async function tk(e){let t=Z.dirname(e.file),r=!1,i=Z.basename(e.file);for(let n of await Re.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Z.join(t,n.name);if(Z.resolve(a)!==Z.resolve(e.file))try{let o=await lt(a),s=Kf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await xc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Qf(e){let t=await lt(e.file);if(t){if(t.owner.id!==e.owner.id||!Ec(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await xc(t,Z.dirname(e.file))}}async function rk(e,t){let r=Date.now()+Kb;for(;;){let i=await ek(e,t);if(!await tk(i))return i;if(await Qf(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function ik(e){let t=Ca.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ca.set(e,n),await t,()=>{r(),Ca.get(e)===n&&Ca.delete(e)}}async function Cc(e,t,r){let i=Z.resolve(e.locksDir),n=Wf.getStore();if(n?.has(i))return r();let a=await ik(i);try{let o=await rk(e,t),s=new Map(n??[]);return s.set(i,o),await Wf.run(s,async()=>{try{return await r()}finally{await Qf(o)}})}finally{a()}}async function Zf(e,t,r){let i=[...new Map(e.map(a=>[Z.resolve(a.locksDir),a])).values()].sort((a,o)=>Z.resolve(a.locksDir).localeCompare(Z.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Cc(o,t,()=>n(a+1)):r()};return n(0)}async function Pa(e,t,r){return Cc(e,`acquire ${t}`,async()=>{let i=await W(e.runtimeDir,e.locksDir);await Re.mkdir(i,{recursive:!0});let n=await W(e.runtimeDir,Z.join(i,Yb(t))),a=Yf(r),o=await Xf(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Ra(e){await lt(e.file)&&await Cc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Z.basename(e.file)}`,async()=>{let t=await lt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ec(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Z.join(e.locksDir,Gf);await xc(t,r)})}function nk(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function ep(e){return Kf(await lt(e))}import Fc from"node:path";import Qk from"node:path";var Hc=Br(mr(),1);import Ar from"path";var Pc={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:"验证预期"}},rp={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:"结论"}},ip={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:"结论"}},np=new Map,tp=new Map;for(let e of Object.keys(Pc)){for(let[t,r]of Object.entries(Pc[e]))np.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(rp[e]))tp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(ip[e]))tp.set(r.toLocaleLowerCase("en-US"),t)}function ak(e,t){return Pc[e][t]}function Rc(e,t){return rp[e][t]??ip[e][t]}function Ac(e){return np.get(e.trim().toLocaleLowerCase("en-US"))??null}function Aa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${ak(e,r)}
173
173
  `).join(`
174
- `)}function Be(e,t,r){return e==="zh-CN"?r:t}import{createHash as Fb}from"node:crypto";import{constants as Ca,promises as Le}from"node:fs";import Ve from"node:path";function Aa(e,t){let r=Ve.relative(e,t);return r===""||!Ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ve.sep}`)}function qb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Wb(e,t){return V({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ra(e,t){return V({...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 Rc(e,t){let r=await Le.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Le.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Jb(e,t,r){let i=Ve.resolve(e),n=Ve.resolve(t);if(!Aa(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Rc(i,r)],o=i;for(let s of Ve.relative(i,n).split(Ve.sep).filter(Boolean)){await Kt(a,r),o=Ve.join(o,s);let c=await Rc(o,r);if(!Aa(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Kt(a,r),a}async function Kt(e,t){for(let r of e){let i=await Le.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Wb(r,i)||await Le.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(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function xr(e){let t=qb(e.maxBytes),r=Ve.resolve(e.file),i=await Jb(e.root,Ve.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Rc(Ve.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Kt(i,e.label);let a=await Le.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=zb(a),s=await Le.realpath(r);if(!Aa(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Aa(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ca.O_RDONLY:Ca.O_RDONLY|Ca.O_NOFOLLOW|Ca.O_NONBLOCK,l=await Le.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Le.lstat(r),Le.realpath(r)]);if(await Kt(i,e.label),await Kt(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!Ra(o,f)||!Ra(o,d))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[v,m,p]=await Promise.all([l.stat(),Le.lstat(r),Le.realpath(r)]);if(await Kt(i,e.label),await Kt(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!Ra(o,v)||!Ra(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:Fb("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}import{createHash as Ub}from"crypto";function Re(e){return Ub("sha256").update(e).digest("hex")}var uA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var dA=8*1024*1024;var fA=64*1024,hA=64*1024;var pA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},mA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var vA=(1n<<256n)-1n;var tk=Hr(hr(),1);var TA=4*1024*1024;var rk=null;function ik(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function eh(e,t){return(...r)=>{let i=rk;if(i===null)return t(...r);let n=ik(`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}}var DA=eh("hookWritePolicy",async e=>(await uc(e))?.hook??{allow_paths:[]});var __=256*1024;var q_={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import Pr from"node:path";var Ri=/^[a-f0-9]{64}$/u,rh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ak=16*1024,nI=process.platform;function ok(e,t){let r=Pr.relative(e,t);return Pr.isAbsolute(r)||r===".."||r.startsWith(`..${Pr.sep}`)?null:r.replaceAll("\\","/")||"."}function ih(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function nh(e,t){if(e.length===0||ih(e)||e.includes("\\")||Pr.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=Pr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function sk(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 Ac(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ih(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function ck(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Ac(e.changeBranch,"Native workspace change branch"),Ac(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 lk(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"||!rh.test(t.baseCommit)||typeof t.targetCommit!="string"||!rh.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Ac(t.targetBranch,"Native workspace Git target branch")}function uk(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"||!Ri.test(String(t.projectRootId))||!Ri.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");sk(t.capturedAt),nh(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&&!Ri.test(String(t.projectRootPathId))||a&&!Ri.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ri.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&lk(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(ck(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 dk(e,t){return Pr.join(Je(e,t),"workspace.json")}function fk(e,t){let r=dk(e,t),i=Ge(e,r),n=ok(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:nh(n,"Native workspace file ref")}}async function hk(e,t){try{let r=fk(e,t),i=await J({root:r.root,ref:r.ref,maxBytes:ak});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ai(e,t){let r=await hk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(uk(r),r)}var ct="comet.native.v3",Ke="comet.native.v2",Ye="comet.native.v1";var ah=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],mk=new Set(ah),oh=new Set([...ah,"minimum_runtime_version","revision"]),vk=new Set([...oh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),gk=new Set(["capability","operation","source","base_hash"]),wk=new Set(["shape","build","verify","archive"]),yk=new Set(["implicit","confirmed"]),Nk=new Set(["pending","pass","fail"]),Yt="comet-state.yaml",Ic=/^[a-f0-9]{64}$/u,sh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Tc=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"},Rr=class extends Error{constructor(r,i){super(r!==ct||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"},_a=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"},_i=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"},Ia=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"},II=Pa("en");function Ti(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ch(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 Oc(e){if(!sh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function kk(e){if(!sh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function lh(e,t){if(e.length===0||Cr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Sk(e,t){let r=Ti(e,`spec_changes[${t}]`);if(ch(r,gk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(kk(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"&&lh(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"||!Ic.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"||!Ic.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 Ek(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 Hc(e,t){if(ch(e,t,Yt),typeof e.name!="string")throw new Error("Native change name is required");if(Oc(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"||!wk.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&&!yk.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(Sk),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"||!Nk.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"&&lh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Ek(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=Ti(e,Yt);if(t.schema!==Ye)throw new Error(`Expected ${Ye}`);return{schema:Ye,...Hc(t,mk)}}function Ii(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _c(e,t,r){if(e===null)return null;let i=typeof e=="string"?bk.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 xk(e){if(e==null)return null;if(typeof e!="string"||!Ic.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Pk(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 $i(e){let t=Ti(e,Yt);if(t.schema!==Ke)throw new Error(`Expected ${Ke}`);if(Ii(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ke} minimum_runtime_version must be 2`);return{schema:Ke,minimum_runtime_version:2,revision:Ii(t.revision,"Native v2 revision"),...Hc(t,oh)}}function Oi(e){let t=Ti(e,Yt);if(t.schema!==ct){if(t.schema===Ye||t.schema===Ke){let o=t.schema===Ye?ji(t):$i(t);throw new Tc(o.name,o.schema)}throw new Rr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Ii(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Rr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Ii(t.revision,"Native revision"),n=Hc(t,vk),a=xk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ct,minimum_runtime_version:3,revision:i,verification_protocol:Pk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_c(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_c(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_c(t.partial_allowance,"Native partial_allowance","allowances")}}function Ck(e){let t=Ti(e,Yt);if(t.schema===Ye){let n=ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(t.schema===Ke){let n=$i(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(t.schema!==ct){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 Rr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Ii(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Rr(t.schema,r).message};let i=Oi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Xe(e,t){Oc(t);let r=Cr.join(e.changesDir,t);if(!se(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Rk(e,t=Cr.dirname(e)){let r=Cr.relative(t,e).split(Cr.sep).join("/"),i=await J({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,$c.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 uh(e,t){let r=Cr.join(Xe(e,t),Yt);await q(e.nativeRoot,r);let i=Ck(await Rk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import vh from"node:path";var Ak="comet.native.acceptance.v1";var OI=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ja=Object.freeze({maxCriteria:1024});function hh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function dh(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function fh(e){return e.includes("-->")||e.includes("--!>")}function*Ta(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
174
+ `)}function Le(e,t,r){return e==="zh-CN"?r:t}import{createHash as ok}from"node:crypto";import{constants as _a,promises as Ve}from"node:fs";import Me from"node:path";function Ta(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function sk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function ck(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ia(e,t){return M({...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 _c(e,t){let r=await Ve.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ve.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function uk(e,t,r){let i=Me.resolve(e),n=Me.resolve(t);if(!Ta(i,n))throw new Error(`${r} is outside its managed root`);let a=[await _c(i,r)],o=i;for(let s of Me.relative(i,n).split(Me.sep).filter(Boolean)){await Xt(a,r),o=Me.join(o,s);let c=await _c(o,r);if(!Ta(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Xt(a,r),a}async function Xt(e,t){for(let r of e){let i=await Ve.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!ck(r,i)||await Ve.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function dk(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Pr(e){let t=sk(e.maxBytes),r=Me.resolve(e.file),i=await uk(e.root,Me.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>_c(Me.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Xt(i,e.label);let a=await Ve.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=lk(a),s=await Ve.realpath(r);if(!Ta(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Ta(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?_a.O_RDONLY:_a.O_RDONLY|_a.O_NOFOLLOW|_a.O_NONBLOCK,l=await Ve.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Ve.lstat(r),Ve.realpath(r)]);if(await Xt(i,e.label),await Xt(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!Ia(o,f)||!Ia(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await dk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([l.stat(),Ve.lstat(r),Ve.realpath(r)]);if(await Xt(i,e.label),await Xt(n,e.label),!m.isFile()||m.isSymbolicLink()||h!==s||!Ia(o,v)||!Ia(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:ok("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}import{createHash as fk}from"crypto";function Ae(e){return fk("sha256").update(e).digest("hex")}var VA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var MA=8*1024*1024;var FA=64*1024,qA=64*1024;var WA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},zA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var JA=(1n<<256n)-1n;var yk=Br(mr(),1);var c_=4*1024*1024;var Nk=null;function bk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function ap(e,t){return(...r)=>{let i=Nk;if(i===null)return t(...r);let n=bk(`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}}var p_=ap("hookWritePolicy",async e=>(await fc(e))?.hook??{allow_paths:[]});var oI=256*1024;var yI={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import Rr from"node:path";var _i=/^[a-f0-9]{64}$/u,sp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Sk=16*1024,$I=process.platform;function Ek(e,t){let r=Rr.relative(e,t);return Rr.isAbsolute(r)||r===".."||r.startsWith(`..${Rr.sep}`)?null:r.replaceAll("\\","/")||"."}function cp(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function lp(e,t){if(e.length===0||cp(e)||e.includes("\\")||Rr.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=Rr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function xk(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 Ic(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||cp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ck(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Ic(e.changeBranch,"Native workspace change branch"),Ic(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 Pk(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"||!sp.test(t.baseCommit)||typeof t.targetCommit!="string"||!sp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Ic(t.targetBranch,"Native workspace Git target branch")}function Rk(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"||!_i.test(String(t.projectRootId))||!_i.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");xk(t.capturedAt),lp(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&&!_i.test(String(t.projectRootPathId))||a&&!_i.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!_i.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Pk(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(Ck(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 Ak(e,t){return Rr.join(Ge(e,t),"workspace.json")}function _k(e,t){let r=Ak(e,t),i=Ue(e,r),n=Ek(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:lp(n,"Native workspace file ref")}}async function Ik(e,t){try{let r=_k(e,t),i=await U({root:r.root,ref:r.ref,maxBytes:Sk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ii(e,t){let r=await Ik(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Rk(r),r)}var ut="comet.native.v3",Ye="comet.native.v2",Xe="comet.native.v1";var up=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],jk=new Set(up),dp=new Set([...up,"minimum_runtime_version","revision"]),$k=new Set([...dp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Ok=new Set(["capability","operation","source","base_hash"]),Hk=new Set(["shape","build","verify","archive"]),Dk=new Set(["implicit","confirmed"]),Bk=new Set(["pending","pass","fail"]),Qt="comet-state.yaml",jc=/^[a-f0-9]{64}$/u,fp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,$c=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"},_r=class extends Error{constructor(r,i){super(r!==ut||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"},ja=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"},Ti=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"},$a=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"},sT=Aa("en");function $i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function pp(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 Dc(e){if(!fp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Vk(e){if(!fp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function hp(e,t){if(e.length===0||Ar.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Mk(e,t){let r=$i(e,`spec_changes[${t}]`);if(pp(r,Ok,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Vk(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"&&hp(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"||!jc.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"||!jc.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 Fk(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 Bc(e,t){if(pp(e,t,Qt),typeof e.name!="string")throw new Error("Native change name is required");if(Dc(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"||!Hk.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&&!Dk.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(Mk),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"||!Bk.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"&&hp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Fk(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 Oi(e){let t=$i(e,Qt);if(t.schema!==Xe)throw new Error(`Expected ${Xe}`);return{schema:Xe,...Bc(t,jk)}}function ji(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Tc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Lk.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 qk(e){if(e==null)return null;if(typeof e!="string"||!jc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Wk(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 Hi(e){let t=$i(e,Qt);if(t.schema!==Ye)throw new Error(`Expected ${Ye}`);if(ji(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ye} minimum_runtime_version must be 2`);return{schema:Ye,minimum_runtime_version:2,revision:ji(t.revision,"Native v2 revision"),...Bc(t,dp)}}function Di(e){let t=$i(e,Qt);if(t.schema!==ut){if(t.schema===Xe||t.schema===Ye){let o=t.schema===Xe?Oi(t):Hi(t);throw new $c(o.name,o.schema)}throw new _r(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=ji(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new _r(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=ji(t.revision,"Native revision"),n=Bc(t,$k),a=qk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ut,minimum_runtime_version:3,revision:i,verification_protocol:Wk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Tc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Tc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Tc(t.partial_allowance,"Native partial_allowance","allowances")}}function zk(e){let t=$i(e,Qt);if(t.schema===Xe){let n=Oi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ut}`}}if(t.schema===Ye){let n=Hi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ut}`}}if(t.schema!==ut){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 _r(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=ji(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new _r(t.schema,r).message};let i=Di(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Qe(e,t){Dc(t);let r=Ar.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Jk(e,t=Ar.dirname(e)){let r=Ar.relative(t,e).split(Ar.sep).join("/"),i=await U({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Hc.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 mp(e,t){let r=Ar.join(Qe(e,t),Qt);await W(e.nativeRoot,r);let i=zk(await Jk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import bp from"node:path";var Gk="comet.native.acceptance.v1";var dT=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ha=Object.freeze({maxCriteria:1024});function wp(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function vp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function gp(e){return e.includes("-->")||e.includes("--!>")}function*Oa(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
175
175
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
176
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=dh(l,t);else if(r)fh(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=dh(l,null);if(d!==null)t=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!fh(u))r=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);h&&n.has(h[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(u)&&(i=h[1])}}}if(c===-1)break;o=c+1}}function Hi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function ph(e,t,r,i=[],n="content-hash"){let a=Hi(r),o=t.replaceAll("\\","/").trim(),s=i.map(Hi);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${pe(Ak,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function mh(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function _k(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ta(e)){n=s+1;let c=o?hh(a):null;c?.level===1&&(Cc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Dc(e,t="brief.md",r=ja.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=_k(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of Ta(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let h=u[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:d}of Ta(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),mh(o.map(l=>ph("brief-example",t,l.join(`
177
- `),[],i)),"Brief",i)}function Bc(e,t="spec.md",r=ja.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(ph("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Ta(e)){let f=l?hh(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=Hi(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(h=>h.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),mh(n,"Specification",i)}var Ik=/^A[1-9]\d*$/u;function gh(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||vh.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||vh.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Tk(e,t){return e.localeCompare(t,"en")}function $a(e){let t=gh(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>Tk(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Dc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=gh(a.source,`Native spec source for ${a.capability}`);i.push(...Bc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Hi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function wh(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!Ik.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function yh(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function jk(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function O(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(jk(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Oa="comet.native.portable-migration.v1",Ok=new Set(["schema","id","change","fromSchema","status","createdAt"]),Hk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Dk=/^[a-z0-9][a-z0-9-]{7,127}$/u,Bk=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Lk=new Set([Ye,Ke,ct]);function Vk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mk(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function Fk(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function qk(e){return e.schema===Ye?ji(e):e.schema===Ke?$i(e):Oi(e)}function Wk(e){return $k.posix.normalize(e.replaceAll("\\","/"))}function zk(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:Wk(t.source)})}function Jk(e){return e==="shape"?"shape":"build"}function Gk(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Uk(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Nh(e){let t=qk(e.state);wh(e.acceptance);let r=Jk(t.phase),i=r==="shape"?0:1,n=Mk(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return C({schema:kr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:zk(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Gk(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:O(Uk(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:gc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Lc(e){let t=Vk(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Ok.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Oa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Dk.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Hk.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Lk.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Bk.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Oa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Fk(t.createdAt,"Native portable migration transaction createdAt")}}function bh(e){switch(Lc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var kh="comet.native.archive-transaction.v4",Sh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Kk=new RegExp(`^portable-archive-(${Sh})\\.json$`,"u"),Yk=new RegExp(`^portable-migration-(${Sh})\\.json$`,"u"),Xk=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Qk=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zk=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),eS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),tS=new Set(["capability","operation","source","content"]),Eh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function xh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ph(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(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function rS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=xh(e,r);if(Ph(i,tS,r),typeof i.capability!="string"||!Eh.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function iS(e){let t=xh(e,"Native portable Archive transaction");if(Ph(t,eS,"Native portable Archive transaction"),t.schema!==kh)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Xk.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Eh.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!Qk.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!Zk.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(rS);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:kh,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Ha(e){let t=Kk.exec(e);if(t)return{kind:"archive",change:t[1]};let r=Yk.exec(e);return r?{kind:"migration",change:r[1]}:null}function Da(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ha(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Vc.join(e.transactionsDir,r)}async function Mc(e,t){let r=Ha(t);if(!r)return null;let i=await J({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Vc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=iS(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Lc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Ch(e,t){let r=Da(e,t);try{return await Mc(e,Vc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Rh(e){return e.kind==="archive"||e.journal.status!=="committed"}import lt from"path";import{TextDecoder as aS}from"util";var oS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),sS=new Set(["id","type","source","target","staged","backup"]),cS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),lS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Ih=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var uS=256*1024,oT=1024*1024,sT=16*1024;var cT=64*1024*1024;var dS=new aS("utf-8",{fatal:!0});function La(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Va(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 Th(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Fc(e,t){if(typeof e!="string"||e.length===0||lt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ba(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Ah(e,t){if(Fc(e,t),e.includes("\\")||e!==lt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function fS(e,t){let r=La(e,`transaction operations[${t}]`);if(Va(r,sS,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Fc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Fc(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function jh(e){let t=La(e,"Native Archive transaction journal");if(Va(t,cS,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Ih.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Th(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ba(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=La(s,`Archive transaction operations[${c}]`);if(Va(l,lS,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Ah(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Ah(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Ba(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Ba(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Ba(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function hS(e){let t=La(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return jh(t);if(Va(t,oS,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Ih.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!lt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!lt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Th(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(fS),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function pS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return lt.join(e.transactionsDir,t)}function $h(e,t){let r=pS(e,t);return{directory:r,journal:lt.join(r,"transaction.json"),events:lt.join(r,"events.jsonl"),staged:lt.join(r,"staged"),backups:lt.join(r,"backups")}}async function qc(e,t){let r=$h(e,t);return await Promise.all(Object.values(r).map(i=>q(e.runtimeDir,i))),r}async function Wc(e,t,r={}){let i=await qc(e,t),n=await xr({root:e.runtimeDir,file:i.journal,maxBytes:uS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(dS.decode(n.bytes)),o=hS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function gS(e,t,r){let i;try{i=await mS.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Wc(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Ha(n.name))try{let a=await Mc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Rh(a))return!0}catch{return!0}return!1}async function wS(e,t){let r=Date.now()+5e3,i=vS.join(e.locksDir,"root-move.lock");for(;;)try{return await Ea(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Kf(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function P(e,t,r,i){let n=await wS(e,t);try{if(await ma(e.projectRoot),await gS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await xa(n)}}import{promises as Di}from"node:fs";import ne from"node:path";var Tt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function zc(e,t){let r=ne.normalize(e),i=ne.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Dh(e,t){let r=ne.relative(e,t);return r===""||!ne.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ne.sep}`)}function Oh(e){return JSON.stringify(e.native)}async function Ma(e,t){let r=await ve(e);if(r&&t){if(Oh(r)!==Oh(t))throw new Error(`Native worktree configuration differs from the source project: ${ne.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await va(e,t),!0):!1}async function yS(e,t){if(!Dh(e,t))return!1;let i=`/${ne.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=A(e,["rev-parse","--git-common-dir"]),a=ne.resolve(e,n),o=ne.join(a,"info","exclude"),s="";try{s=await Di.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Di.mkdir(ne.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
176
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=vp(l,t);else if(r)gp(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=vp(l,null);if(d!==null)t=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!gp(u))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function Bi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function yp(e,t,r,i=[],n="content-hash"){let a=Bi(r),o=t.replaceAll("\\","/").trim(),s=i.map(Bi);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${me(Gk,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Np(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function Uk(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Oa(e)){n=s+1;let c=o?wp(a):null;c?.level===1&&(Ac(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Lc(e,t="brief.md",r=Ha.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=Uk(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of Oa(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let p=u[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:d}of Oa(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),Np(o.map(l=>yp("brief-example",t,l.join(`
177
+ `),[],i)),"Brief",i)}function Vc(e,t="spec.md",r=Ha.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(yp("spec-scenario",t,[o.title,...o.body].join(`
178
+ `),o.context,i)),o=null}};for(let{line:c,body:l}of Oa(e)){let f=l?wp(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=Bi(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Np(n,"Specification",i)}var Kk=/^A[1-9]\d*$/u;function kp(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||bp.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||bp.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Yk(e,t){return e.localeCompare(t,"en")}function Da(e){let t=kp(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>Yk(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Lc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=kp(a.source,`Native spec source for ${a.capability}`);i.push(...Vc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Bi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Sp(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!Kk.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Ep(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function Xk(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function H(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(Xk(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Ba="comet.native.portable-migration.v1",Zk=new Set(["schema","id","change","fromSchema","status","createdAt"]),eS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tS=/^[a-z0-9][a-z0-9-]{7,127}$/u,rS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),iS=new Set([Xe,Ye,ut]);function nS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function aS(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function oS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function sS(e){return e.schema===Xe?Oi(e):e.schema===Ye?Hi(e):Di(e)}function cS(e){return Qk.posix.normalize(e.replaceAll("\\","/"))}function lS(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:cS(t.source)})}function uS(e){return e==="shape"?"shape":"build"}function dS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function fS(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function xp(e){let t=sS(e.state);Sp(e.acceptance);let r=uS(t.phase),i=r==="shape"?0:1,n=aS(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return P({schema:Er,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:lS(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:dS(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:H(fS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:yc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Mc(e){let t=nS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Zk.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ba)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!tS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!eS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!iS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!rS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ba,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:oS(t.createdAt,"Native portable migration transaction createdAt")}}function Cp(e){switch(Mc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Pp="comet.native.archive-transaction.v4",Rp="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",pS=new RegExp(`^portable-archive-(${Rp})\\.json$`,"u"),hS=new RegExp(`^portable-migration-(${Rp})\\.json$`,"u"),mS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),wS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),yS=new Set(["capability","operation","source","content"]),Ap=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function _p(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ip(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(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function NS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=_p(e,r);if(Ip(i,yS,r),typeof i.capability!="string"||!Ap.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function bS(e){let t=_p(e,"Native portable Archive transaction");if(Ip(t,wS,"Native portable Archive transaction"),t.schema!==Pp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!mS.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Ap.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!vS.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!gS.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(NS);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Pp,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function La(e){let t=pS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=hS.exec(e);return r?{kind:"migration",change:r[1]}:null}function Va(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=La(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Fc.join(e.transactionsDir,r)}async function qc(e,t){let r=La(t);if(!r)return null;let i=await U({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Fc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=bS(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Mc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Tp(e,t){let r=Va(e,t);try{return await qc(e,Fc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function jp(e){return e.kind==="archive"||e.journal.status!=="committed"}import dt from"path";import{TextDecoder as SS}from"util";var ES=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),xS=new Set(["id","type","source","target","staged","backup"]),CS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),PS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Hp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var RS=256*1024,HT=1024*1024,DT=16*1024;var BT=64*1024*1024;var AS=new SS("utf-8",{fatal:!0});function Fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qa(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 Dp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Wc(e,t){if(typeof e!="string"||e.length===0||dt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ma(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $p(e,t){if(Wc(e,t),e.includes("\\")||e!==dt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function _S(e,t){let r=Fa(e,`transaction operations[${t}]`);if(qa(r,xS,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Wc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Wc(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Bp(e){let t=Fa(e,"Native Archive transaction journal");if(qa(t,CS,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Hp.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Dp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ma(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Fa(s,`Archive transaction operations[${c}]`);if(qa(l,PS,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);$p(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&$p(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Ma(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Ma(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Ma(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function IS(e){let t=Fa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bp(t);if(qa(t,ES,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Hp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!dt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!dt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Dp(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(_S),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function TS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return dt.join(e.transactionsDir,t)}function Lp(e,t){let r=TS(e,t);return{directory:r,journal:dt.join(r,"transaction.json"),events:dt.join(r,"events.jsonl"),staged:dt.join(r,"staged"),backups:dt.join(r,"backups")}}async function zc(e,t){let r=Lp(e,t);return await Promise.all(Object.values(r).map(i=>W(e.runtimeDir,i))),r}async function Jc(e,t,r={}){let i=await zc(e,t),n=await Pr({root:e.runtimeDir,file:i.journal,maxBytes:RS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(AS.decode(n.bytes)),o=IS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function OS(e,t,r){let i;try{i=await jS.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Jc(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(La(n.name))try{let a=await qc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(jp(a))return!0}catch{return!0}return!1}async function HS(e,t){let r=Date.now()+5e3,i=$S.join(e.locksDir,"root-move.lock");for(;;)try{return await Pa(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await ep(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function C(e,t,r,i){let n=await HS(e,t);try{if(await wa(e.projectRoot),await OS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ra(n)}}import{promises as Li}from"node:fs";import ae from"node:path";var Ot=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Gc(e,t){let r=ae.normalize(e),i=ae.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Fp(e,t){let r=ae.relative(e,t);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function Vp(e){return JSON.stringify(e.native)}async function Wa(e,t){let r=await ge(e);if(r&&t){if(Vp(r)!==Vp(t))throw new Error(`Native worktree configuration differs from the source project: ${ae.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await ya(e,t),!0):!1}async function DS(e,t){if(!Fp(e,t))return!1;let i=`/${ae.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=_(e,["rev-parse","--git-common-dir"]),a=ae.resolve(e,n),o=ae.join(a,"info","exclude"),s="";try{s=await Li.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Li.mkdir(ae.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
179
179
  `)?"":`
180
- `;return await Di.appendFile(o,`${c}${i}
181
- `,"utf8"),!0}function NS(e,t,r){let i=ne.resolve(e,r??ne.join(".worktrees",t)),n=ne.resolve(e,A(e,["rev-parse","--git-common-dir"]));if(Dh(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Wt(e).some(a=>zc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function bS(e){try{throw await Di.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Hh(e){try{return await Di.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Jc(e){let t=ne.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=F(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await _t(t,e.sourceConfig?.native.artifact_root??"docs");return Uf([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=F(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Qs(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Qs(t,o),!pr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!at(t))throw new Error("Native branch isolation requires a clean current working directory");if(pr(t,n))throw new Error(`Native change branch already exists: ${n}`);A(t,["switch","-c",n,o]),h=!0}let v;try{v=await Ma(t,e.sourceConfig)}catch(m){throw new Tt(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!zc(h,i.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Ma(t,e.sourceConfig)}catch(m){throw new Tt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=ta(i.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await Hh(c.root)){let h=e.worktreePath?ne.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!zc(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Ma(c.root,e.sourceConfig)}catch(m){throw new Tt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await Hh(c.root)&&(A(i.primaryWorktreeRoot,["worktree","prune"]),s=ta(i.primaryWorktreeRoot));let l=pr(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=NS(i.primaryWorktreeRoot,e.name,e.worktreePath);await bS(f);let d=await yS(i.primaryWorktreeRoot,f),u={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{A(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),u.createdBranch=!l,u.createdWorktree=!0,u.configInitialized=await Ma(f,e.sourceConfig)}catch(h){throw new Tt(`Native worktree preparation is incomplete: ${h.message}`,u,{cause:h})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:u}})}var Gc="comet.native.supervisor.v2",SS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Lh(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`}async function Vh(e){let t=Xt.join(".worktrees",`${e.parent}-integration`);return Jc({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Lh(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function ES(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Jc({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Xt.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function xS(e,t){return Xt.join(He(e,t),"supervisor")}function Fa(e,t){return Xt.join(xS(e,t),"state.json")}function Mh(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!==Gc)throw new Error(`Native Supervisor state schema must be ${Gc}`);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(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(jt(t.integration.targetCommit,"Native Supervisor target commit"),jt(t.integration.headCommit,"Native Supervisor integration head commit"),!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.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&&jt(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(jt(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.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 re(e,t){try{let r=await Bh.readFile(Fa(e,t),"utf8"),i=JSON.parse(r);return Mh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ae(e,t){Mh(t),await Bh.mkdir(e.changesRuntimeDir,{recursive:!0}),await me(Fa(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function jt(e,t){if(!SS.test(e))throw new Error(`${t} must be a Git commit`)}function Qe(e){return structuredClone(e)}function ut(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function PS(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function CS(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Uc(e){jt(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}));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:Gc,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}}}async function qa(e){let t=Lh(e.parent),r=mr(e.paths.projectRoot,t);if(!r)return null;let i=mr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Wt(e.paths.projectRoot).map(o=>Xt.resolve(o)).find(o=>F(o).currentBranch===t);if(!n)return null;let a=Uc({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 ut(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Fh(e){let t=Qe(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function Kc(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Qe(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);PS(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,ut(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function RS(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function qh(e,t){let r=RS(e,t),i=Qe(e);return ut(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function AS(e,t,r){let i=F(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!at(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=A(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return A(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return A(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(A(e,["merge","--ff-only",r]),A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function _S(e){if(!at(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=A(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Xt.resolve(t)!==Xt.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=A(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return A(e.integration.worktree,["rev-parse","HEAD"])}function IS(e,t,r){let i=F(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!at(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function Yc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,ut(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Wa(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,ut(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function Wh(e){return P(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await re(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await ve(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let d;try{d=await ES({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?IS(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):AS(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(h){let v=Qe(o),m=v.children.find(({name:p})=>p===l.name);m&&(m.blocker=h.message,ut(v,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let u=Kc(o,{role:f?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:kS()});o=u.state,s.push(u.task)}return(s.length>0||c)&&await ae(e.paths,o),{state:o,tasks:s}})}function zh(e,t){jt(t.candidateCommit,"Native Supervisor candidate commit");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,ut(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Jh(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Qe(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),ut(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function TS(e,t){jt(t.integrationCommit,"Native Supervisor integration commit");let r=Qe(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,ut(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function Gh(e){return P(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await re(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=CS(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=_S(r);if(a!==r.integration.headCommit){let c=(()=>{try{return A(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return A(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{A(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{A(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=A(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=TS(r,{name:e.name,integrationCommit:o,checks:e.checks});return await ae(e.paths,s),s})}function Uh(e,t){if(jt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Qe(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Kh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var Yh="children.yaml",za="comet.native.children.v1",Ar="comet.native.children.v2",jS=Ar,$S=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xh=new Set(["schema","children"]),OS=new Set(["schema","acceptance_index","children"]),HS=new Set(["name","depends_on","covers"]),DS=new Set(["name","summary","depends_on"]),BS=new Set(["name","depends_on","covers"]);function Ga(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ja(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 Qh(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 Xc(e,t){let r=Ae.normalize(Ae.resolve(e)),i=Ae.normalize(Ae.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function LS(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 Zh(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 Bi(e){let t=new Set(e.acceptance.filter(({source:r})=>r===e.brief).map(({id:r})=>r));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let r=[...e.history].reverse().find(({outcome:i})=>i==="fail");for(let i of r?.unresolved_ids??[])t.add(i)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function VS(e){let t=Ga(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=Ga(n,`Native children acceptance_index.${i}`);if(Ja(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 MS(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=Object.keys(e),a=i.filter(c=>!(c in e)),o=n.filter(c=>!i.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of i){let l=s.get(c);if(!l)continue;let f=e[c];if(f.source!==l.source||f.text!==l.text){let d=["source","text"].filter(u=>f[u]!==l[u]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function FS(e,t,r={}){let i=(0,Qc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Ga(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==za&&a!==Ar)throw Ja(n,Xh,"Native children contract"),new Error(`Native children schema must be ${za} or ${Ar}`);let o=a===za?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ja(n,o==="indexed-v2"?OS:Xh,"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((d,u)=>{let h=Ga(d,`Native child ${u}`);if(Ja(h,o==="indexed-v2"?BS:o==="summary-v2"?DS:HS,`Native ${s} child fields (child ${u})`),typeof h.name!="string"||!$S.test(h.name))throw new Error(`Native child ${u} name is invalid`);let v=o==="summary-v2";if(v){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:v?h.summary:null,depends_on:Qh(h.depends_on,`Native child ${h.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Qh(h.covers,`Native child ${h.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let d of c){let u=d.depends_on.filter(h=>!f.has(h));if(u.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${u.join(", ")}`)}if(LS(c),a===jS){if(o==="indexed-v2"){let d=VS(n.acceptance_index);MS(d,t,r);let u=Object.keys(d);return Zh(c,u,u),{schema:Ar,acceptance_index:d,children:c}}return{schema:Ar,children:c}}return t&&Zh(c,t),{schema:za,children:c}}async function Li(e){let t=Ae.join(e.changeDir,Yh);try{await tp.lstat(t)}catch(i){if(i.code==="ENOENT")return null;throw i}let r=await J({root:e.changeDir,ref:Yh});return{contract:FS(r.text,e.acceptanceIds,e.validation),size:r.size}}function qS(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 WS(e){let t=qS(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 Zc(e){try{let t=await J({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return WS(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ua(e){return pe("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 zS(e){let t=Wt(e.projectRoot);t.some(i=>Xc(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Ae.resolve(n)))]){let n=await ve(i);n&&r.push({projectRoot:i,paths:await _t(i,n.native.artifact_root),parent:Xc(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function JS(e,t){let r=Ae.join(e.paths.changesDir,t,"comet-state.yaml");try{return await De(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GS(e,t){let r;try{r=await tp.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=Ae.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await De(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function US(e,t,r){let i=Ae.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Ae.sep}`))return null;let n=i.split(Ae.sep).join("/");try{let a=(0,Qc.parseDocument)(A(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:C(a.toJS({mapAsMap:!1}))}catch{return null}}function KS(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 ep(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ze(e){let t=Ae.join(e.paths.changesDir,e.state.name),r=await Zc(t),i=await Li({changeDir:t,validation:Bi(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{}});if(!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 n=Ua({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n;if(i.contract.schema===Ar){let p=await re(e.paths,e.state.name);if(!p){let w=e.state.workspace.target_branch??e.state.workspace.change_branch;if(w){let k=await qa({paths:e.paths,parent:e.state.name,targetBranch:w,contract:i.contract});k&&(p=k,await ae(e.paths,k))}}if(p){let w=Kh(p);return e.state.children_contract_hash!==n?{...w,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(k=>({...k,message:"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let y=new Map(i.contract.children.map(w=>[w.name,w])),g=i.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:o&&w.depends_on.every(k=>i.contract.children.filter(({name:S})=>S!==w.name).every(({name:S})=>S!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let w of g){if(w.status!=="ready")continue;y.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let s=await zS(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,f=new Map;for(let p of s){let y=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await GS(p,c)){let w={...g,source:p,committedState:US(p,g.file,y)};l.set(g.state.name,[...l.get(g.state.name)??[],w])}for(let g of c){let w=await JS(p,g);w&&f.set(g,[...f.get(g)??[],{source:p,state:w}])}}let d=new Map;for(let p of i.contract.children){let y=(l.get(p.name)??[]).find(({source:k,committedState:S})=>k.parent&&S?.name===p.name&&ep(S,a));if(y){d.set(p.name,{kind:"done",phase:y.state.phase,projectRoot:y.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let w=f.get(p.name)??[];w.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):w[0]&&d.set(p.name,KS(w[0].state,w[0].source,a))}let u=new Map(i.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let y=h.get(p);if(y)return y;let g=u.get(p),k=g.depends_on.map(v).every(({status:Y})=>Y==="done"),S=d.get(p),E=S?.kind==="active"&&k?g.depends_on.filter(Y=>!(l.get(Y)??[]).some(({source:ee,committedState:$})=>Xc(ee.projectRoot,S.projectRoot)&&$?.name===Y&&ep($,a))):[],x,N=S?.message??null;S?.kind==="done"?(x=k?"done":"blocked",k||(N=`Native child ${p} was merged before its dependencies`)):S?.kind==="active"?(x=k&&E.length===0?"active":"blocked",k?E.length>0&&(N=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):S?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(N="Parent Shape confirmation is required"));let _={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:x,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:N};return h.set(p,_),_},m=i.contract.children.map(({name:p})=>v(p));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}function Qt(e,t,r){return e.language==="zh-CN"?r:t}function YS(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});return t&&e.phase==="shape"&&e.status==="active"?{required:!0,message:Qt(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:Qt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Qt(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")}:e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"?r(Qt(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,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。")):e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"?r(Qt(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")):e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier")?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."}:e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable"?e.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."}:r(Qt(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 tl(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ka(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function rp(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function XS(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function QS(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function ZS(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function Vi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:tl({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ka("summary","--summary"),rp(e.name,e.flag)]}}function el(e){return[Vi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Vi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function U(e,t){let r=QS(t)&&e.coordination_mode===void 0,i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:YS(e,r)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ka("summary","--summary")],commandAlternatives:[Vi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...el({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:tl({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ka("summary","--summary")],commandAlternatives:[Vi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...el({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ka("summary","--summary")],commandAlternatives:el({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...i,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?tl({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:r?"await-user":"continue",action:"confirm-shape",commandArgs:ZS({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[XS("coordination-mode","--coordination-mode",ga)]:[],rp("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...i,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}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...i,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...i,userCommunication:!a&&o?{...i.userCommunication,agentInstruction:`${i.userCommunication.agentInstruction} ${Qt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:i.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Vi({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as KE}from"node:crypto";import{promises as Yi}from"node:fs";import YE from"node:path";import{randomUUID as wl}from"node:crypto";import{promises as Gi}from"node:fs";import Z from"node:path";import{createWriteStream as NE,promises as bE}from"node:fs";import be from"node:path";import{spawn as rl}from"node:child_process";import{existsSync as ip}from"node:fs";import Zt from"node:path";var eE=new Set([".bat",".cmd",".ps1"]),tE=new Set([".bat",".cmd"]),rE=/[&|<>()^%"!\r\n]/u,iE=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function il(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function nE(e){let t=(il(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function aE(e,t,r){let n=Zt.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(il(t,"PATH")??"").split(Zt.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Zt.win32.extname(e)?[e]:nE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Zt.join(s,c):Zt.resolve(r,c)))}function oE(e,t,r){return aE(e,t,r).find(i=>ip(i))??e}function sE(e){let t=il(e,"SystemRoot");if(t){let r=Zt.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(ip(r))return r}return"powershell.exe"}function cE(e){if(e.some(t=>rE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function lE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(iE,"utf16le").toString("base64");return rl(sE(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function nl(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return rl(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=oE(e,i,r.cwd),a=Zt.win32.extname(n).toLowerCase();return tE.has(a)&&cE(t),eE.has(a)?lE(n,t,{cwd:r.cwd,env:i}):rl(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as uE}from"node:child_process";import al from"node:path";var dE=1e3,fE=2;async function Ya(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&al.win32.isAbsolute(r)?al.win32.resolve(r):"C:\\Windows",n=al.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(d,u=!1)=>{s||(s=!0,l&&clearTimeout(l),u&&c?.kill("SIGKILL"),o(d))};try{c=uE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",d=>f(d===0)),l=setTimeout(()=>f(!1,!0),dE)}catch{f(!1)}});for(let o=0;o<fE;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var hE=/\b(Bearer|Basic)\s+[^\s"']+/giu,pE=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,mE=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,vE=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,gE=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,wE=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,yE=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function $t(e){return e.replace(hE,"$1 [REDACTED]").replace(pE,"[REDACTED PRIVATE KEY]").replace(mE,"$1[REDACTED]@").replace(vE,"[REDACTED TOKEN]").replace(gE,'$1"[REDACTED]"').replace(wE,"$1$2$1$3$4[REDACTED]$4").replace(yE,"$1$2[REDACTED]")}function np(e,t){let r=be.relative(e,t);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function ap(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Xa(e,t){if(t.length===0||t.includes("\\")||be.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||be.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=be.resolve(e),i=be.resolve(r,...t.split("/"));if(!np(r,i))throw new Error("Native check cwd escaped the project root");return i}function Mi(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var kE=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function ol(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=$t(r);return kE.test(r)&&(t=!0),i})}function Qa(e,t){if(ap(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return Xa(e,t.cwdRef)}async function sl(e){let{plan:t}=e;ap(e.operationId,"Native check operation ID");let r=Qa(e.projectRoot,t),i=be.join(e.runtimeDir,"logs","checks"),n=be.join(i,`${e.operationId}-${t.id}.log`);if(!np(be.resolve(e.runtimeDir),be.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await bE.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=NE(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=nl(t.executable,t.argv,{cwd:r,env:process.env})}catch(h){o.destroy(),c(h);return}let f=!1,d=null,u=setTimeout(()=>{f=!0,Ya(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);u.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",h=>{d=h,o.write(`
182
- [comet] failed to start check: ${$t(h.message)}
183
- `)}),l.once("close",(h,v)=>{clearTimeout(u);let m=(e.now??(()=>new Date))();o.end(()=>{let p=f||d!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:ol(t.argv),cwdRef:t.cwdRef,status:p?"interrupted":h===0?"passed":"failed",exitCode:h,signal:v,timedOut:f,durationMs:Math.max(0,m.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:m.toISOString(),repeatable:t.repeatable,logRef:be.relative(e.runtimeDir,n).split(be.sep).join("/")})})}),o.once("error",h=>{clearTimeout(u),Ya(l).catch(()=>l.kill("SIGKILL")),c(h)})})}import{randomUUID as PE}from"node:crypto";var op=Symbol("comet.native.trusted-execution-identity"),sp=Symbol("comet.native.trusted-verifier-envelope"),K="skill-coordinated";function cl(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function ll(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){cl(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:K,executionRef:cl(t.executionRef,"Native execution ref"),[op]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:cl(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[sp]:!0})}})}function Za(e){return typeof e=="object"&&e!==null&&e[sp]===!0}function cp(e){return typeof e=="object"&&e!==null&&e[op]===!0}function eo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function qi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function er(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function SE(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=eo(t,`Native Verifier acceptance ${r}`);Fi(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=er(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:er(i.reason,`Native Verifier acceptance ${n} reason`)}})}function EE(e){let t=eo(e,"Native Verifier final result");if(Fi(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:qi(t.iteration,"Native Verifier iteration"),attempt:qi(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:SE(t.acceptance),risks:t.risks,summary:er(t.summary,"Native Verifier summary")}}function xE(e,t){let r=eo(e,`Native Verifier check request ${t}`);if(Fi(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=qi(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:er(r.id,`Native Verifier check request ${t} ID`),name:er(r.name,`Native Verifier check request ${t} name`),executable:er(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:er(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function ul(e){let t=eo(e,"Native Verifier response");if(t.kind==="final-result")return Fi(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:EE(t.result)};if(t.kind==="request-checks"){if(Fi(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:qi(t.iteration,"Native Verifier iteration"),attempt:qi(t.attempt,"Native Verifier attempt"),checks:t.checks.map(xE)}}throw new Error("Native Verifier response kind is invalid")}function lp(e){if(!Za(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=ul(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:u})=>u),c=s.filter((u,h)=>s.indexOf(u)!==h),l=s.filter(u=>!o.includes(u)),f=o.filter(u=>!s.includes(u));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=i.result.acceptance.map(({result:u})=>u);if(i.result.verdict==="pass"&&d.some(u=>u!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var Wi=3,dl=2;function ge(e){return e.state_version+1}function CE(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function fl(e){return e.map(t=>({...t,result:"pending",reason:null}))}function up(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function RE(e){return(e??[]).map(t=>({name:O(t.name),result:t.result,note:t.note?O(t.note):null}))}function Ot(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:O(e.summary),completed_at:e.completedAt}}function dp(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,phase:"build",state_version:ge(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function fp(e){let t=C(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!cp(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=CE(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):fl(t.acceptance),o=(r.now??new Date).toISOString();return C({...t,phase:"verify",state_version:ge(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??PE(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:O(r.summary),addressed_acceptance_ids:i,checks:RE(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>O(s)),known_limits_truncated:!1,review:{status:"passed",summary:O(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function hp(e){let t=C(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return C({...t,state_version:ge(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function AE(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function _E(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===K?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:O(e.response.result.summary),risks:e.response.result.risks.map(t=>O(t)),risks_truncated:!1,completed_at:e.completedAt}}function pp(e){let t=C(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=up(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=lp({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(m=>[m.id,m])),o=t.acceptance.map(m=>{let p=a.get(m.id);return p?{...m,result:p.result,reason:O(p.reason)}:m}),s=o.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),c=_E({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let y=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:C({...y,state_version:ge(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:fl(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let m=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),p=t.builder_handoff.identity_provider===K;return{response:i,state:C({...m,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:ge(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:O("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...m,status:"await-user",state_version:ge(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:O(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=AE(t,s),d=l>=e.maxVerifyFailures,u=f>=3,h=d||u,v=Ne({...t,acceptance:o,verification:c},Ot({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...v,phase:h?"verify":"build",status:h?"await-user":"active",state_version:ge(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:h?[{owner:"user",reason:O(d?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:O("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:h?"await-user":"repairing",iteration:h?t.loop.iteration:t.loop.iteration+1,attempt:h?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,execution_failure_count:0,previous_unresolved_ids:s,next_action:h?"await-user":"repair-failed-acceptance"}})}}function mp(e){let t=C(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==K||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return C({...t,phase:"archive",status:"active",state_version:ge(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function vp(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==K||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=up(t),n=Ne(t,Ot({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return C({...n,status:"await-user",state_version:ge(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:O(e.summary),risks:[O("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:O("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function gp(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=O(e.summary),n=Ne(t,Ot({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return C({...n,phase:"archive",status:"active",state_version:ge(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:O(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function wp(e){let t=C(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:r})=>r==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return C({...t,status:"active",state_version:ge(t),verification_result:"pending",verification_report:null,verification:null,acceptance:t.acceptance.map(r=>r.result==="failed"||r.result==="blocked"?{...r,result:"pending",reason:null}:r),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function yp(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Wi,a=Ne(t,Ot({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return C({...a,status:n?"blocked":"active",state_version:ge(t),blockers:n?[{owner:"runtime",reason:O(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Np(e){let t=C(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:r})=>r==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return C({...t,status:"active",state_version:ge(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function zi(e){let t=C(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Ne(t,Ot({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?fl(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return C({...i,phase:"build",status:"active",state_version:ge(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as kp}from"node:fs";import Ji from"node:path";function to(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ro(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 et(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 bp(e,t){return e===null?null:et(e,t)}function no(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 IE(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 TE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function io(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=et(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function pl(e,t){let r=et(e,t);if(!Ji.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ji.resolve(r)}function jE(e,t){let r=`Native local checks[${t}]`,i=to(e,r);if(ro(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),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((l,f)=>et(l,`${r}.argv[${f}]`,!0)),a=io(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=no(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:et(i.id,`${r}.id`),name:et(i.name,`${r}.name`),operationId:et(i.operationId,`${r}.operationId`),status:a,repeatable:TE(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:no(i.executionCount,`${r}.executionCount`),argv:n,cwd:pl(i.cwd,`${r}.cwd`),exitCode:IE(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:et(i.log,`${r}.log`)}}function ml(e){let t="Native local execution state",r=to(e,t);if(ro(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Pi)throw new Error(`Native local execution schema must be ${Pi}`);let i=to(r.workspace,"Native local workspace");ro(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=to(r.execution,"Native local execution");ro(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"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:et(o.operationId,"Native local execution.operationId"),stage:io(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:io(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:bp(o.executionId,"Native local execution.executionId"),status:io(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:no(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(jE);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:Pi,change:et(r.change,"Native local change"),basedOnStateVersion:no(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:pl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:pl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:bp(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function oe(e){return ml({schema:Pi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ji.resolve(e.projectRoot),worktreeRoot:Ji.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function tt(e){let t;try{t=await kp.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 ml(r)}async function L(e,t,r={}){let i=ml(t);await kp.mkdir(Ji.dirname(e),{recursive:!0}),await me(e,i,r)}async function vl(e){let t=null,r=null;try{t=await tt(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=oe(e);return await L(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as $E}from"node:fs";function Ht(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function dt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function OE(e){return e.archived?Be(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Be(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Be(e.language,"Verification passed; ready to archive","验收通过,可归档"):Be(e.language,"Verification passed","验收通过")}function HE(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Be(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?OE(e):e.verification_result==="blocked"?Be(t,"Blocked","已阻塞"):e.verification_result==="fail"?Be(t,"Failed","未通过"):Be(t,"Pending","待处理")}function DE(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===K?K:"host-attested"),r=t===K&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function BE(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Pc(r,d),n=(d,u)=>Be(r,d,u),a=e.acceptance.map(d=>`| ${dt(d.id)} | ${dt(d.result)} | ${dt(d.source)} | ${dt(d.text)} | ${dt(Ht(d.reason))} |`).join(`
185
- `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let u=d.argv_display.map(Ht).join(" ");return`| ${dt(Ht(d.name))} | ${dt(u||"—")} | ${dt(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
186
- `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Ht(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
187
- `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Ht(d)}`).join(`
188
- `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${dt(Ht(d.summary))} | ${d.completed_at} |`)].join(`
180
+ `;return await Li.appendFile(o,`${c}${i}
181
+ `,"utf8"),!0}function BS(e,t,r){let i=ae.resolve(e,r??ae.join(".worktrees",t)),n=ae.resolve(e,_(e,["rev-parse","--git-common-dir"]));if(Fp(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Jt(e).some(a=>Gc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function LS(e){try{throw await Li.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Mp(e){try{return await Li.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Uc(e){let t=ae.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=q(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await jt(t,e.sourceConfig?.native.artifact_root??"docs");return Zf([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=q(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;ec(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(ec(t,o),!vr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!st(t))throw new Error("Native branch isolation requires a clean current working directory");if(vr(t,n))throw new Error(`Native change branch already exists: ${n}`);_(t,["switch","-c",n,o]),p=!0}let v;try{v=await Wa(t,e.sourceConfig)}catch(m){throw new Ot(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?ae.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Gc(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Wa(t,e.sourceConfig)}catch(m){throw new Ot(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=na(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await Mp(c.root)){let p=e.worktreePath?ae.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Gc(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Wa(c.root,e.sourceConfig)}catch(m){throw new Ot(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await Mp(c.root)&&(_(i.primaryWorktreeRoot,["worktree","prune"]),s=na(i.primaryWorktreeRoot));let l=vr(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=BS(i.primaryWorktreeRoot,e.name,e.worktreePath);await LS(f);let d=await DS(i.primaryWorktreeRoot,f),u={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{_(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),u.createdBranch=!l,u.createdWorktree=!0,u.configInitialized=await Wa(f,e.sourceConfig)}catch(p){throw new Ot(`Native worktree preparation is incomplete: ${p.message}`,u,{cause:p})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:u}})}var Kc="comet.native.supervisor.v2",MS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Wp(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`}async function zp(e){let t=Zt.join(".worktrees",`${e.parent}-integration`);return Uc({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Wp(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function FS(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Uc({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Zt.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function qS(e,t){return Zt.join(De(e,t),"supervisor")}function za(e,t){return Zt.join(qS(e,t),"state.json")}function Jp(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!==Kc)throw new Error(`Native Supervisor state schema must be ${Kc}`);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(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Ht(t.integration.targetCommit,"Native Supervisor target commit"),Ht(t.integration.headCommit,"Native Supervisor integration head commit"),!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.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&&Ht(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(Ht(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.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 ie(e,t){try{let r=await qp.readFile(za(e,t),"utf8"),i=JSON.parse(r);return Jp(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function oe(e,t){Jp(t),await qp.mkdir(e.changesRuntimeDir,{recursive:!0}),await ve(za(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Ht(e,t){if(!MS.test(e))throw new Error(`${t} must be a Git commit`)}function Ze(e){return structuredClone(e)}function ft(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function WS(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function zS(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Yc(e){Ht(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}));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:Kc,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}}}async function Ja(e){let t=Wp(e.parent),r=gr(e.paths.projectRoot,t);if(!r)return null;let i=gr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Jt(e.paths.projectRoot).map(o=>Zt.resolve(o)).find(o=>q(o).currentBranch===t);if(!n)return null;let a=Yc({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 ft(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Gp(e){let t=Ze(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function Xc(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ze(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);WS(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,ft(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function JS(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function Up(e,t){let r=JS(e,t),i=Ze(e);return ft(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function GS(e,t,r){let i=q(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!st(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=_(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return _(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return _(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(_(e,["merge","--ff-only",r]),_(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function US(e){if(!st(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=_(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Zt.resolve(t)!==Zt.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=_(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return _(e.integration.worktree,["rev-parse","HEAD"])}function KS(e,t,r){let i=q(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!st(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(_(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function Qc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,ft(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Ga(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,ft(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function Kp(e){return C(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await ie(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await ge(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let d;try{d=await FS({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?KS(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):GS(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let v=Ze(o),m=v.children.find(({name:h})=>h===l.name);m&&(m.blocker=p.message,ft(v,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let u=Xc(o,{role:f?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:VS()});o=u.state,s.push(u.task)}return(s.length>0||c)&&await oe(e.paths,o),{state:o,tasks:s}})}function Yp(e,t){Ht(t.candidateCommit,"Native Supervisor candidate commit");let r=Ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,ft(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Xp(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),ft(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function YS(e,t){Ht(t.integrationCommit,"Native Supervisor integration commit");let r=Ze(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,ft(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function Qp(e){return C(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await ie(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=zS(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=US(r);if(a!==r.integration.headCommit){let c=(()=>{try{return _(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return _(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{_(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{_(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=_(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=YS(r,{name:e.name,integrationCommit:o,checks:e.checks});return await oe(e.paths,s),s})}function Zp(e,t){if(Ht(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ze(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function eh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var th="children.yaml",Vi="comet.native.children.v1",Ir="comet.native.children.v2",lh=Ir,XS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rh=new Set(["schema","children"]),QS=new Set(["schema","acceptance_index","children"]),ZS=new Set(["name","depends_on","covers"]),eE=new Set(["name","summary","depends_on"]),tE=new Set(["name","depends_on","covers"]);function Ka(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ua(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 ih(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 Zc(e,t){let r=_e.normalize(_e.resolve(e)),i=_e.normalize(_e.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function rE(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 nh(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 iE(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===lh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=a.filter(c=>!n.includes(c));let o=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),f=e.acceptance_index[c];l&&f&&(f.source!==l.source||f.text!==l.text)&&i.mismatched.push(c)}let s=new Set(a);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return i.uncovered=a.filter(c=>!ah(e.children,c)),oh(i)?i:null}if(e.schema===Vi&&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=>!ah(e.children,a)),oh(i)?i:null}return null}function ah(e,t){return e.some(r=>r.covers.includes(t))}function oh(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Mi(e){let t=new Set(e.acceptance.filter(({source:r})=>r===e.brief).map(({id:r})=>r));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let r=[...e.history].reverse().find(({outcome:i})=>i==="fail");for(let i of r?.unresolved_ids??[])t.add(i)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function nE(e){let t=Ka(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=Ka(n,`Native children acceptance_index.${i}`);if(Ua(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 aE(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=Object.keys(e),a=i.filter(c=>!(c in e)),o=n.filter(c=>!i.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of i){let l=s.get(c);if(!l)continue;let f=e[c];if(f.source!==l.source||f.text!==l.text){let d=["source","text"].filter(u=>f[u]!==l[u]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function oE(e,t,r={}){let i=(0,el.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Ka(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Vi&&a!==Ir)throw Ua(n,rh,"Native children contract"),new Error(`Native children schema must be ${Vi} or ${Ir}`);let o=a===Vi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ua(n,o==="indexed-v2"?QS:rh,"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((u,p)=>{let v=Ka(u,`Native child ${p}`);if(Ua(v,o==="indexed-v2"?tE:o==="summary-v2"?eE:ZS,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!XS.test(v.name))throw new Error(`Native child ${p} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:ih(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?ih(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:u})=>u);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let u of c){let p=u.depends_on.filter(v=>!f.has(v));if(p.length>0)throw new Error(`Native child ${u.name} depends on unknown child: ${p.join(", ")}`)}rE(c);let d=r.policy==="advisory";if(a===lh){if(o==="indexed-v2"){let u=nE(n.acceptance_index);d||aE(u,t,r);let p=Object.keys(u);return d||nh(c,p,p),{schema:Ir,acceptance_index:u,children:c}}return{schema:Ir,children:c}}return t&&!d&&nh(c,t),{schema:Vi,children:c}}async function Fi(e){let t=_e.join(e.changeDir,th);try{await ch.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await U({root:e.changeDir,ref:th}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=oE(r.text,e.acceptanceIds,n);return{contract:a,size:r.size,drift:i?iE(a,e.acceptanceIds,e.validation??{}):null}}function sE(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 cE(e){let t=sE(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 tl(e){try{let t=await U({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return cE(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ya(e){return me("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 lE(e){let t=Jt(e.projectRoot);t.some(i=>Zc(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>_e.resolve(n)))]){let n=await ge(i);n&&r.push({projectRoot:i,paths:await jt(i,n.native.artifact_root),parent:Zc(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function uE(e,t){let r=_e.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Be(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function dE(e,t){let r;try{r=await ch.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=_e.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Be(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function fE(e,t,r){let i=_e.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${_e.sep}`))return null;let n=i.split(_e.sep).join("/");try{let a=(0,el.parseDocument)(_(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:P(a.toJS({mapAsMap:!1}))}catch{return null}}function pE(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 sh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function et(e){let t=_e.join(e.paths.changesDir,e.state.name),r=await tl(t),i=await Fi({changeDir:t,validation:Mi(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{},policy:"advisory"});if(!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 n=Ya({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!i.drift;if(i.contract.schema===Ir){let h=await ie(e.paths,e.state.name);if(!h){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let k=await Ja({paths:e.paths,parent:e.state.name,targetBranch:y,contract:i.contract});k&&(h=k,await oe(e.paths,k))}}if(h){let y=eh(h);return e.state.children_contract_hash!==n||i.drift?{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(k=>({...k,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let w=new Map(i.contract.children.map(y=>[y.name,y])),g=i.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(k=>i.contract.children.filter(({name:S})=>S!==y.name).every(({name:S})=>S!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await lE(e.paths),c=new Set(i.contract.children.map(({name:h})=>h)),l=new Map,f=new Map;for(let h of s){let w=h.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await dE(h,c)){let y={...g,source:h,committedState:fE(h,g.file,w)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await uE(h,g);y&&f.set(g,[...f.get(g)??[],{source:h,state:y}])}}let d=new Map;for(let h of i.contract.children){let w=(l.get(h.name)??[]).find(({source:k,committedState:S})=>k.parent&&S?.name===h.name&&sh(S,a));if(w){d.set(h.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let g=l.get(h.name)?.[0];if(g){d.set(h.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=f.get(h.name)??[];y.length>1?d.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&d.set(h.name,pE(y[0].state,y[0].source,a))}let u=new Map(i.contract.children.map(h=>[h.name,h])),p=new Map,v=h=>{let w=p.get(h);if(w)return w;let g=u.get(h),k=g.depends_on.map(v).every(({status:X})=>X==="done"),S=d.get(h),E=S?.kind==="active"&&k?g.depends_on.filter(X=>!(l.get(X)??[]).some(({source:te,committedState:O})=>Zc(te.projectRoot,S.projectRoot)&&O?.name===X&&sh(O,a))):[],x,N=S?.message??null;S?.kind==="done"?(x=k?"done":"blocked",k||(N=`Native child ${h} was merged before its dependencies`)):S?.kind==="active"?(x=k&&E.length===0?"active":"blocked",k?E.length>0&&(N=`Native child ${h} does not include merged dependencies: ${E.join(", ")}`):N=`Native child ${h} started before its dependencies merged`):S?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(N="Parent Shape confirmation is required"));let I={name:h,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:x,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:N};return p.set(h,I),I},m=i.contract.children.map(({name:h})=>v(h));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:m.every(({status:h})=>h==="done")}}function er(e,t,r){return e.language==="zh-CN"?r:t}function hE(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:er(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:er(e,"Reply A or B","回复 A 或 B"),agentInstruction:er(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready")return r(er(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 r(er(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return 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:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."};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 n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"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:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,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."}}return r(er(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 il(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Xa(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function uh(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function mE(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function vE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function gE(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function qi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:il({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Xa("summary","--summary"),uh(e.name,e.flag)]}}function rl(e){return[qi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),qi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function K(e,t){let r=vE(t)&&e.coordination_mode===void 0,i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:hE(e,r)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Xa("summary","--summary")],commandAlternatives:[qi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...rl({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:il({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Xa("summary","--summary")],commandAlternatives:[qi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...rl({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Xa("summary","--summary")],commandAlternatives:rl({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...i,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?il({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:r?"await-user":"continue",action:"confirm-shape",commandArgs:gE({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[mE("coordination-mode","--coordination-mode",Na)]:[],uh("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...i,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}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...i,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...i,userCommunication:!a&&o?{...i.userCommunication,agentInstruction:`${i.userCommunication.agentInstruction} ${er(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:i.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[qi({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as px}from"node:crypto";import{promises as Zi}from"node:fs";import hx from"node:path";import{randomUUID as Nl}from"node:crypto";import{promises as Yi}from"node:fs";import ee from"node:path";import{createWriteStream as BE,promises as LE}from"node:fs";import ke from"node:path";import{spawn as nl}from"node:child_process";import{existsSync as dh}from"node:fs";import tr from"node:path";var wE=new Set([".bat",".cmd",".ps1"]),yE=new Set([".bat",".cmd"]),NE=/[&|<>()^%"!\r\n]/u,bE=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function al(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function kE(e){let t=(al(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function SE(e,t,r){let n=tr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(al(t,"PATH")??"").split(tr.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=tr.win32.extname(e)?[e]:kE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?tr.join(s,c):tr.resolve(r,c)))}function EE(e,t,r){return SE(e,t,r).find(i=>dh(i))??e}function xE(e){let t=al(e,"SystemRoot");if(t){let r=tr.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(dh(r))return r}return"powershell.exe"}function CE(e){if(e.some(t=>NE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function PE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(bE,"utf16le").toString("base64");return nl(xE(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function ol(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return nl(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=EE(e,i,r.cwd),a=tr.win32.extname(n).toLowerCase();return yE.has(a)&&CE(t),wE.has(a)?PE(n,t,{cwd:r.cwd,env:i}):nl(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as RE}from"node:child_process";import sl from"node:path";var AE=1e3,_E=2;async function Qa(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&sl.win32.isAbsolute(r)?sl.win32.resolve(r):"C:\\Windows",n=sl.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(d,u=!1)=>{s||(s=!0,l&&clearTimeout(l),u&&c?.kill("SIGKILL"),o(d))};try{c=RE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",d=>f(d===0)),l=setTimeout(()=>f(!1,!0),AE)}catch{f(!1)}});for(let o=0;o<_E;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var IE=/\b(Bearer|Basic)\s+[^\s"']+/giu,TE=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,jE=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,$E=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,OE=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,HE=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,DE=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Dt(e){return e.replace(IE,"$1 [REDACTED]").replace(TE,"[REDACTED PRIVATE KEY]").replace(jE,"$1[REDACTED]@").replace($E,"[REDACTED TOKEN]").replace(OE,'$1"[REDACTED]"').replace(HE,"$1$2$1$3$4[REDACTED]$4").replace(DE,"$1$2[REDACTED]")}function fh(e,t){let r=ke.relative(e,t);return r===""||!ke.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ke.sep}`)}function ph(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Za(e,t){if(t.length===0||t.includes("\\")||ke.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||ke.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=ke.resolve(e),i=ke.resolve(r,...t.split("/"));if(!fh(r,i))throw new Error("Native check cwd escaped the project root");return i}function Wi(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var VE=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function cl(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Dt(r);return VE.test(r)&&(t=!0),i})}function eo(e,t){if(ph(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return Za(e,t.cwdRef)}async function ll(e){let{plan:t}=e;ph(e.operationId,"Native check operation ID");let r=eo(e.projectRoot,t),i=ke.join(e.runtimeDir,"logs","checks"),n=ke.join(i,`${e.operationId}-${t.id}.log`);if(!fh(ke.resolve(e.runtimeDir),ke.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await LE.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=BE(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=ol(t.executable,t.argv,{cwd:r,env:process.env})}catch(p){o.destroy(),c(p);return}let f=!1,d=null,u=setTimeout(()=>{f=!0,Qa(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);u.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",p=>{d=p,o.write(`
182
+ [comet] failed to start check: ${Dt(p.message)}
183
+ `)}),l.once("close",(p,v)=>{clearTimeout(u);let m=(e.now??(()=>new Date))();o.end(()=>{let h=f||d!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:cl(t.argv),cwdRef:t.cwdRef,status:h?"interrupted":p===0?"passed":"failed",exitCode:p,signal:v,timedOut:f,durationMs:Math.max(0,m.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:m.toISOString(),repeatable:t.repeatable,logRef:ke.relative(e.runtimeDir,n).split(ke.sep).join("/")})})}),o.once("error",p=>{clearTimeout(u),Qa(l).catch(()=>l.kill("SIGKILL")),c(p)})})}import{randomUUID as WE}from"node:crypto";var hh=Symbol("comet.native.trusted-execution-identity"),mh=Symbol("comet.native.trusted-verifier-envelope"),Y="skill-coordinated";function ul(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function dl(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){ul(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Y,executionRef:ul(t.executionRef,"Native execution ref"),[hh]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:ul(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[mh]:!0})}})}function to(e){return typeof e=="object"&&e!==null&&e[mh]===!0}function vh(e){return typeof e=="object"&&e!==null&&e[hh]===!0}function ro(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Ji(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function ME(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=ro(t,`Native Verifier acceptance ${r}`);zi(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=rr(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:rr(i.reason,`Native Verifier acceptance ${n} reason`)}})}function FE(e){let t=ro(e,"Native Verifier final result");if(zi(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Ji(t.iteration,"Native Verifier iteration"),attempt:Ji(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:ME(t.acceptance),risks:t.risks,summary:rr(t.summary,"Native Verifier summary")}}function qE(e,t){let r=ro(e,`Native Verifier check request ${t}`);if(zi(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=Ji(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:rr(r.id,`Native Verifier check request ${t} ID`),name:rr(r.name,`Native Verifier check request ${t} name`),executable:rr(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:rr(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function fl(e){let t=ro(e,"Native Verifier response");if(t.kind==="final-result")return zi(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:FE(t.result)};if(t.kind==="request-checks"){if(zi(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Ji(t.iteration,"Native Verifier iteration"),attempt:Ji(t.attempt,"Native Verifier attempt"),checks:t.checks.map(qE)}}throw new Error("Native Verifier response kind is invalid")}function gh(e){if(!to(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=fl(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:u})=>u),c=s.filter((u,p)=>s.indexOf(u)!==p),l=s.filter(u=>!o.includes(u)),f=o.filter(u=>!s.includes(u));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=i.result.acceptance.map(({result:u})=>u);if(i.result.verdict==="pass"&&d.some(u=>u!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var Gi=3,pl=2;function ye(e){return e.state_version+1}function zE(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function hl(e){return e.map(t=>({...t,result:"pending",reason:null}))}function wh(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function JE(e){return(e??[]).map(t=>({name:H(t.name),result:t.result,note:t.note?H(t.note):null}))}function pt(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:H(e.summary),completed_at:e.completedAt}}function yh(e){let t=P(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return P({...t,phase:"build",state_version:ye(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Nh(e){let t=P(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!vh(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=zE(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):hl(t.acceptance),o=(r.now??new Date).toISOString();return P({...t,phase:"verify",state_version:ye(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??WE(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:H(r.summary),addressed_acceptance_ids:i,checks:JE(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>H(s)),known_limits_truncated:!1,review:{status:"passed",summary:H(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function bh(e){let t=P(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return P({...t,state_version:ye(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function GE(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function UE(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Y?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:H(e.response.result.summary),risks:e.response.result.risks.map(t=>H(t)),risks_truncated:!1,completed_at:e.completedAt}}function kh(e){let t=P(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=wh(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=gh({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:h})=>h==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(h=>[h.id,h])),o=t.acceptance.map(h=>{let w=a.get(h.id);return w?{...h,result:w.result,reason:H(w.reason)}:h}),s=o.filter(({result:h})=>h==="failed"||h==="blocked").map(({id:h})=>h),c=UE({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let g=we({...t,acceptance:o,verification:c},pt({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:P({...g,state_version:ye(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:hl(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let h=we({...t,acceptance:o,verification:c},pt({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),w=t.builder_handoff.identity_provider===Y;return{response:i,state:P({...h,phase:w?"verify":"archive",status:w?"await-user":"active",state_version:ye(t),verification_result:"pass",verification_report:"verification.md",blockers:w?[{owner:"user",reason:H("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:w?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:w?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let h=we({...t,acceptance:o,verification:c},pt({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:P({...h,status:"await-user",state_version:ye(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:H(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=GE(t,s),d=l>=e.maxVerifyFailures,u=f>=3,p=d||u,v=u?"stalled":d?"budget":void 0,m=we({...t,acceptance:o,verification:c},pt({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:P({...m,phase:p?"verify":"build",status:p?"await-user":"active",state_version:ye(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:H(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:H("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function Sh(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Y||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return P({...t,phase:"archive",status:"active",state_version:ye(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Eh(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Y||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=wh(t),n=we(t,pt({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return P({...n,status:"await-user",state_version:ye(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:H(e.summary),risks:[H("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:H("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function xh(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=H(e.summary),n=we(t,pt({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return P({...n,phase:"archive",status:"active",state_version:ye(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:H(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Ch(e,t){let r=P(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=we(r,pt({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return P({...i,status:"active",state_version:ye(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Ph(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Gi,a=we(t,pt({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return P({...a,status:n?"blocked":"active",state_version:ye(t),blockers:n?[{owner:"runtime",reason:H(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Rh(e){let t=P(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:r})=>r==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return P({...t,status:"active",state_version:ye(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Ui(e){let t=P(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=we(t,pt({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?hl(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return P({...i,phase:"build",status:"active",state_version:ye(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as _h}from"node:fs";import Ki from"node:path";function io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function no(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 tt(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 Ah(e,t){return e===null?null:tt(e,t)}function oo(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 KE(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 YE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ao(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function ml(e,t){if(e===null)return null;let r=tt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function vl(e,t){let r=tt(e,t);if(!Ki.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ki.resolve(r)}function XE(e,t){let r=`Native local checks[${t}]`,i=io(e,r);if(no(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),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((l,f)=>tt(l,`${r}.argv[${f}]`,!0)),a=ao(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=ml(i.startedAt,`${r}.startedAt`),s=ml(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=oo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:tt(i.id,`${r}.id`),name:tt(i.name,`${r}.name`),operationId:tt(i.operationId,`${r}.operationId`),status:a,repeatable:YE(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:oo(i.executionCount,`${r}.executionCount`),argv:n,cwd:vl(i.cwd,`${r}.cwd`),exitCode:KE(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:tt(i.log,`${r}.log`)}}function gl(e){let t="Native local execution state",r=io(e,t);if(no(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Ri)throw new Error(`Native local execution schema must be ${Ri}`);let i=io(r.workspace,"Native local workspace");no(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=io(r.execution,"Native local execution");no(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=ml(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:tt(o.operationId,"Native local execution.operationId"),stage:ao(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ao(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ah(o.executionId,"Native local execution.executionId"),status:ao(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:oo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(XE);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:Ri,change:tt(r.change,"Native local change"),basedOnStateVersion:oo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:vl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:vl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ah(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function se(e){return gl({schema:Ri,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ki.resolve(e.projectRoot),worktreeRoot:Ki.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function rt(e){let t;try{t=await _h.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 gl(r)}async function V(e,t,r={}){let i=gl(t);await _h.mkdir(Ki.dirname(e),{recursive:!0}),await ve(e,i,r)}async function wl(e){let t=null,r=null;try{t=await rt(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=se(e);return await V(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as QE}from"node:fs";function Bt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function ht(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function ZE(e){return e.archived?Le(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Le(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Le(e.language,"Verification passed; ready to archive","验收通过,可归档"):Le(e.language,"Verification passed","验收通过")}function ex(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Le(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?ZE(e):e.verification_result==="blocked"?Le(t,"Blocked","已阻塞"):e.verification_result==="fail"?Le(t,"Failed","未通过"):Le(t,"Pending","待处理")}function tx(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Y?Y:"host-attested"),r=t===Y&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function rx(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Rc(r,d),n=(d,u)=>Le(r,d,u),a=e.acceptance.map(d=>`| ${ht(d.id)} | ${ht(d.result)} | ${ht(d.source)} | ${ht(d.text)} | ${ht(Bt(d.reason))} |`).join(`
185
+ `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let u=d.argv_display.map(Bt).join(" ");return`| ${ht(Bt(d.name))} | ${ht(u||"—")} | ${ht(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
186
+ `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Bt(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
187
+ `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Bt(d)}`).join(`
188
+ `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${ht(Bt(d.summary))} | ${d.completed_at} |`)].join(`
189
189
  `),f=t?.finalVerification.layers?`
190
190
  ## ${n("Supervisor evidence layers","Supervisor 分层证据")}
191
191
 
@@ -202,13 +202,13 @@ generated_from_state_version: ${e.state_version}
202
202
 
203
203
  ## ${i("currentResult")}
204
204
 
205
- - ${n("Result","结果")}: **${HE(e)}**
206
- - ${n("Verification status","验证情况")}: **${DE(e)}**
205
+ - ${n("Result","结果")}: **${ex(e)}**
206
+ - ${n("Verification status","验证情况")}: **${tx(e)}**
207
207
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
208
208
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
209
209
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
210
210
  - ${n("Completed","完成时间")}: ${e.verification.completed_at}
211
- - ${n("Summary","摘要")}: ${Ht(e.verification.summary)}
211
+ - ${n("Summary","摘要")}: ${Bt(e.verification.summary)}
212
212
 
213
213
  ## ${i("acceptance")}
214
214
 
@@ -238,17 +238,23 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
238
238
 
239
239
  `:""}## ${i("conclusion")}
240
240
 
241
- ${Ht(e.verification.summary)}
242
- `}function LE(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Sp(e){let t;try{t=await $E.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=LE(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function _r(e){await xe(e.file,BE(e.state,e.supervisor))}var xp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VE="comet-state.yaml",ME="state.json",r$=Pa("en");function tr(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function ue(e,t){if(!xp.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Z.join(e.changesDir,t);if(!se(e.changesDir,r))throw new Error("Native change path escaped");return r}function Fe(e,t){return Z.join(ue(e,t),VE)}function D(e,t){return Z.join(He(e,t),ME)}async function Ui(e,t){try{let r=await Gi.readFile(Fe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Me(e){return F(e).currentBranch}async function j(e,t){return De(Fe(e,t))}async function ke(e){let t=await Ci({file:Fe(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=Z.join(ue(e.paths,t.name),"verification.md");await q(e.paths.nativeRoot,r),await Gi.rm(r,{force:!0})}return t}async function Pp(e){let t=ue(e.paths,e.state.name),r=Z.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Gi.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!xp.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Z.join(t,...s.split("/")),l=await Gi.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=Z.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await Gi.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Cp(e){let t=ue(e.paths,e.state.name),r=await J({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),i=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await J({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}return $a({briefMarkdown:r.text,specs:i})}async function Rp(e){return P(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"confirm-shape"});let r=await Pp({paths:e.paths,state:t}),i=await Cp({paths:e.paths,state:t,specChanges:r}),n=await Li({changeDir:ue(e.paths,t.name),acceptanceIds:i.map(({id:h})=>h),validation:Bi({...t,acceptance:i})});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=await Zc(ue(e.paths,t.name))||n?.contract.schema==="comet.native.children.v2"&&n.contract.children.length>=2,o=e.coordinationMode??t.coordination_mode;if(a&&!n)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(a&&o===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!a&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let s=dp({state:{...t,spec_changes:r},acceptance:i.map(h=>({...h}))});if(delete s.children_contract_hash,delete s.coordination_mode,n){s.children_contract_hash=Ua({acceptance:s.acceptance,children:n.contract}),a&&(s.coordination_mode=o);let h=[...t.history].reverse().find(({outcome:v})=>v==="pass"||v==="fail");if(h?.outcome==="fail"&&h.unresolved_ids.length>0){let v=await Ze({paths:e.paths,state:s}),m=new Set((v?.children??[]).filter(({status:y})=>y!=="done").flatMap(({covers:y})=>y)),p=h.unresolved_ids.filter(y=>!m.has(y));if(p.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${p.join(", ")}`)}}let c=null,l=n?.contract.schema==="comet.native.children.v2"?await re(e.paths,t.name):null,f=null,d=null;if(n?.contract.schema==="comet.native.children.v2"){if(f=t.workspace.target_branch??t.workspace.change_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(d=mr(e.paths.projectRoot,f),!d)throw new Error(`Native Supervisor target branch has no commit: ${f}`);l||(l=await qa({paths:e.paths,parent:t.name,targetBranch:f,contract:n.contract})),l||(c=await Vh({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await ve(e.paths.projectRoot)}))}let u=await ke({paths:e.paths,previous:t,next:s});if(await L(D(e.paths,t.name),oe({portableState:u,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n?.contract.schema==="comet.native.children.v2"&&f&&d){let h=l?Fh({state:l,contract:n.contract}):c?Uc({parent:u.name,targetBranch:f,targetCommit:d,integrationBranch:c.binding.changeBranch,integrationWorktree:c.projectRoot,contract:n.contract}):null;if(!h)throw new Error("Native Supervisor integration state is unavailable");await ae(e.paths,h)}return u})}async function co(e){let t=await Pp(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await Cp({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!yh(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Li({changeDir:ue(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Bi({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Ua({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Dt(e){let t=await co(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Fp({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Ap(e){return P(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await j(e.paths,e.name);if(await Dt({paths:e.paths,state:t}),await Li({changeDir:ue(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Bi(t)})||t.children_contract_hash){let a=await Ze({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=fp({state:t,input:e.input}),n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function lo(e){let t=await j(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await Ze({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function yl(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:Xa(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function _p(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...yl(t,r,i),executionCount:e.executionCount}}function Ip(e,t){let r=Z.relative(Z.resolve(e),Z.resolve(t));if(Z.isAbsolute(r)||r===".."||r.startsWith(`..${Z.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Z.sep).join("/");return Xa(e,i),i}function gl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Mi({id:e.id,name:e.id,executable:r,argv:i,cwdRef:Ip(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function FE(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Ir(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:O(i),argv_display:ol(r.argv.slice(1)).map(n=>O(n)),argv_truncated:!1,cwd_ref:Ip(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:FE(r)}})}function qE(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Ki(e){if(e.local===null||e.local.change!==e.state.name)return oe({portableState:e.state,projectRoot:e.projectRoot,branch:Me(e.projectRoot)});let t=e.local.execution?.operationId??wl();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function Tr(e){try{let t=await tt(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Tp(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function WE(e){let{state:t,local:r,envelope:i}=e;if(!Za(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function zE(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function so(e){let t=await Tr({paths:e.paths,state:e.state}),r=yp({state:e.state,summary:e.summary}),i=await ke({paths:e.paths,previous:e.state,next:r});return await L(D(e.paths,e.state.name),Ki({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Ep(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>gl(i,r)===Mi(t[n]))}async function JE(e){return P(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await j(e.paths,e.name);if(await Dt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=D(e.paths,t.name),i=(await vl({file:r,portableState:t,projectRoot:e.projectRoot,branch:Me(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Ep(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Ir({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=zi({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await ke({paths:e.paths,previous:t,next:c});throw await L(D(e.paths,t.name),oe({portableState:l,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Ep(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=wl(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?_p(s,o,n,e.projectRoot):s?{...s,operationId:n}:yl(o,n,e.projectRoot)})};return await L(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function ao(e){return P(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await j(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await tt(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await L(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function jp(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){Qa(t,c);let l=Mi(c);i.has(l)||(i.add(l),r.push(c))}let n=await JE({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=He(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await ao({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:"running",executionCount:u.executionCount+1,startedAt:l}:u)})});let f=await sl({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await ao({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:u)})})}await ao({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await ao({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await tt(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Ir({local:s,projectRoot:t,supplied:[]})}}async function GE(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=dl)throw new Error(`Native Verifier request-checks exceeded ${dl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let h of r.checks){let v=gl(h,e.projectRoot);n.set(v,h),h.status!=="interrupted"&&i.set(v,h),a.set(h.id,v)}let o=new Map,s=new Map;for(let h of e.response.checks){let v=qE(h);Qa(e.projectRoot,v);let m=Mi(v),p=s.get(v.id);if(p!==void 0&&p!==m)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let y=a.get(v.id);if(y!==void 0&&y!==m)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,m);let g=n.get(m);if(g?.status==="interrupted"&&!g.repeatable)throw new Error(`Native check ${g.id} was interrupted and is not repeatable; user resolution is required`);o.has(m)||o.set(m,v)}let c=[...o.entries()],l=c.filter(([h])=>!i.has(h));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),u={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(h=>{let v=gl(h,e.projectRoot),m=o.get(v);return m&&h.status==="interrupted"?_p(h,m,r.execution.operationId,e.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>yl(h,r.execution.operationId,e.projectRoot))]};return await L(t,u,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:u,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>i.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function oo(e){return P(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await j(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await tt(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await L(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function UE(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await oo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await sl({projectRoot:e.projectRoot,runtimeDir:He(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await oo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await oo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await oo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Ir({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function $p(e){return P(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Dt({paths:e.paths,state:t});let i=(await vl({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:Me(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Ir({local:i,projectRoot:r,supplied:e.checks});let n=hp(t),a=await ke({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=wl();return await L(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Op(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await P(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await j(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Dt({paths:e.paths,state:r});let n=await Tr({paths:e.paths,state:r}),a=WE({state:r,local:n,envelope:e.envelope}),o;try{o=ul(a.payload)}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,h=await so({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${h.loop.execution_failure_count}/${Wi} was recorded`,{cause:d})}let s=zE(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Ir({local:n,projectRoot:i,supplied:e.checks}));let d=pp({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let u=await GE({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:u}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=d}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,h=await so({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${h.loop.execution_failure_count}/${Wi} was recorded`,{cause:d})}let f=await ke({paths:e.paths,previous:r,next:l.state});return await L(D(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?Ki({local:n,state:f,projectRoot:i}):oe({portableState:f,projectRoot:i,branch:Me(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await _r({file:Z.join(ue(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await UE({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await P(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await j(e.paths,e.name);return a.state_version!==t.state.state_version?null:so({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Wi} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Hp(e){return P(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await j(e.paths,e.name),r=await Tr({paths:e.paths,state:t});if(Tp({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return so({paths:e.paths,state:t,summary:e.summary})})}async function Dp(e){return P(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name);await Dt({paths:e.paths,state:t});let r=await Tr({paths:e.paths,state:t}),i=Tp({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Ir({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=vp({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await ke({paths:e.paths,previous:t,next:a});return await L(D(e.paths,t.name),Ki({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await _r({file:Z.join(ue(e.paths,t.name),"verification.md"),state:o}),o})}async function Bp(e){return P(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Dt({paths:e.paths,state:t});let r=mp(t),i=await ke({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await _r({file:Z.join(ue(e.paths,t.name),"verification.md"),state:i}),i})}async function Lp(e){return P(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Dt({paths:e.paths,state:t});let r=gp({state:t,summary:e.summary}),i=await ke({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await _r({file:Z.join(ue(e.paths,t.name),"verification.md"),state:i}),i})}async function Vp(e){return P(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Dt({paths:e.paths,state:t});let r=await Tr({paths:e.paths,state:t}),i=wp(t),n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),Ki({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Mp(e){return P(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await j(e.paths,e.name);tr({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await Tr({paths:e.paths,state:t}),i=Np(t),n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),Ki({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function uo(e){return P(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await j(e.paths,e.name);if(tr({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=zi({state:t,reason:e.reason}),i=await ke({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function fo(e){return P(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await j(e.paths,e.name);if(tr({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Fp({paths:e.paths,state:t,reason:e.reason})})}async function Fp(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Ne(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:O(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete i.children_contract_hash;let n=await ke({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Me(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function ho(e){if(e.state.verification===null)return"not-applicable";let t=Z.join(ue(e.paths,e.state.name),"verification.md");return await Sp({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await _r({file:t,state:e.state}),"rebuilt")}var qp=["evidence.md","repair.md","archive.md","checkpoint.md"],XE="verification.md";async function QE(e,t){let r=await Ch(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Wp(e,t){await Yi.mkdir(e.transactionsDir,{recursive:!0}),await me(Da(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function zp(e,t,r={}){let i=r.removeVerificationReport===!1?qp:[...qp,XE];await Promise.all([Yi.rm(He(e,t),{recursive:!0,force:!0}),Yi.rm(vc(e,t),{recursive:!0,force:!0}),...i.map(n=>Yi.rm(YE.join(Xe(e,t),n),{force:!0}))])}async function Jp(e,t){await L(D(e,t.name),oe({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Gp(e,t){try{let r=await Ai(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Up(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=F(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function ZE(e){let t=Xe(e.paths,e.state.name),r=await J({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await J({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return $a({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Kp(e,t){let r=await uh(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Yp(e){return P(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await QE(e.paths,e.name),r=await Ui(e.paths,e.name)?await De(Fe(e.paths,e.name)):null;if(!t&&r)return await zp(e.paths,e.name,{removeVerificationReport:!1}),await Jp(e.paths,r),r;let i=null,n=null;for(t||(i=await Kp(e.paths,e.name),n=await Gp(e.paths,e.name),Up(e.paths,n),t={schema:Oa,id:KE(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Wp(e.paths,t));;){let a=bh(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Kp(e.paths,e.name),n??=await Gp(e.paths,e.name),Up(e.paths,n),r=Nh({state:i,acceptance:await ZE({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await ka(Fe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await zp(e.paths,e.name):a.action==="commit-transaction"&&(r??=await De(Fe(e.paths,e.name)),await Jp(e.paths,r)),t={...t,status:a.nextStatus},await Wp(e.paths,t)}return await Yi.rm(Da(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??De(Fe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Xp}from"node:fs";import Qp from"node:path";function ex(e,t){let r=F(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function tx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function rx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Ne(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:O(t),completed_at:i});return C({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?tx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function ix(e){try{let t=await tt(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Nl(e){return P(e.paths,`recover portable change ${e.name}`,async()=>{let t=await j(e.paths,e.name);if(t.status==="done")return await ho({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=ex(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=D(e.paths,e.name),n=await ix(i),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await L(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await ho({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=zi({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Ci({file:Fe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await Xp.rm(Qp.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await L(i,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=c||l;if(f){let u=rx(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await Ci({file:Fe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let d=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await Xp.mkdir(Qp.dirname(D(e.paths,t.name)),{recursive:!0}),await L(i,d,{containedRoot:e.paths.runtimeDir}),await ho({paths:e.paths,state:t}),{state:t,local:d,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}function nx(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function rt(e){let t=e.acceptance.reduce((r,i)=>({...r,[i.result]:r[i.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:t,unresolved_acceptance_ids:e.acceptance.filter(({result:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:nx(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}import{randomUUID as nm}from"node:crypto";import{promises as Zp}from"node:fs";import Qi from"node:path";function jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function de(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function H(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function kl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>H(r,`${t}[${i}]`))}function ax(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=jr(t,`Native Builder check ${r}`);if(de(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:H(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function ox(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=jr(t,`Native Runtime check ${r}`);if(de(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:H(i.id,`Native Runtime check ${r} id`),name:H(i.name,`Native Runtime check ${r} name`),executable:H(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:H(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function em(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:H(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function sx(e){let t=jr(e,"Native Supervisor evidence");return de(t,["summary","checks"],"Native Supervisor evidence"),{summary:H(t.summary,"Native Supervisor evidence summary"),checks:kl(t.checks,"Native Supervisor evidence checks")}}function cx(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=jr(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:H(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function lx(e){let t=jr(e,"Native Runner input");if(t.kind==="builder-handoff"){de(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=jr(t.review,"Native Builder review");if(de(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:H(t.summary,"Native Builder summary"),addressed_acceptance_ids:kl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:ax(t.checks),known_limits:kl(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:H(r.summary,"Native Builder review summary"),reviewer_execution_ref:H(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return de(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:ox(t.checks)};if(t.kind==="verifier-response")return de(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return de(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:H(t.summary,"Native Verifier execution error summary"),...em(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return de(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:H(t.summary,"Native unavailable Verifier summary"),...em(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return de(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),candidateCommit:H(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return de(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),reason:H(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return de(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return de(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),reason:H(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(de(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:H(t.child,"Native Supervisor child"),runId:H(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:sx(t.evidence)}}if(t.kind==="supervisor-integrate")return de(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:H(t.child,"Native Supervisor child"),checks:cx(t.checks)};throw new Error("Native Runner input kind is invalid")}async function am(e,t){let r=Qi.resolve(t,e),i=await Zp.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Zp.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return lx(n)}function tm(e){return`${K}:${e}:${nm()}`}function rm(e,t,r,i){if(Qi.resolve(A(e.projectRoot,["rev-parse","--show-toplevel"]))!==Qi.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(A(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!at(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(A(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function ux(e,t){let r=F(e.projectRoot),i=Qi.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Qi.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=A(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!at(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Xi(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==K)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function im(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Xi(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=r.acceptance.filter(({result:c})=>c==="pending").map(({id:c})=>c);return{coordination:K,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:ue(t,r.name),supervisorStateRef:a?Fa(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:c,operation:l,source:f})=>({capability:c,operation:l,ref:f})),acceptanceCount:r.acceptance.length,scopeIds:s,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(c=>({...c}))}}async function bl(e){Xi(e.state);let t=await tt(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function om(e){let t=await re(e.paths,e.name),r=e.input,i=t?await j(e.paths,e.name):null,n=t!==null&&i?.phase==="verify"&&t.children.every(({status:u})=>u==="integrated"||u==="archived"),a=t!==null&&i?.phase==="build"&&t.children.every(({status:u})=>u==="integrated"||u==="archived");if(t&&r.kind==="supervisor-builder-result")return P(e.paths,`apply Native Supervisor Builder result ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:g})=>g===r.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${r.child}`);try{rm(h.task,r.candidateCommit,"builder",`comet/supervisor/${u.parent}/${r.child}`)}catch(g){throw await ae(e.paths,Wa(u,{child:r.child,runId:r.runId,reason:g.message})),g}let v=h.task.projectRoot,m=zh(u,r),p=Kc(m,{role:"verifier",child:r.child,projectRoot:v,runId:nm()});await ae(e.paths,p.state);let y=await j(e.paths,e.name);return{state:y,supervisorTask:p.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(y)}});if(t&&r.kind==="supervisor-builder-failure")return P(e.paths,`cancel Native Supervisor Builder task ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:p})=>p===r.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${r.child}`);let v=Yc(u,{child:r.child,runId:r.runId,reason:r.reason});await ae(e.paths,v);let m=await j(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}});if(t&&r.kind==="supervisor-reconnect")return P(e.paths,`reconnect Native Supervisor task ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:p})=>p===r.child)?.task;if(!h||h.runId!==r.runId)throw new Error(`Native Supervisor task runId is not current for ${r.child}`);try{ux(h,`comet/supervisor/${u.parent}/${r.child}`)}catch(p){throw await ae(e.paths,Wa(u,{child:r.child,runId:r.runId,reason:p.message})),p}let v=qh(u,{child:r.child,runId:r.runId});await ae(e.paths,v.state);let m=await j(e.paths,e.name);return{state:m,supervisorState:v.state,supervisorTask:v.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}});if(t&&r.kind==="supervisor-cancel")return P(e.paths,`cancel Native Supervisor task ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=Yc(u,{child:r.child,runId:r.runId,reason:r.reason});await ae(e.paths,h);let v=await j(e.paths,e.name);return{state:v,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(v)}});if(t&&r.kind==="supervisor-verifier-result")return P(e.paths,`apply Native Supervisor Verifier result ${r.child}`,async()=>{let u=await re(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=u.children.find(({name:p})=>p===r.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${r.child}`);try{rm(h.task,h.candidateCommit,"verifier",`comet/supervisor/${u.parent}/${r.child}`)}catch(p){throw await ae(e.paths,Wa(u,{child:r.child,runId:r.runId,reason:p.message})),p}let v=Jh(u,r);await ae(e.paths,v);let m=await j(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}});if(t&&r.kind==="supervisor-integrate"){let u=await Gh({paths:e.paths,state:t,name:r.child,checks:r.checks}),h=await lo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=h.state;return{state:v,supervisorState:u,supervisorTask:null,checks:r.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:U(v)}}if(t&&(r.kind==="builder-handoff"||r.kind==="dispatch-verifier"||r.kind==="verifier-response"||r.kind==="verifier-execution-error"||r.kind==="verifier-unavailable"||r.kind==="supervisor-builder-result"||r.kind==="supervisor-builder-failure"||r.kind==="supervisor-reconnect"||r.kind==="supervisor-cancel"||r.kind==="supervisor-verifier-result")&&!n&&!(r.kind==="builder-handoff"&&a))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(r.kind==="builder-handoff"){let h=ll().captureExecutionIdentity({identityProvider:K,executionRef:tm("builder")}),v=await Ap({paths:e.paths,name:e.name,input:{identity:h,summary:r.summary,addressedAcceptanceIds:r.addressed_acceptance_ids,checks:r.checks,knownLimits:r.known_limits,review:{status:r.review.status,summary:r.review.summary,reviewerExecutionRef:r.review.reviewer_execution_ref}}});return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(v)}}if(r.kind==="dispatch-verifier"){if(n&&r.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let u=await j(e.paths,e.name);if(u.builder_handoff!==null&&u.builder_handoff.identity_provider!==K){let y=await uo({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:y,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(y)}}Xi(u);let v=(u.loop.next_action==="run-final-full-verification"&&u.verification?.verdict==="pass"&&u.verification.checks.every(({status:y})=>y==="passed")?u.verification.checks:null)??(await jp({paths:e.paths,name:e.name,plans:r.checks,...n&&t?{projectRoot:t.integration.worktree}:{}})).checks,m=tm("verifier"),p=await $p({paths:e.paths,name:e.name,checks:v,verifierExecutionId:m,...n&&t?{projectRoot:t.integration.worktree}:{}});return{state:p,checks:v,requestChecks:null,verifierDispatch:im({paths:e.paths,state:p,checks:v,verifierExecutionRef:m,supervisor:n?t:null}),continuation:U(p)}}if(r.kind==="verifier-execution-error"){let u=await j(e.paths,e.name);Xi(u),await bl({paths:e.paths,state:u});let h=await Hp({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(h)}}if(r.kind==="verifier-unavailable"){let u=await Dp({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:u,checks:u.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:U(u)}}if(r.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let o=await j(e.paths,e.name),s=Xi(o),c=await bl({paths:e.paths,state:o}),l=ll(),f=l.captureExecutionIdentity({identityProvider:K,executionRef:c}),d=await Op({paths:e.paths,name:e.name,envelope:l.envelopeVerifierResponse({candidateId:s.candidate_id,identity:f,payload:r.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...n&&t?{projectRoot:t.integration.worktree}:{}});if(n&&d.response.kind==="final-result"){if(d.state.verification_result==="pass"&&(d.checks.length===0||d.checks.some(({status:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let u=await re(e.paths,e.name);if(!u)throw new Error("Native Supervisor state disappeared during verification");let h=A(u.integration.worktree,["rev-parse","HEAD"]),v=d.response.result.summary,m=u.children.every(({status:g,verification:w})=>(g==="integrated"||g==="archived")&&w!==null),p=d.checks.length>0&&d.checks.every(({status:g})=>g==="passed"),y=Uh(u,{status:d.state.verification_result==="pass"?"passed":d.state.verification_result==="blocked"?"incomplete":"failed",summary:v,headCommit:h,layers:{childVerification:m?"complete":"incomplete",parentIntegration:p?"complete":"incomplete",parentChecks:d.checks.map(({name:g})=>g.text),notRerun:u.children.flatMap(({verification:g})=>g?.checks??[]),incomplete:d.checks.filter(({status:g})=>g!=="passed").map(({name:g})=>g.text)}});return await ae(e.paths,y),{...d,supervisorState:y,verifierDispatch:null,continuation:U(d.state)}}return{...d,verifierDispatch:d.requestChecks===null?null:im({paths:e.paths,state:d.state,checks:d.checks,verifierExecutionRef:await bl({paths:e.paths,state:d.state}),supervisor:n?t:null}),continuation:U(d.state)}}import en from"path";import{realpathSync as Kx}from"fs";var fx=["outcome","scope","nonGoals","acceptanceExamples"],oO=[...fx,"constraints","decisions","openQuestions","verificationExpectations"];var hx=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var sm=1024*1024;var lm="scoped-text-safety",px=1,mx=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var vx="comet.native.checker-policy.v1";var kO=pe(vx,{policy:lm,version:px,limits:mx,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var gx=["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"],SO=new Set(gx);var Nx=sm,VO=3*Nx;var um={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:[]},kx=Re("comet-native-runtime:v3:scope-reopen"),h0=[{skillVersion:"3",skillHash:Re("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Re("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Re("comet-native-runtime:v1")}];var fm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],G0=new Set(fm),Ax=new Set([...fm,"minimum_runtime_version","revision"]),U0=new Set([...Ax,"operation"]),K0=512*1024,_x=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Y0=new Set([..._x,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var tH={maxAcceptanceCriteria:ja.maxCriteria};var oH={maxSpecs:64,maxFileBytes:ia,maxTotalBytes:4*1024*1024};import{execFile as Lx}from"node:child_process";import{promisify as Vx}from"node:util";var vH={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var DH=512*1024;var Zi=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var oD=64*1024;var sD=3600*1e3;var cD=Vx(Lx);var po=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}};var GD={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var iB=16*1024*1024,nB=256*1024,aB=16*1024;var dB=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var pB=16*1024;var PB=16*1024;var vL=16*1024*1024,mo=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"},vo=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"};var mm=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],El=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:mm,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, 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 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> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
241
+ ${Bt(e.verification.summary)}
242
+ `}function ix(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Ih(e){let t;try{t=await QE.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=ix(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Tr(e){await Ce(e.file,rx(e.state,e.supervisor))}var jh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nx="comet-state.yaml",ax="state.json",T$=Aa("en");function ir(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function de(e,t){if(!jh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ee.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}function qe(e,t){return ee.join(de(e,t),nx)}function B(e,t){return ee.join(De(e,t),ax)}async function Xi(e,t){try{let r=await Yi.readFile(qe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Fe(e){return q(e).currentBranch}async function $(e,t){return Be(qe(e,t))}async function Se(e){let t=await Ai({file:qe(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ee.join(de(e.paths,t.name),"verification.md");await W(e.paths.nativeRoot,r),await Yi.rm(r,{force:!0})}return t}async function $h(e){let t=de(e.paths,e.state.name),r=ee.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Yi.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!jh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=ee.join(t,...s.split("/")),l=await Yi.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=ee.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await Yi.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Oh(e){let t=de(e.paths,e.state.name),r=await U({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),i=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await U({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}return Da({briefMarkdown:r.text,specs:i})}async function Hh(e){return C(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"confirm-shape"});let r=await $h({paths:e.paths,state:t}),i=await Oh({paths:e.paths,state:t,specChanges:r}),n=await Fi({changeDir:de(e.paths,t.name),acceptanceIds:i.map(({id:p})=>p),validation:Mi({...t,acceptance:i})});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=await tl(de(e.paths,t.name))||n?.contract.schema==="comet.native.children.v2"&&n.contract.children.length>=2,o=e.coordinationMode??t.coordination_mode;if(a&&!n)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(a&&o===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!a&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let s=yh({state:{...t,spec_changes:r},acceptance:i.map(p=>({...p}))});if(delete s.children_contract_hash,delete s.coordination_mode,n){s.children_contract_hash=Ya({acceptance:s.acceptance,children:n.contract}),a&&(s.coordination_mode=o);let p=[...t.history].reverse().find(({outcome:v})=>v==="pass"||v==="fail");if(p?.outcome==="fail"&&p.unresolved_ids.length>0){let v=await et({paths:e.paths,state:s}),m=new Set((v?.children??[]).filter(({status:w})=>w!=="done").flatMap(({covers:w})=>w)),h=p.unresolved_ids.filter(w=>!m.has(w));if(h.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${h.join(", ")}`)}}let c=null,l=n?.contract.schema==="comet.native.children.v2"?await ie(e.paths,t.name):null,f=null,d=null;if(n?.contract.schema==="comet.native.children.v2"){if(f=t.workspace.target_branch??t.workspace.change_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(d=gr(e.paths.projectRoot,f),!d)throw new Error(`Native Supervisor target branch has no commit: ${f}`);l||(l=await Ja({paths:e.paths,parent:t.name,targetBranch:f,contract:n.contract})),l||(c=await zp({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await ge(e.paths.projectRoot)}))}let u=await Se({paths:e.paths,previous:t,next:s});if(await V(B(e.paths,t.name),se({portableState:u,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n?.contract.schema==="comet.native.children.v2"&&f&&d){let p=l?Gp({state:l,contract:n.contract}):c?Yc({parent:u.name,targetBranch:f,targetCommit:d,integrationBranch:c.binding.changeBranch,integrationWorktree:c.projectRoot,contract:n.contract}):null;if(!p)throw new Error("Native Supervisor integration state is unavailable");await oe(e.paths,p)}return u})}async function uo(e){let t=await $h(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await Oh({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Ep(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Fi({changeDir:de(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Mi({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Ya({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Lt(e){let t=await uo(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Yh({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Dh(e){return C(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Lt({paths:e.paths,state:t}),await Fi({changeDir:de(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Mi(t)})||t.children_contract_hash){let a=await et({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Nh({state:t,input:e.input}),n=await Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),se({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function fo(e){let t=await $(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await et({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function bl(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:Za(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function Bh(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...bl(t,r,i),executionCount:e.executionCount}}function Lh(e,t){let r=ee.relative(ee.resolve(e),ee.resolve(t));if(ee.isAbsolute(r)||r===".."||r.startsWith(`..${ee.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(ee.sep).join("/");return Za(e,i),i}function yl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Wi({id:e.id,name:e.id,executable:r,argv:i,cwdRef:Lh(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function ox(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function jr(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:H(i),argv_display:cl(r.argv.slice(1)).map(n=>H(n)),argv_truncated:!1,cwd_ref:Lh(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:ox(r)}})}function sx(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Qi(e){if(e.local===null||e.local.change!==e.state.name)return se({portableState:e.state,projectRoot:e.projectRoot,branch:Fe(e.projectRoot)});let t=e.local.execution?.operationId??Nl();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function $r(e){try{let t=await rt(B(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Vh(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function cx(e){let{state:t,local:r,envelope:i}=e;if(!to(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function lx(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function lo(e){let t=await $r({paths:e.paths,state:e.state}),r=Ph({state:e.state,summary:e.summary}),i=await Se({paths:e.paths,previous:e.state,next:r});return await V(B(e.paths,e.state.name),Qi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Th(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>yl(i,r)===Wi(t[n]))}async function ux(e){return C(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Lt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=B(e.paths,t.name),i=(await wl({file:r,portableState:t,projectRoot:e.projectRoot,branch:Fe(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Th(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:jr({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=Ui({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await Se({paths:e.paths,previous:t,next:c});throw await V(B(e.paths,t.name),se({portableState:l,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Th(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Nl(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?Bh(s,o,n,e.projectRoot):s?{...s,operationId:n}:bl(o,n,e.projectRoot)})};return await V(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function so(e){return C(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await $(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=B(e.paths,t.name),i=await rt(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await V(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function Mh(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){eo(t,c);let l=Wi(c);i.has(l)||(i.add(l),r.push(c))}let n=await ux({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=De(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await so({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:"running",executionCount:u.executionCount+1,startedAt:l}:u)})});let f=await ll({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await so({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:u)})})}await so({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await so({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await rt(B(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:jr({local:s,projectRoot:t,supplied:[]})}}async function dx(e){let t=B(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=pl)throw new Error(`Native Verifier request-checks exceeded ${pl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let v=yl(p,e.projectRoot);n.set(v,p),p.status!=="interrupted"&&i.set(v,p),a.set(p.id,v)}let o=new Map,s=new Map;for(let p of e.response.checks){let v=sx(p);eo(e.projectRoot,v);let m=Wi(v),h=s.get(v.id);if(h!==void 0&&h!==m)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let w=a.get(v.id);if(w!==void 0&&w!==m)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,m);let g=n.get(m);if(g?.status==="interrupted"&&!g.repeatable)throw new Error(`Native check ${g.id} was interrupted and is not repeatable; user resolution is required`);o.has(m)||o.set(m,v)}let c=[...o.entries()],l=c.filter(([p])=>!i.has(p));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,d=new Map(c.map(([,p])=>[p.id,p.name])),u={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(p=>{let v=yl(p,e.projectRoot),m=o.get(v);return m&&p.status==="interrupted"?Bh(p,m,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>bl(p,r.execution.operationId,e.projectRoot))]};return await V(t,u,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:u,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,p])=>p),requestedNames:d,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function co(e){return C(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await $(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=B(e.paths,t.name),i=await rt(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await V(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function fx(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await co({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await ll({projectRoot:e.projectRoot,runtimeDir:De(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await co({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await co({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await co({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:jr({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function Fh(e){return C(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Lt({paths:e.paths,state:t});let i=(await wl({file:B(e.paths,t.name),portableState:t,projectRoot:r,branch:Fe(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");jr({local:i,projectRoot:r,supplied:e.checks});let n=bh(t),a=await Se({paths:e.paths,previous:t,next:n}),o=B(e.paths,t.name),s=Nl();return await V(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function qh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await C(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await $(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Lt({paths:e.paths,state:r});let n=await $r({paths:e.paths,state:r}),a=cx({state:r,local:n,envelope:e.envelope}),o;try{o=fl(a.payload)}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,p=await lo({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${p.loop.execution_failure_count}/${Gi} was recorded`,{cause:d})}let s=lx(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=jr({local:n,projectRoot:i,supplied:e.checks}));let d=kh({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let u=await dx({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:u}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=d}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,p=await lo({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${p.loop.execution_failure_count}/${Gi} was recorded`,{cause:d})}let f=await Se({paths:e.paths,previous:r,next:l.state});return await V(B(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?Qi({local:n,state:f,projectRoot:i}):se({portableState:f,projectRoot:i,branch:Fe(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await Tr({file:ee.join(de(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await fx({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await C(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await $(e.paths,e.name);return a.state_version!==t.state.state_version?null:lo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Gi} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Wh(e){return C(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=await $r({paths:e.paths,state:t});if(Vh({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return lo({paths:e.paths,state:t,summary:e.summary})})}async function zh(e){return C(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);await Lt({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=Vh({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=jr({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Eh({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Se({paths:e.paths,previous:t,next:a});return await V(B(e.paths,t.name),Qi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Tr({file:ee.join(de(e.paths,t.name),"verification.md"),state:o}),o})}async function Jh(e){return C(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Lt({paths:e.paths,state:t});let r=Sh(t),i=await Se({paths:e.paths,previous:t,next:r});return await V(B(e.paths,t.name),se({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Tr({file:ee.join(de(e.paths,t.name),"verification.md"),state:i}),i})}async function Gh(e){return C(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Lt({paths:e.paths,state:t});let r=xh({state:t,summary:e.summary}),i=await Se({paths:e.paths,previous:t,next:r});return await V(B(e.paths,t.name),se({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Tr({file:ee.join(de(e.paths,t.name),"verification.md"),state:i}),i})}async function Uh(e){return C(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Lt({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=Ch(t,{reason:e.reason}),n=await Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),Qi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Kh(e){return C(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await $r({paths:e.paths,state:t}),i=Rh(t),n=await Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),Qi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function po(e){return C(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await $(e.paths,e.name);if(ir({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=Ui({state:t,reason:e.reason}),i=await Se({paths:e.paths,previous:t,next:r});return await V(B(e.paths,t.name),se({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function ho(e){return C(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await $(e.paths,e.name);if(ir({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Yh({paths:e.paths,state:t,reason:e.reason})})}async function Yh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...we(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete i.children_contract_hash;let n=await Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),se({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function mo(e){if(e.state.verification===null)return"not-applicable";let t=ee.join(de(e.paths,e.state.name),"verification.md");return await Ih({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Tr({file:t,state:e.state}),"rebuilt")}var Xh=["evidence.md","repair.md","archive.md","checkpoint.md"],mx="verification.md";async function vx(e,t){let r=await Tp(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Qh(e,t){await Zi.mkdir(e.transactionsDir,{recursive:!0}),await ve(Va(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Zh(e,t,r={}){let i=r.removeVerificationReport===!1?Xh:[...Xh,mx];await Promise.all([Zi.rm(De(e,t),{recursive:!0,force:!0}),Zi.rm(wc(e,t),{recursive:!0,force:!0}),...i.map(n=>Zi.rm(hx.join(Qe(e,t),n),{force:!0}))])}async function em(e,t){await V(B(e,t.name),se({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function tm(e,t){try{let r=await Ii(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function rm(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=q(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function gx(e){let t=Qe(e.paths,e.state.name),r=await U({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await U({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Da({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function im(e,t){let r=await mp(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function nm(e){return C(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await vx(e.paths,e.name),r=await Xi(e.paths,e.name)?await Be(qe(e.paths,e.name)):null;if(!t&&r)return await Zh(e.paths,e.name,{removeVerificationReport:!1}),await em(e.paths,r),r;let i=null,n=null;for(t||(i=await im(e.paths,e.name),n=await tm(e.paths,e.name),rm(e.paths,n),t={schema:Ba,id:px(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Qh(e.paths,t));;){let a=Cp(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await im(e.paths,e.name),n??=await tm(e.paths,e.name),rm(e.paths,n),r=xp({state:i,acceptance:await gx({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await xa(qe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Zh(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Be(qe(e.paths,e.name)),await em(e.paths,r)),t={...t,status:a.nextStatus},await Qh(e.paths,t)}return await Zi.rm(Va(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Be(qe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as am}from"node:fs";import om from"node:path";function wx(e,t){let r=q(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function yx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Nx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:we(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(t),completed_at:i});return P({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?yx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function bx(e){try{let t=await rt(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function kl(e){return C(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.status==="done")return await mo({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=wx(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=B(e.paths,e.name),n=await bx(i),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await V(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await mo({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=Ui({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Ai({file:qe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await am.rm(om.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=se({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await V(i,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=c||l;if(f){let u=Nx(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await Ai({file:qe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let d=se({portableState:t,projectRoot:e.paths.projectRoot,branch:q(e.paths.projectRoot).currentBranch});return await am.mkdir(om.dirname(B(e.paths,t.name)),{recursive:!0}),await V(i,d,{containedRoot:e.paths.runtimeDir}),await mo({paths:e.paths,state:t}),{state:t,local:d,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}function kx(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function it(e){let t=e.acceptance.reduce((r,i)=>({...r,[i.result]:r[i.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:t,unresolved_acceptance_ids:e.acceptance.filter(({result:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:kx(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}import{randomUUID as fm}from"node:crypto";import{promises as sm}from"node:fs";import tn from"node:path";function Or(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fe(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function D(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function El(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>D(r,`${t}[${i}]`))}function Sx(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Or(t,`Native Builder check ${r}`);if(fe(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:D(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function Ex(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Or(t,`Native Runtime check ${r}`);if(fe(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:D(i.id,`Native Runtime check ${r} id`),name:D(i.name,`Native Runtime check ${r} name`),executable:D(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:D(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function cm(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:D(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function xx(e){let t=Or(e,"Native Supervisor evidence");return fe(t,["summary","checks"],"Native Supervisor evidence"),{summary:D(t.summary,"Native Supervisor evidence summary"),checks:El(t.checks,"Native Supervisor evidence checks")}}function Cx(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=Or(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:D(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function Px(e){let t=Or(e,"Native Runner input");if(t.kind==="builder-handoff"){fe(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=Or(t.review,"Native Builder review");if(fe(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:D(t.summary,"Native Builder summary"),addressed_acceptance_ids:El(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:Sx(t.checks),known_limits:El(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:D(r.summary,"Native Builder review summary"),reviewer_execution_ref:D(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return fe(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:Ex(t.checks)};if(t.kind==="verifier-response")return fe(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return fe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:D(t.summary,"Native Verifier execution error summary"),...cm(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return fe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:D(t.summary,"Native unavailable Verifier summary"),...cm(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return fe(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),candidateCommit:D(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return fe(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),reason:D(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return fe(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return fe(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),reason:D(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(fe(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:xx(t.evidence)}}if(t.kind==="supervisor-integrate")return fe(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:D(t.child,"Native Supervisor child"),checks:Cx(t.checks)};throw new Error("Native Runner input kind is invalid")}async function pm(e,t){let r=tn.resolve(t,e),i=await sm.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await sm.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return Px(n)}function lm(e){return`${Y}:${e}:${fm()}`}function um(e,t,r,i){if(tn.resolve(_(e.projectRoot,["rev-parse","--show-toplevel"]))!==tn.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(_(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!st(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(_(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{_(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function Rx(e,t){let r=q(e.projectRoot),i=tn.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==tn.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=_(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!st(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{_(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function en(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Y)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function Ax(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function dm(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=en(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=Ax(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Y,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:de(t,r.name),supervisorStateRef:a?za(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:d})=>({capability:l,operation:f,ref:d})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function Sl(e){en(e.state);let t=await rt(B(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function hm(e){let t=await ie(e.paths,e.name),r=e.input,i=t?await $(e.paths,e.name):null,n=t!==null&&i?.phase==="verify"&&t.children.every(({status:u})=>u==="integrated"||u==="archived"),a=t!==null&&i?.phase==="build"&&t.children.every(({status:u})=>u==="integrated"||u==="archived");if(t&&r.kind==="supervisor-builder-result")return C(e.paths,`apply Native Supervisor Builder result ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:g})=>g===r.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${r.child}`);try{um(p.task,r.candidateCommit,"builder",`comet/supervisor/${u.parent}/${r.child}`)}catch(g){throw await oe(e.paths,Ga(u,{child:r.child,runId:r.runId,reason:g.message})),g}let v=p.task.projectRoot,m=Yp(u,r),h=Xc(m,{role:"verifier",child:r.child,projectRoot:v,runId:fm()});await oe(e.paths,h.state);let w=await $(e.paths,e.name);return{state:w,supervisorTask:h.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}});if(t&&r.kind==="supervisor-builder-failure")return C(e.paths,`cancel Native Supervisor Builder task ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:h})=>h===r.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${r.child}`);let v=Qc(u,{child:r.child,runId:r.runId,reason:r.reason});await oe(e.paths,v);let m=await $(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}});if(t&&r.kind==="supervisor-reconnect")return C(e.paths,`reconnect Native Supervisor task ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:h})=>h===r.child)?.task;if(!p||p.runId!==r.runId)throw new Error(`Native Supervisor task runId is not current for ${r.child}`);try{Rx(p,`comet/supervisor/${u.parent}/${r.child}`)}catch(h){throw await oe(e.paths,Ga(u,{child:r.child,runId:r.runId,reason:h.message})),h}let v=Up(u,{child:r.child,runId:r.runId});await oe(e.paths,v.state);let m=await $(e.paths,e.name);return{state:m,supervisorState:v.state,supervisorTask:v.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}});if(t&&r.kind==="supervisor-cancel")return C(e.paths,`cancel Native Supervisor task ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=Qc(u,{child:r.child,runId:r.runId,reason:r.reason});await oe(e.paths,p);let v=await $(e.paths,e.name);return{state:v,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(t&&r.kind==="supervisor-verifier-result")return C(e.paths,`apply Native Supervisor Verifier result ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:h})=>h===r.child);if(!p?.task||p.task.role!=="verifier"||!p.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${r.child}`);try{um(p.task,p.candidateCommit,"verifier",`comet/supervisor/${u.parent}/${r.child}`)}catch(h){throw await oe(e.paths,Ga(u,{child:r.child,runId:r.runId,reason:h.message})),h}let v=Xp(u,r);await oe(e.paths,v);let m=await $(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}});if(t&&r.kind==="supervisor-integrate"){let u=await Qp({paths:e.paths,state:t,name:r.child,checks:r.checks}),p=await fo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=p.state;return{state:v,supervisorState:u,supervisorTask:null,checks:r.checks,requestChecks:null,verifierDispatch:null,parentAdvance:p.parentAdvance,continuation:K(v)}}if(t&&(r.kind==="builder-handoff"||r.kind==="dispatch-verifier"||r.kind==="verifier-response"||r.kind==="verifier-execution-error"||r.kind==="verifier-unavailable"||r.kind==="supervisor-builder-result"||r.kind==="supervisor-builder-failure"||r.kind==="supervisor-reconnect"||r.kind==="supervisor-cancel"||r.kind==="supervisor-verifier-result")&&!n&&!(r.kind==="builder-handoff"&&a))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(r.kind==="builder-handoff"){let p=dl().captureExecutionIdentity({identityProvider:Y,executionRef:lm("builder")}),v=await Dh({paths:e.paths,name:e.name,input:{identity:p,summary:r.summary,addressedAcceptanceIds:r.addressed_acceptance_ids,checks:r.checks,knownLimits:r.known_limits,review:{status:r.review.status,summary:r.review.summary,reviewerExecutionRef:r.review.reviewer_execution_ref}}});return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}}if(r.kind==="dispatch-verifier"){if(n&&r.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let u=await $(e.paths,e.name);if(u.builder_handoff!==null&&u.builder_handoff.identity_provider!==Y){let w=await po({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:w,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}}en(u);let v=(u.loop.next_action==="run-final-full-verification"&&u.verification?.verdict==="pass"&&u.verification.checks.every(({status:w})=>w==="passed")?u.verification.checks:null)??(await Mh({paths:e.paths,name:e.name,plans:r.checks,...n&&t?{projectRoot:t.integration.worktree}:{}})).checks,m=lm("verifier"),h=await Fh({paths:e.paths,name:e.name,checks:v,verifierExecutionId:m,...n&&t?{projectRoot:t.integration.worktree}:{}});return{state:h,checks:v,requestChecks:null,verifierDispatch:dm({paths:e.paths,state:h,checks:v,verifierExecutionRef:m,supervisor:n?t:null}),continuation:K(h)}}if(r.kind==="verifier-execution-error"){let u=await $(e.paths,e.name);en(u),await Sl({paths:e.paths,state:u});let p=await Wh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:p,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(p)}}if(r.kind==="verifier-unavailable"){let u=await zh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:u,checks:u.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:K(u)}}if(r.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let o=await $(e.paths,e.name),s=en(o),c=await Sl({paths:e.paths,state:o}),l=dl(),f=l.captureExecutionIdentity({identityProvider:Y,executionRef:c}),d=await qh({paths:e.paths,name:e.name,envelope:l.envelopeVerifierResponse({candidateId:s.candidate_id,identity:f,payload:r.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...n&&t?{projectRoot:t.integration.worktree}:{}});if(n&&d.response.kind==="final-result"){if(d.state.verification_result==="pass"&&(d.checks.length===0||d.checks.some(({status:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let u=await ie(e.paths,e.name);if(!u)throw new Error("Native Supervisor state disappeared during verification");let p=_(u.integration.worktree,["rev-parse","HEAD"]),v=d.response.result.summary,m=u.children.every(({status:g,verification:y})=>(g==="integrated"||g==="archived")&&y!==null),h=d.checks.length>0&&d.checks.every(({status:g})=>g==="passed"),w=Zp(u,{status:d.state.verification_result==="pass"?"passed":d.state.verification_result==="blocked"?"incomplete":"failed",summary:v,headCommit:p,layers:{childVerification:m?"complete":"incomplete",parentIntegration:h?"complete":"incomplete",parentChecks:d.checks.map(({name:g})=>g.text),notRerun:u.children.flatMap(({verification:g})=>g?.checks??[]),incomplete:d.checks.filter(({status:g})=>g!=="passed").map(({name:g})=>g.text)}});return await oe(e.paths,w),{...d,supervisorState:w,verifierDispatch:null,continuation:K(d.state)}}return{...d,verifierDispatch:d.requestChecks===null?null:dm({paths:e.paths,state:d.state,checks:d.checks,verifierExecutionRef:await Sl({paths:e.paths,state:d.state}),supervisor:n?t:null}),continuation:K(d.state)}}import nn from"path";import{realpathSync as xC}from"fs";var mt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mm(e){return e?e.command?`${mt.next} ${e.command}`:e.ask_user?`${mt.next} ${e.ask_user}`:null:null}function vm(e,t){let r=[e.summary],i=mm(e.next);return i&&r.push(i),e.user_message&&r.push("",mt.relay,e.user_message),t!==void 0&&r.push("",mt.details,JSON.stringify(t,null,2)),`${r.join(`
243
+ `)}
244
+ `}function gm(e,t,r){let i=[e.summary],n=mm(e.next);return n&&i.push(n),e.user_message&&i.push("",mt.relay,e.user_message),i.push("",`${mt.detail} ${t}`),r!==void 0&&i.push("",mt.details,JSON.stringify(r,null,2)),i.join(`
245
+ `)}var Ix=["outcome","scope","nonGoals","acceptanceExamples"],DO=[...Ix,"constraints","decisions","openQuestions","verificationExpectations"];var Tx=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var wm=1024*1024;var Nm="scoped-text-safety",jx=1,$x=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Ox="comet.native.checker-policy.v1";var ZO=me(Ox,{policy:Nm,version:jx,limits:$x,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Hx=["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"],e0=new Set(Hx);var Lx=wm,g0=3*Lx;var bm={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:[]},Mx=Ae("comet-native-runtime:v3:scope-reopen"),W0=[{skillVersion:"3",skillHash:Ae("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Ae("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Ae("comet-native-runtime:v1")}];var Sm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],EH=new Set(Sm),Ux=new Set([...Sm,"minimum_runtime_version","revision"]),xH=new Set([...Ux,"operation"]),CH=512*1024,Kx=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),PH=new Set([...Kx,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var TH={maxAcceptanceCriteria:Ha.maxCriteria};var DH={maxSpecs:64,maxFileBytes:oa,maxTotalBytes:4*1024*1024};import{execFile as nC}from"node:child_process";import{promisify as aC}from"node:util";var GH={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var hD=512*1024;var rn=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var DD=64*1024;var BD=3600*1e3;var LD=aC(nC);var vo=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}};var EB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var $B=16*1024*1024,OB=256*1024,HB=16*1024;var FB=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var zB=16*1024;var iL=16*1024;var GL=16*1024*1024,go=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"},wo=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"};function R(e,t,r){return e==="zh-CN"?r:t}var xl={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Cm(e,t){return typeof e=="string"&&xl[e]?R(t,xl[e].en,xl[e].zh):typeof e=="string"?e:""}function Cl(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 dC(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 Pm(e,t){let r=[];e.failed>0&&r.push(R(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(R(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(R(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=R(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Rm(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 Pl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function fC(e,t,r){return e==="done"?R(r,"complete","已完成"):e==="await-user"?R(r,"waiting for a user decision","等待用户决定"):e==="blocked"?R(r,"paused: needs attention","已暂停,需要处理"):t?R(r,"waiting for a user decision","等待用户决定"):R(r,"ready to continue","可继续推进")}function pC(e,t,r){let i=Pl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=Cm(e.phase,i),s=fC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Pm(t,i));let c=e.userCommunication,l=Am(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Am(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:R(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:R(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:R(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function hC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function mC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Cm(e.phase,t),n=e.status==="await-user"?R(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?R(t,"paused","已暂停"):e.status==="done"?R(t,"complete","已完成"):R(t,"in progress","进行中"),a=Cl(e.acceptance)?`${R(t,", ",",")}${Pm(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function vC(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 gC(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 wC(e){if(e.healthy){let i=e.repaired?R("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):R("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=yC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:R("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:R("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function yC(e){return Rm(e)?Am(e,Pl(e)):void 0}function _m(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(gC(t))return wC(t);if(hC(t)){let i=vC(t.items);return{summary:[t.total===t.items.length?R(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):R(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>mC(a,i))].join(`
246
+ `)}}let r=t.continuation;if(Rm(r))return pC(r,NC(t),bC(t,Pl(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(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(Cl(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Cl(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return dC(r.acceptance)}return null}function bC(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Im(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("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:R("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:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("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:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("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:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Tm=["--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."],Al=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Tm,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] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, 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 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> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
243
247
  comet native next <change-name> --runner-input <json-file>`,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 Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--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, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," 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)."],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','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]
244
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Sl(e,t){return`${e}:
248
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Rl(e,t){return`${e}:
245
249
  ${t.map(r=>` ${r}`).join(`
246
- `)}`}function Jx(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return El[r]||t.length>1&&El[t[0]]?.subcommands?r:t[0]}function Gx(e=[]){let t=Jx(e),r=El[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Sl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...mm];return n&&n.length>0&&i.push("",Sl("Options",n)),i.push("",`Output:
247
- ${r.output}`),r.examples&&i.push("",Sl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
250
+ `)}`}function kC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Al[r]||t.length>1&&Al[t[0]]?.subcommands?r:t[0]}function SC(e=[]){let t=kC(e),r=Al[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Rl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Tm];return n&&n.length>0&&i.push("",Rl("Options",n)),i.push("",`Output:
251
+ ${r.output}`),r.examples&&i.push("",Rl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
248
252
  `)}
249
- `}}var Ux=Gx().usage;var TL=10*1024*1024,B=class extends Error{};function ft(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new B(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function ht(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new B(`${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 B(`${t} requires a value`);return e.splice(i,2),n}function gm(e){if(e.length>0)throw new B(`Unexpected argument: ${e[0]}`)}function wm(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new B(`${t} is required`);return r}function xl(e,t){let r=en.normalize(vm(e)),i=en.normalize(vm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function vm(e){let t=en.resolve(e);try{return Kx.native(t)}catch{return t}}function Yx(e){let t=en.resolve(e),r=F(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=F(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!xl(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||xl(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:xl(process.cwd(),r.currentWorktreeRoot)?en.resolve(process.cwd()):r.currentWorktreeRoot}async function ym(e){return e?Yx(e):ha(process.cwd())}async function Nm(e){let t=await Hf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function pt(e,t,r){return{command:e,exitCode:0,data:t,text:r??JSON.stringify(t,null,2)+`
250
- `}}function bm(e,t){if(t instanceof B)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof mo)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 vo)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof _a)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 _i)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 Tt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ia)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 po)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Zi)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 km(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
251
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}var Xx=new Set(["confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function Qx(e){let t=ht(e,"--expected-state-version"),r=ht(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new B("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new B("--expected-state-version must be a positive integer");if(!Xx.has(r))throw new B("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Or(e,t){let r=await Ze({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:U(t,r)}}function Zx(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function Sm(e){return{action:e.action,reason:e.reason,message:e.message}}async function Em(e,t){let r=wm(e,"change name"),i=ht(e,"--summary"),n=ht(e,"--runner-input"),a=ft(e,"--confirmed"),o=ft(e,"--accept-result"),s=ft(e,"--revise-implementation"),c=ft(e,"--revise-requirements"),l=ft(e,"--retry-verifier"),f=ft(e,"--resolve-verifier-blocker"),d=ht(e,"--coordination-mode"),u=d;if(d!==void 0&&!ga.includes(d))throw new B("--coordination-mode must be multi-session or single-session");if(u!==void 0&&!a)throw new B("--coordination-mode is only valid with --confirmed in Shape");let h=ht(e,"--max-parallel"),v=h===void 0?2:Number(h);if(!Number.isSafeInteger(v)||v<1)throw new B("--max-parallel must be a positive integer");let m=Qx(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new B("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");gm(e);let p=await Nm(t);if(!await Ui(p.paths,r)){if(n)throw new B("--runner-input is only valid for portable Native changes");if(!i)throw new B("--summary is required");let S=await Yp({paths:p.paths,name:r});return pt("next",{state:rt(S),migration:{completed:!0,summary:i},continuation:U(S)})}if(n){if(i||a||o||s||c||l||f||m)throw new B("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let S=await Nl({paths:p.paths,name:r,preserveRunningExecution:!0}),E=S.state;if(S.action==="await-user"||S.action==="done"||S.reason!=="available")return pt("next",{state:rt(E),recovery:Sm(S),...await Or(p.paths,E)});if(E.phase==="build"){let _=await co({paths:p.paths,state:E});if(_.drifted){let $=await fo({paths:p.paths,name:r,reason:_.reason??"Native confirmed requirements changed"});return pt("next",{state:rt($),...await Or(p.paths,$)})}let Y=await re(p.paths,r),ee=await Ze({paths:p.paths,state:E});if(ee&&!ee.allDone&&!Y)throw new B("Native parent Build advances child changes and does not accept a Builder handoff")}let x=await am(n,t),N=await om({paths:p.paths,name:r,input:x,maxVerifyFailures:p.config.native.max_verify_failures});return pt("next",{...Zx(N),state:rt(N.state),...await Or(p.paths,N.state),coordination:K})}let y=await Nl({paths:p.paths,name:r}),g=y.state;if(u!==void 0&&g.phase!=="shape")throw new B("--coordination-mode is only valid when confirming Shape");if(!i)throw new B("--summary is required");let w,k=null;if(a)if(g.phase==="shape")w=await Rp({paths:p.paths,name:r,...u===void 0?{}:{coordinationMode:u},expectedContinuation:m});else if(g.phase==="verify"&&g.status==="await-user"&&g.loop.next_action==="confirm-verifier-unavailable")w=await Lp({paths:p.paths,name:r,summary:i,expectedContinuation:m});else throw new B("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback");else if(o){if(!m&&(g.phase!=="verify"||g.status!=="await-user"||g.loop.next_action!=="confirm-skill-coordinated-pass"))throw new B("--accept-result is only valid for a pending Verify pass decision");w=await Bp({paths:p.paths,name:r,expectedContinuation:m})}else if(s){if(g.phase!=="verify")throw new B("--revise-implementation is only valid from Verify");w=await uo({paths:p.paths,name:r,reason:i,expectedContinuation:m})}else if(c){if(!m&&g.phase!=="verify"&&g.phase!=="archive")throw new B("--revise-requirements is only valid from Verify or Archive");w=await fo({paths:p.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:m})}else if(l)w=await Mp({paths:p.paths,name:r,expectedContinuation:m});else if(f)w=await Vp({paths:p.paths,name:r,expectedContinuation:m});else{if(y.reason!=="available")return pt("next",{state:rt(g),recovery:Sm(y),...await Or(p.paths,g)});if(g.phase==="build"){let E=await co({paths:p.paths,state:g});if(E.drifted)w=await fo({paths:p.paths,name:r,reason:E.reason??"Native confirmed requirements changed"});else{let x=await Ze({paths:p.paths,state:g});if(x){let N=x,_=[],Y=await re(p.paths,r);if(Y&&!x.allDone){let ee=await Wh({paths:p.paths,parent:r,maxParallel:v});_=ee.tasks,(_.length>0||ee.state.stateVersion!==Y.stateVersion)&&(N=await Ze({paths:p.paths,state:g})??N)}if(N.allDone&&!(g.loop.stage==="repairing"&&g.verification_result==="fail"))k=await lo({paths:p.paths,name:r,trigger:"recovery"}),w=k.state;else return pt("next",{state:rt(g),childSummary:N.children.reduce((ee,$)=>({...ee,[$.status]:(ee[$.status]??0)+1}),{total:N.children.length}),readyChildren:N.readyChildren,..._.length>0?{supervisorTasks:_}:{},continuation:U(g,N)})}}}if(w)return pt("next",{state:rt(w),...k?{parentAdvance:k.parentAdvance}:{},...await Or(p.paths,w)});let S=g.phase==="shape"?await Ze({paths:p.paths,state:g}):null;return{command:"next",exitCode:65,data:{state:rt(g),continuation:U(g,S)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return pt("next",{state:rt(w),...u===void 0?{}:{coordinationMode:u},...await Or(p.paths,w)})}function eP(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
252
- `}}async function xm(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,c;try{ft(n,"--json"),s=ht(n,"--project-root");let f=[...n,...a],d=await ym(s);c=await t(f,d)}catch(f){c=bm(e,f)}let l=o?eP(c):km(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
253
+ `}}var EC=SC().usage;var fV=10*1024*1024,L=class extends Error{};function nt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new L(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function vt(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new L(`${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 L(`${t} requires a value`);return e.splice(i,2),n}function $m(e){if(e.length>0)throw new L(`Unexpected argument: ${e[0]}`)}function Om(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new L(`${t} is required`);return r}function _l(e,t){let r=nn.normalize(jm(e)),i=nn.normalize(jm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function jm(e){let t=nn.resolve(e);try{return xC.native(t)}catch{return t}}function CC(e){let t=nn.resolve(e),r=q(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=q(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!_l(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||_l(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:_l(process.cwd(),r.currentWorktreeRoot)?nn.resolve(process.cwd()):r.currentWorktreeRoot}async function Hm(e){return e?CC(e):va(process.cwd())}async function Dm(e){let t=await Mf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Bm(e){return JSON.stringify(e,null,2)+`
254
+ `}function gt(e,t,r){return{command:e,exitCode:0,data:t,text:r??Bm(t)}}function PC(e,t){if(t instanceof L)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof go)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 wo)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof ja)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 Ti)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 Ot)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof $a)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 vo)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof rn)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 Lm(e,t){let r=PC(e,t),i=r.error;if(!i)return r;let n=Im({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function Vm(e,t,r=!1){let i=e.envelope??_m(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...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}})+`
255
+ `}:e.error?{exitCode:e.exitCode,stderr:i?gm(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:vm(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Bm(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
256
+ ${mt.details}
257
+ ${JSON.stringify(e.data,null,2)}
258
+ `}:{exitCode:e.exitCode,stdout:e.text}}var RC=new Set(["confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function AC(e){let t=vt(e,"--expected-state-version"),r=vt(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new L("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new L("--expected-state-version must be a positive integer");if(!RC.has(r))throw new L("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Dr(e,t){let r=await et({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:K(t,r)}}function _C(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function Mm(e){return{action:e.action,reason:e.reason,message:e.message}}async function Fm(e,t){let r=Om(e,"change name"),i=vt(e,"--summary"),n=vt(e,"--runner-input"),a=nt(e,"--confirmed"),o=nt(e,"--accept-result"),s=nt(e,"--revise-implementation"),c=nt(e,"--revise-requirements"),l=nt(e,"--retry-verifier"),f=nt(e,"--resolve-verifier-blocker"),d=vt(e,"--coordination-mode"),u=d;if(d!==void 0&&!Na.includes(d))throw new L("--coordination-mode must be multi-session or single-session");if(u!==void 0&&!a)throw new L("--coordination-mode is only valid with --confirmed in Shape");let p=vt(e,"--max-parallel"),v=p===void 0?2:Number(p);if(!Number.isSafeInteger(v)||v<1)throw new L("--max-parallel must be a positive integer");let m=AC(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new L("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");$m(e);let h=await Dm(t);if(!await Xi(h.paths,r)){if(n)throw new L("--runner-input is only valid for portable Native changes");if(!i)throw new L("--summary is required");let S=await nm({paths:h.paths,name:r});return gt("next",{state:it(S),migration:{completed:!0,summary:i},continuation:K(S)})}if(n){if(i||a||o||s||c||l||f||m)throw new L("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let S=await kl({paths:h.paths,name:r,preserveRunningExecution:!0}),E=S.state;if(S.action==="await-user"||S.action==="done"||S.reason!=="available")return gt("next",{state:it(E),recovery:Mm(S),...await Dr(h.paths,E)});if(E.phase==="build"){let I=await uo({paths:h.paths,state:E});if(I.drifted){let O=await ho({paths:h.paths,name:r,reason:I.reason??"Native confirmed requirements changed"});return gt("next",{state:it(O),...await Dr(h.paths,O)})}let X=await ie(h.paths,r),te=await et({paths:h.paths,state:E});if(te&&!te.allDone&&!X)throw new L("Native parent Build advances child changes and does not accept a Builder handoff")}let x=await pm(n,t),N=await hm({paths:h.paths,name:r,input:x,maxVerifyFailures:h.config.native.max_verify_failures});return gt("next",{..._C(N),state:it(N.state),...await Dr(h.paths,N.state),coordination:Y})}let w=await kl({paths:h.paths,name:r}),g=w.state;if(u!==void 0&&g.phase!=="shape")throw new L("--coordination-mode is only valid when confirming Shape");if(!i)throw new L("--summary is required");let y,k=null;if(a)if(g.phase==="shape")y=await Hh({paths:h.paths,name:r,...u===void 0?{}:{coordinationMode:u},expectedContinuation:m});else if(g.phase==="verify"&&g.status==="await-user"&&g.loop.next_action==="confirm-verifier-unavailable")y=await Gh({paths:h.paths,name:r,summary:i,expectedContinuation:m});else throw new L("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback");else if(o){if(!m&&(g.phase!=="verify"||g.status!=="await-user"||g.loop.next_action!=="confirm-skill-coordinated-pass"))throw new L("--accept-result is only valid for a pending Verify pass decision");y=await Jh({paths:h.paths,name:r,expectedContinuation:m})}else if(s){if(g.phase!=="verify")throw new L("--revise-implementation is only valid from Verify");y=await po({paths:h.paths,name:r,reason:i,expectedContinuation:m})}else if(c){if(!m&&g.phase!=="verify"&&g.phase!=="archive")throw new L("--revise-requirements is only valid from Verify or Archive");y=await ho({paths:h.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:m})}else if(l)y=await Kh({paths:h.paths,name:r,expectedContinuation:m});else if(f)y=await Uh({paths:h.paths,name:r,reason:i,expectedContinuation:m});else{if(w.reason!=="available")return gt("next",{state:it(g),recovery:Mm(w),...await Dr(h.paths,g)});if(g.phase==="build"){let E=await uo({paths:h.paths,state:g});if(E.drifted)y=await ho({paths:h.paths,name:r,reason:E.reason??"Native confirmed requirements changed"});else{let x=await et({paths:h.paths,state:g});if(x){let N=x,I=[],X=await ie(h.paths,r);if(X&&!x.allDone){let te=await Kp({paths:h.paths,parent:r,maxParallel:v});I=te.tasks,(I.length>0||te.state.stateVersion!==X.stateVersion)&&(N=await et({paths:h.paths,state:g})??N)}if(N.allDone&&!(g.loop.stage==="repairing"&&g.verification_result==="fail"))k=await fo({paths:h.paths,name:r,trigger:"recovery"}),y=k.state;else return gt("next",{state:it(g),childSummary:N.children.reduce((te,O)=>({...te,[O.status]:(te[O.status]??0)+1}),{total:N.children.length}),readyChildren:N.readyChildren,...I.length>0?{supervisorTasks:I}:{},continuation:K(g,N)})}}}if(y)return gt("next",{state:it(y),...k?{parentAdvance:k.parentAdvance}:{},...await Dr(h.paths,y)});let S=g.phase==="shape"?await et({paths:h.paths,state:g}):null;return{command:"next",exitCode:65,data:{state:it(g),continuation:K(g,S)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return gt("next",{state:it(y),...u===void 0?{}:{coordinationMode:u},...await Dr(h.paths,y)})}async function qm(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{nt(n,"--json"),nt(n,"--verbose"),c=vt(n,"--project-root");let d=[...n,...a],u=await Hm(c);l=await t(d,u)}catch(d){l=Lm(e,d)}let f=Vm(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
253
259
  `)?"":`
254
- `)),l.exitCode}process.exitCode=await xm("next",Em);
260
+ `)),f.exitCode}process.exitCode=await qm("next",Fm);