comet-dsh-plugin 0.0.0-stage → 0.5.4

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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +176 -0
  3. package/README.md +152 -2
  4. package/client.js +349 -0
  5. package/cordis.patch.yml +4 -0
  6. package/icon.png +0 -0
  7. package/index.js +183 -0
  8. package/locale/en.json +7 -0
  9. package/locale/zh.json +7 -0
  10. package/package.json +58 -4
  11. package/rules/comet-workflow-guard.md +65 -0
  12. package/rules/migration-assets.json +218 -0
  13. package/server/comet-plugin-setup.mjs +192 -0
  14. package/skills/comet/SKILL.md +37 -0
  15. package/skills/comet/agents/openai.yaml +3 -0
  16. package/skills/comet/reference/change-walkthrough.md +77 -0
  17. package/skills/comet/reference/edit-review.md +26 -0
  18. package/skills/comet/reference/host-check.md +11 -0
  19. package/skills/comet/reference/platform-execution.md +34 -0
  20. package/skills/comet/reference/task-learning.md +39 -0
  21. package/skills/comet/runtime/classic/checks.yaml +6 -0
  22. package/skills/comet/runtime/classic/guardrails.yaml +13 -0
  23. package/skills/comet/runtime/classic/skill.yaml +122 -0
  24. package/skills/comet/scripts/comet-archive.mjs +310 -0
  25. package/skills/comet/scripts/comet-check.mjs +179 -0
  26. package/skills/comet/scripts/comet-entry-runtime.mjs +151 -0
  27. package/skills/comet/scripts/comet-env.mjs +15 -0
  28. package/skills/comet/scripts/comet-guard.mjs +335 -0
  29. package/skills/comet/scripts/comet-handoff.mjs +289 -0
  30. package/skills/comet/scripts/comet-hook-guard.mjs +295 -0
  31. package/skills/comet/scripts/comet-hook-router-guard.mjs +629 -0
  32. package/skills/comet/scripts/comet-hook-router.mjs +17 -0
  33. package/skills/comet/scripts/comet-intent.mjs +181 -0
  34. package/skills/comet/scripts/comet-plugin-hook.mjs +213 -0
  35. package/skills/comet/scripts/comet-resume-probe.mjs +205 -0
  36. package/skills/comet/scripts/comet-runtime.mjs +572 -0
  37. package/skills/comet/scripts/comet-state.mjs +381 -0
  38. package/skills/comet/scripts/comet-yaml-validate.mjs +182 -0
  39. package/skills/comet-any/SKILL.md +47 -0
  40. package/skills/comet-any/agents/openai.yaml +5 -0
  41. package/skills/comet-any/reference/sdk-creation.md +100 -0
  42. package/skills/comet-archive/SKILL.md +28 -0
  43. package/skills/comet-archive/agents/openai.yaml +5 -0
  44. package/skills/comet-archive/reference/compat.md +188 -0
  45. package/skills/comet-build/SKILL.md +35 -0
  46. package/skills/comet-build/agents/openai.yaml +5 -0
  47. package/skills/comet-build/reference/compat.md +191 -0
  48. package/skills/comet-classic/SKILL.md +98 -0
  49. package/skills/comet-classic/agents/openai.yaml +3 -0
  50. package/skills/comet-classic/reference/auto-transition.md +34 -0
  51. package/skills/comet-classic/reference/classic-layout.md +36 -0
  52. package/skills/comet-classic/reference/comet-yaml-fields.md +82 -0
  53. package/skills/comet-classic/reference/context-recovery.md +128 -0
  54. package/skills/comet-classic/reference/debug-gate.md +30 -0
  55. package/skills/comet-classic/reference/decision-point.md +109 -0
  56. package/skills/comet-classic/reference/dirty-worktree.md +59 -0
  57. package/skills/comet-classic/reference/file-structure.md +32 -0
  58. package/skills/comet-classic/reference/intent-frame.md +132 -0
  59. package/skills/comet-classic/reference/scripts.md +144 -0
  60. package/skills/comet-classic/reference/sdk-methods.md +136 -0
  61. package/skills/comet-classic/reference/subagent-dispatch.md +75 -0
  62. package/skills/comet-classic/reference/workspace.md +23 -0
  63. package/skills/comet-design/SKILL.md +25 -0
  64. package/skills/comet-design/agents/openai.yaml +5 -0
  65. package/skills/comet-design/reference/compat.md +191 -0
  66. package/skills/comet-hotfix/SKILL.md +46 -0
  67. package/skills/comet-hotfix/agents/openai.yaml +5 -0
  68. package/skills/comet-hotfix/reference/compat.md +240 -0
  69. package/skills/comet-memory/SKILL.md +68 -0
  70. package/skills/comet-memory/agents/openai.yaml +5 -0
  71. package/skills/comet-native/SKILL.md +139 -0
  72. package/skills/comet-native/agents/openai.yaml +3 -0
  73. package/skills/comet-native/reference/artifacts.md +118 -0
  74. package/skills/comet-native/reference/clarification.md +120 -0
  75. package/skills/comet-native/reference/commands.md +321 -0
  76. package/skills/comet-native/reference/edit-review.md +26 -0
  77. package/skills/comet-native/reference/recovery.md +64 -0
  78. package/skills/comet-native/reference/workspace.md +70 -0
  79. package/skills/comet-native/scripts/comet-native-archive.mjs +475 -0
  80. package/skills/comet-native/scripts/comet-native-cancel.mjs +461 -0
  81. package/skills/comet-native/scripts/comet-native-doctor.mjs +475 -0
  82. package/skills/comet-native/scripts/comet-native-hook-guard.mjs +470 -0
  83. package/skills/comet-native/scripts/comet-native-init.mjs +465 -0
  84. package/skills/comet-native/scripts/comet-native-new.mjs +478 -0
  85. package/skills/comet-native/scripts/comet-native-next.mjs +470 -0
  86. package/skills/comet-native/scripts/comet-native-root.mjs +472 -0
  87. package/skills/comet-native/scripts/comet-native-runtime.mjs +525 -0
  88. package/skills/comet-native/scripts/comet-native-select.mjs +468 -0
  89. package/skills/comet-native/scripts/comet-native-show.mjs +462 -0
  90. package/skills/comet-native/scripts/comet-native-spec.mjs +468 -0
  91. package/skills/comet-native/scripts/comet-native-status.mjs +467 -0
  92. package/skills/comet-native/scripts/comet-native-transfer.mjs +466 -0
  93. package/skills/comet-open/SKILL.md +265 -0
  94. package/skills/comet-open/agents/openai.yaml +5 -0
  95. package/skills/comet-open/reference/batch-changes.md +51 -0
  96. package/skills/comet-review/SKILL.md +121 -0
  97. package/skills/comet-review/agents/openai.yaml +5 -0
  98. package/skills/comet-tweak/SKILL.md +49 -0
  99. package/skills/comet-tweak/agents/openai.yaml +5 -0
  100. package/skills/comet-tweak/reference/compat.md +232 -0
  101. package/skills/comet-verify/SKILL.md +30 -0
  102. package/skills/comet-verify/agents/openai.yaml +5 -0
  103. package/skills/comet-verify/reference/compat.md +202 -0
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __cometCreateRequire } from 'module';
3
+ const require = __cometCreateRequire(import.meta.url);
4
+ var pA=Object.create;var pd=Object.defineProperty;var mA=Object.getOwnPropertyDescriptor;var hA=Object.getOwnPropertyNames;var gA=Object.getPrototypeOf,wA=Object.prototype.hasOwnProperty;var Qa=(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 je=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var A=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},yA=(e,t)=>{for(var r in t)pd(e,r,{get:t[r],enumerable:!0})},vA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of hA(t))!wA.call(e,i)&&i!==r&&pd(e,i,{get:()=>t[i],enumerable:!(n=mA(t,i))||n.enumerable});return e};var Tt=(e,t,r)=>(r=e!=null?pA(gA(e)):{},vA(t||!e||!e.__esModule?pd(r,"default",{value:e,enumerable:!0}):r,e));var we=A(dt=>{"use strict";var md=Symbol.for("yaml.alias"),Gg=Symbol.for("yaml.document"),ec=Symbol.for("yaml.map"),Yg=Symbol.for("yaml.pair"),hd=Symbol.for("yaml.scalar"),tc=Symbol.for("yaml.seq"),Gr=Symbol.for("yaml.node.type"),RA=e=>!!e&&typeof e=="object"&&e[Gr]===md,SA=e=>!!e&&typeof e=="object"&&e[Gr]===Gg,CA=e=>!!e&&typeof e=="object"&&e[Gr]===ec,EA=e=>!!e&&typeof e=="object"&&e[Gr]===Yg,Xg=e=>!!e&&typeof e=="object"&&e[Gr]===hd,_A=e=>!!e&&typeof e=="object"&&e[Gr]===tc;function Qg(e){if(e&&typeof e=="object")switch(e[Gr]){case ec:case tc:return!0}return!1}function AA(e){if(e&&typeof e=="object")switch(e[Gr]){case md:case ec:case hd:case tc:return!0}return!1}var xA=e=>(Xg(e)||Qg(e))&&!!e.anchor;dt.ALIAS=md;dt.DOC=Gg;dt.MAP=ec;dt.NODE_TYPE=Gr;dt.PAIR=Yg;dt.SCALAR=hd;dt.SEQ=tc;dt.hasAnchor=xA;dt.isAlias=RA;dt.isCollection=Qg;dt.isDocument=SA;dt.isMap=CA;dt.isNode=AA;dt.isPair=EA;dt.isScalar=Xg;dt.isSeq=_A});var ns=A(gd=>{"use strict";var st=we(),$t=Symbol("break visit"),Zg=Symbol("skip children"),Nr=Symbol("remove node");function rc(e,t){let r=ew(t);st.isDocument(e)?Yi(null,e.contents,r,Object.freeze([e]))===Nr&&(e.contents=null):Yi(null,e,r,Object.freeze([]))}rc.BREAK=$t;rc.SKIP=Zg;rc.REMOVE=Nr;function Yi(e,t,r,n){let i=tw(e,t,r,n);if(st.isNode(i)||st.isPair(i))return rw(e,n,i),Yi(e,i,r,n);if(typeof i!="symbol"){if(st.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let s=Yi(o,t.items[o],r,n);if(typeof s=="number")o=s-1;else{if(s===$t)return $t;s===Nr&&(t.items.splice(o,1),o-=1)}}}else if(st.isPair(t)){n=Object.freeze(n.concat(t));let o=Yi("key",t.key,r,n);if(o===$t)return $t;o===Nr&&(t.key=null);let s=Yi("value",t.value,r,n);if(s===$t)return $t;s===Nr&&(t.value=null)}}return i}async function nc(e,t){let r=ew(t);st.isDocument(e)?await Xi(null,e.contents,r,Object.freeze([e]))===Nr&&(e.contents=null):await Xi(null,e,r,Object.freeze([]))}nc.BREAK=$t;nc.SKIP=Zg;nc.REMOVE=Nr;async function Xi(e,t,r,n){let i=await tw(e,t,r,n);if(st.isNode(i)||st.isPair(i))return rw(e,n,i),Xi(e,i,r,n);if(typeof i!="symbol"){if(st.isCollection(t)){n=Object.freeze(n.concat(t));for(let o=0;o<t.items.length;++o){let s=await Xi(o,t.items[o],r,n);if(typeof s=="number")o=s-1;else{if(s===$t)return $t;s===Nr&&(t.items.splice(o,1),o-=1)}}}else if(st.isPair(t)){n=Object.freeze(n.concat(t));let o=await Xi("key",t.key,r,n);if(o===$t)return $t;o===Nr&&(t.key=null);let s=await Xi("value",t.value,r,n);if(s===$t)return $t;s===Nr&&(t.value=null)}}return i}function ew(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 tw(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(st.isMap(t))return r.Map?.(e,t,n);if(st.isSeq(t))return r.Seq?.(e,t,n);if(st.isPair(t))return r.Pair?.(e,t,n);if(st.isScalar(t))return r.Scalar?.(e,t,n);if(st.isAlias(t))return r.Alias?.(e,t,n)}function rw(e,t,r){let n=t[t.length-1];if(st.isCollection(n))n.items[e]=r;else if(st.isPair(n))e==="key"?n.key=r:n.value=r;else if(st.isDocument(n))n.contents=r;else{let i=st.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}gd.visit=rc;gd.visitAsync=nc});var wd=A(iw=>{"use strict";var nw=we(),PA=ns(),IA={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},OA=e=>e.replace(/[!,[\]{}]/g,t=>IA[t]),is=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 n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[o,s]=n;return this.tags[o]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[o]=n;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let s=/^\d+\.\d+$/.test(o);return r(6,`Unsupported YAML version ${o}`,s),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let s=t.slice(2,-1);return s==="!"||s==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),s)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let o=this.tags[n];if(o)try{return o+decodeURIComponent(i)}catch(s){return r(String(s)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+OA(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&nw.isNode(t.contents)){let o={};PA.visit(t.contents,(s,c)=>{nw.isNode(c)&&c.tag&&(o[c.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,s]of n)o==="!!"&&s==="tag:yaml.org,2002:"||(!t||i.some(c=>c.startsWith(s)))&&r.push(`%TAG ${o} ${s}`);return r.join(`
5
+ `)}};is.defaultYaml={explicit:!1,version:"1.2"};is.defaultTags={"!!":"tag:yaml.org,2002:"};iw.Directives=is});var ic=A(os=>{"use strict";var ow=we(),NA=ns();function TA(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 sw(e){let t=new Set;return NA.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function aw(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function $A(e,t){let r=[],n=new Map,i=null;return{onAnchor:o=>{r.push(o),i??(i=sw(e));let s=aw(t,i);return i.add(s),s},setAnchors:()=>{for(let o of r){let s=n.get(o);if(typeof s=="object"&&s.anchor&&(ow.isScalar(s.node)||ow.isCollection(s.node)))s.node.anchor=s.anchor;else{let c=new Error("Failed to resolve repeated object (this should not happen)");throw c.source=o,c}}},sourceObjects:n}}os.anchorIsValid=TA;os.anchorNames=sw;os.createNodeAnchors=$A;os.findNewAnchor=aw});var yd=A(cw=>{"use strict";function ss(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,o=n.length;i<o;++i){let s=n[i],c=ss(e,n,String(i),s);c===void 0?delete n[i]:c!==s&&(n[i]=c)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let o=n.get(i),s=ss(e,n,i,o);s===void 0?n.delete(i):s!==o&&n.set(i,s)}else if(n instanceof Set)for(let i of Array.from(n)){let o=ss(e,n,i,i);o===void 0?n.delete(i):o!==i&&(n.delete(i),n.add(o))}else for(let[i,o]of Object.entries(n)){let s=ss(e,n,i,o);s===void 0?delete n[i]:s!==o&&(n[i]=s)}return e.call(t,r,n)}cw.applyReviver=ss});var dn=A(uw=>{"use strict";var jA=we();function lw(e,t,r){if(Array.isArray(e))return e.map((n,i)=>lw(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!jA.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=o=>{n.res=o,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}uw.toJS=lw});var oc=A(fw=>{"use strict";var DA=yd(),dw=we(),qA=dn(),vd=class{constructor(t){Object.defineProperty(this,dw.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:n,onAnchor:i,reviver:o}={}){if(!dw.isDocument(t))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=qA.toJS(this,"",s);if(typeof i=="function")for(let{count:u,res:f}of s.anchors.values())i(f,u);return typeof o=="function"?DA.applyReviver(o,{"":c},"",c):c}};fw.NodeBase=vd});var as=A(pw=>{"use strict";var LA=ic(),MA=ns(),Qi=we(),WA=oc(),FA=dn(),kd=class extends WA.NodeBase{constructor(t){super(Qi.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 n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],MA.visit(t,{Node:(o,s)=>{(Qi.isAlias(s)||Qi.hasAnchor(s))&&n.push(s)}}),r&&(r.aliasResolveCache=n));let i;for(let o of n){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:o}=r,s=this.resolve(i,r);if(!s){let u=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(u)}let c=n.get(s);if(c||(FA.toJS(s,null,r),c=n.get(s)),c?.res===void 0){let u="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(u)}if(o>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=sc(i,s,n)),c.count*c.aliasCount>o)){let u="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(u)}return c.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(LA.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${i} `}return i}};function sc(e,t,r){if(Qi.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(Qi.isCollection(t)){let n=0;for(let i of t.items){let o=sc(e,i,r);o>n&&(n=o)}return n}else if(Qi.isPair(t)){let n=sc(e,t.key,r),i=sc(e,t.value,r);return Math.max(n,i)}return 1}pw.Alias=kd});var Ze=A(bd=>{"use strict";var HA=we(),VA=oc(),BA=dn(),UA=e=>!e||typeof e!="function"&&typeof e!="object",fn=class extends VA.NodeBase{constructor(t){super(HA.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:BA.toJS(this.value,t,r)}toString(){return String(this.value)}};fn.BLOCK_FOLDED="BLOCK_FOLDED";fn.BLOCK_LITERAL="BLOCK_LITERAL";fn.PLAIN="PLAIN";fn.QUOTE_DOUBLE="QUOTE_DOUBLE";fn.QUOTE_SINGLE="QUOTE_SINGLE";bd.Scalar=fn;bd.isScalarValue=UA});var cs=A(hw=>{"use strict";var KA=as(),Qn=we(),mw=Ze(),JA="tag:yaml.org,2002:";function zA(e,t,r){if(t){let n=r.filter(o=>o.tag===t),i=n.find(o=>!o.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function GA(e,t,r){if(Qn.isDocument(e)&&(e=e.contents),Qn.isNode(e))return e;if(Qn.isPair(e)){let d=r.schema[Qn.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:n,onAnchor:i,onTagObj:o,schema:s,sourceObjects:c}=r,u;if(n&&e&&typeof e=="object"){if(u=c.get(e),u)return u.anchor??(u.anchor=i(e)),new KA.Alias(u.anchor);u={anchor:null,node:null},c.set(e,u)}t?.startsWith("!!")&&(t=JA+t.slice(2));let f=zA(e,t,s.tags);if(!f){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new mw.Scalar(e);return u&&(u.node=d),d}f=e instanceof Map?s[Qn.MAP]:Symbol.iterator in Object(e)?s[Qn.SEQ]:s[Qn.MAP]}o&&(o(f),delete r.onTagObj);let a=f?.createNode?f.createNode(r.schema,e,r):typeof f?.nodeClass?.from=="function"?f.nodeClass.from(r.schema,e,r):new mw.Scalar(e);return t?a.tag=t:f.default||(a.tag=f.tag),u&&(u.node=a),a}hw.createNode=GA});var cc=A(ac=>{"use strict";var YA=cs(),Tr=we(),XA=oc();function Rd(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let o=t[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let s=[];s[o]=n,n=s}else n=new Map([[o,n]])}return YA.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var gw=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Sd=class extends XA.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(n=>Tr.isNode(n)||Tr.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(gw(t))this.add(r);else{let[n,...i]=t,o=this.get(n,!0);if(Tr.isCollection(o))o.addIn(i,r);else if(o===void 0&&this.schema)this.set(n,Rd(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(Tr.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,o=this.get(n,!0);return i.length===0?!r&&Tr.isScalar(o)?o.value:o:Tr.isCollection(o)?o.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Tr.isPair(r))return!1;let n=r.value;return n==null||t&&Tr.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return Tr.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let o=this.get(n,!0);if(Tr.isCollection(o))o.setIn(i,r);else if(o===void 0&&this.schema)this.set(n,Rd(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};ac.Collection=Sd;ac.collectionFromPath=Rd;ac.isEmptyPath=gw});var ls=A(lc=>{"use strict";var QA=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Cd(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var ZA=(e,t,r)=>e.endsWith(`
6
+ `)?Cd(r,t):r.includes(`
7
+ `)?`
8
+ `+Cd(r,t):(e.endsWith(" ")?"":" ")+r;lc.indentComment=Cd;lc.lineComment=ZA;lc.stringifyComment=QA});var yw=A(us=>{"use strict";var ex="flow",Ed="block",uc="quoted";function tx(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:o=20,onFold:s,onOverflow:c}={}){if(!i||i<0)return e;i<o&&(o=0);let u=Math.max(1+o,1+i-t.length);if(e.length<=u)return e;let f=[],a={},d=i-t.length;typeof n=="number"&&(n>i-Math.max(2,o)?f.push(0):d=i-n);let p,l,m=!1,h=-1,g=-1,w=-1;r===Ed&&(h=ww(e,h,t.length),h!==-1&&(d=h+u));for(let b;b=e[h+=1];){if(r===uc&&b==="\\"){switch(g=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===`
9
+ `)r===Ed&&(h=ww(e,h,t.length)),d=h+t.length+u,p=void 0;else{if(b===" "&&l&&l!==" "&&l!==`
10
+ `&&l!==" "){let S=e[h+1];S&&S!==" "&&S!==`
11
+ `&&S!==" "&&(p=h)}if(h>=d)if(p)f.push(p),d=p+u,p=void 0;else if(r===uc){for(;l===" "||l===" ";)l=b,b=e[h+=1],m=!0;let S=h>w+1?h-2:g-1;if(a[S])return e;f.push(S),a[S]=!0,d=S+u,p=void 0}else m=!0}l=b}if(m&&c&&c(),f.length===0)return e;s&&s();let k=e.slice(0,f[0]);for(let b=0;b<f.length;++b){let S=f[b],E=f[b+1]||e.length;S===0?k=`
12
+ ${t}${e.slice(0,E)}`:(r===uc&&a[S]&&(k+=`${e[S]}\\`),k+=`
13
+ ${t}${e.slice(S+1,E)}`)}return k}function ww(e,t,r){let n=t,i=t+1,o=e[i];for(;o===" "||o===" ";)if(t<i+r)o=e[++t];else{do o=e[++t];while(o&&o!==`
14
+ `);n=t,i=t+1,o=e[i]}return n}us.FOLD_BLOCK=Ed;us.FOLD_FLOW=ex;us.FOLD_QUOTED=uc;us.foldFlowLines=tx});var fs=A(vw=>{"use strict";var yr=Ze(),pn=yw(),fc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),pc=e=>/^(%|---|\.\.\.)/m.test(e);function rx(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let o=0,s=0;o<i;++o)if(e[o]===`
15
+ `){if(o-s>n)return!0;if(s=o+1,i-s<=n)return!1}return!0}function ds(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(pc(e)?" ":""),s="",c=0;for(let u=0,f=r[u];f;f=r[++u])if(f===" "&&r[u+1]==="\\"&&r[u+2]==="n"&&(s+=r.slice(c,u)+"\\ ",u+=1,c=u,f="\\"),f==="\\")switch(r[u+1]){case"u":{s+=r.slice(c,u);let a=r.substr(u+2,4);switch(a){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:a.substr(0,2)==="00"?s+="\\x"+a.substr(2):s+=r.substr(u,6)}u+=5,c=u+1}break;case"n":if(n||r[u+2]==='"'||r.length<i)u+=1;else{for(s+=r.slice(c,u)+`
16
+
17
+ `;r[u+2]==="\\"&&r[u+3]==="n"&&r[u+4]!=='"';)s+=`
18
+ `,u+=2;s+=o,r[u+2]===" "&&(s+="\\"),u+=1,c=u+1}break;default:u+=1}return s=c?s+r.slice(c):r,n?s:pn.foldFlowLines(s,o,pn.FOLD_QUOTED,fc(t,!1))}function _d(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return ds(e,t);let r=t.indent||(pc(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return t.implicitKey?n:pn.foldFlowLines(n,r,pn.FOLD_FLOW,fc(t,!1))}function Zi(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=ds;else{let i=e.includes('"'),o=e.includes("'");i&&!o?n=_d:o&&!i?n=ds:n=r?_d:ds}return n(e,t)}var Ad;try{Ad=new RegExp(`(^|(?<!
21
+ ))
22
+ +(?!
23
+ |$)`,"g")}catch{Ad=/\n+(?!\n|$)/g}function dc({comment:e,type:t,value:r},n,i,o){let{blockQuote:s,commentString:c,lineWidth:u}=n.options;if(!s||/\n[\t ]+$/.test(r))return Zi(r,n);let f=n.indent||(n.forceBlockIndent||pc(r)?" ":""),a=s==="literal"?!0:s==="folded"||t===yr.Scalar.BLOCK_FOLDED?!1:t===yr.Scalar.BLOCK_LITERAL?!0:!rx(r,u,f.length);if(!r)return a?`|
24
+ `:`>
25
+ `;let d,p;for(p=r.length;p>0;--p){let E=r[p-1];if(E!==`
26
+ `&&E!==" "&&E!==" ")break}let l=r.substring(p),m=l.indexOf(`
27
+ `);m===-1?d="-":r===l||m!==l.length-1?(d="+",o&&o()):d="",l&&(r=r.slice(0,-l.length),l[l.length-1]===`
28
+ `&&(l=l.slice(0,-1)),l=l.replace(Ad,`$&${f}`));let h=!1,g,w=-1;for(g=0;g<r.length;++g){let E=r[g];if(E===" ")h=!0;else if(E===`
29
+ `)w=g;else break}let k=r.substring(0,w<g?w+1:g);k&&(r=r.substring(k.length),k=k.replace(/\n+/g,`$&${f}`));let S=(h?f?"2":"1":"")+d;if(e&&(S+=" "+c(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!a){let E=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${f}`),O=!1,K=fc(n,!0);s!=="folded"&&t!==yr.Scalar.BLOCK_FOLDED&&(K.onOverflow=()=>{O=!0});let D=pn.foldFlowLines(`${k}${E}${l}`,f,pn.FOLD_BLOCK,K);if(!O)return`>${S}
31
+ ${f}${D}`}return r=r.replace(/\n+/g,`$&${f}`),`|${S}
32
+ ${f}${k}${r}${l}`}function nx(e,t,r,n){let{type:i,value:o}=e,{actualString:s,implicitKey:c,indent:u,indentStep:f,inFlow:a}=t;if(c&&o.includes(`
33
+ `)||a&&/[[\]{},]/.test(o))return Zi(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return c||a||!o.includes(`
34
+ `)?Zi(o,t):dc(e,t,r,n);if(!c&&!a&&i!==yr.Scalar.PLAIN&&o.includes(`
35
+ `))return dc(e,t,r,n);if(pc(o)){if(u==="")return t.forceBlockIndent=!0,dc(e,t,r,n);if(c&&u===f)return Zi(o,t)}let d=o.replace(/\n+/g,`$&
36
+ ${u}`);if(s){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:l,tags:m}=t.doc.schema;if(m.some(p)||l?.some(p))return Zi(o,t)}return c?d:pn.foldFlowLines(d,u,pn.FOLD_FLOW,fc(t,!1))}function ix(e,t,r,n){let{implicitKey:i,inFlow:o}=t,s=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:c}=e;c!==yr.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(c=yr.Scalar.QUOTE_DOUBLE);let u=a=>{switch(a){case yr.Scalar.BLOCK_FOLDED:case yr.Scalar.BLOCK_LITERAL:return i||o?Zi(s.value,t):dc(s,t,r,n);case yr.Scalar.QUOTE_DOUBLE:return ds(s.value,t);case yr.Scalar.QUOTE_SINGLE:return _d(s.value,t);case yr.Scalar.PLAIN:return nx(s,t,r,n);default:return null}},f=u(c);if(f===null){let{defaultKeyType:a,defaultStringType:d}=t.options,p=i&&a||d;if(f=u(p),f===null)throw new Error(`Unsupported default string type ${p}`)}return f}vw.stringifyString=ix});var ps=A(xd=>{"use strict";var ox=ic(),mn=we(),sx=ls(),ax=fs();function cx(e,t){let r=Object.assign({blockQuote:!0,commentString:sx.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),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function lx(e,t){if(t.tag){let i=e.filter(o=>o.tag===t.tag);if(i.length>0)return i.find(o=>o.format===t.format)??i[0]}let r,n;if(mn.isScalar(t)){n=t.value;let i=e.filter(o=>o.identify?.(n));if(i.length>1){let o=i.filter(s=>s.test);o.length>0&&(i=o)}r=i.find(o=>o.format===t.format)??i.find(o=>!o.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function ux(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],o=(mn.isScalar(e)||mn.isCollection(e))&&e.anchor;o&&ox.anchorIsValid(o)&&(r.add(o),i.push(`&${o}`));let s=e.tag??(t.default?null:t.tag);return s&&i.push(n.directives.tagString(s)),i.join(" ")}function dx(e,t,r,n){if(mn.isPair(e))return e.toString(t,r,n);if(mn.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 i,o=mn.isNode(e)?e:t.doc.createNode(e,{onTagObj:u=>i=u});i??(i=lx(t.doc.schema.tags,o));let s=ux(o,i,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);let c=typeof i.stringify=="function"?i.stringify(o,t,r,n):mn.isScalar(o)?ax.stringifyString(o,t,r,n):o.toString(t,r,n);return s?mn.isScalar(o)||c[0]==="{"||c[0]==="["?`${s} ${c}`:`${s}
37
+ ${t.indent}${c}`:c}xd.createStringifyContext=cx;xd.stringify=dx});var Sw=A(Rw=>{"use strict";var Yr=we(),kw=Ze(),bw=ps(),ms=ls();function fx({key:e,value:t},r,n,i){let{allNullValues:o,doc:s,indent:c,indentStep:u,options:{commentString:f,indentSeq:a,simpleKeys:d}}=r,p=Yr.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Yr.isCollection(e)||!Yr.isNode(e)&&typeof e=="object"){let K="With simple keys, collection cannot be used as a key value";throw new Error(K)}}let l=!d&&(!e||p&&t==null&&!r.inFlow||Yr.isCollection(e)||(Yr.isScalar(e)?e.type===kw.Scalar.BLOCK_FOLDED||e.type===kw.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!l&&(d||!o),indent:c+u});let m=!1,h=!1,g=bw.stringify(e,r,()=>m=!0,()=>h=!0);if(!l&&!r.inFlow&&g.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(r.inFlow){if(o||t==null)return m&&n&&n(),g===""?"?":l?`? ${g}`:g}else if(o&&!d||t==null&&l)return g=`? ${g}`,p&&!m?g+=ms.lineComment(g,r.indent,f(p)):h&&i&&i(),g;m&&(p=null),l?(p&&(g+=ms.lineComment(g,r.indent,f(p))),g=`? ${g}
38
+ ${c}:`):(g=`${g}:`,p&&(g+=ms.lineComment(g,r.indent,f(p))));let w,k,b;Yr.isNode(t)?(w=!!t.spaceBefore,k=t.commentBefore,b=t.comment):(w=!1,k=null,b=null,t&&typeof t=="object"&&(t=s.createNode(t))),r.implicitKey=!1,!l&&!p&&Yr.isScalar(t)&&(r.indentAtStart=g.length+1),h=!1,!a&&u.length>=2&&!r.inFlow&&!l&&Yr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let S=!1,E=bw.stringify(t,r,()=>S=!0,()=>h=!0),O=" ";if(p||w||k){if(O=w?`
39
+ `:"",k){let K=f(k);O+=`
40
+ ${ms.indentComment(K,r.indent)}`}E===""&&!r.inFlow?O===`
41
+ `&&b&&(O=`
42
+
43
+ `):O+=`
44
+ ${r.indent}`}else if(!l&&Yr.isCollection(t)){let K=E[0],D=E.indexOf(`
45
+ `),Y=D!==-1,Q=r.inFlow??t.flow??t.items.length===0;if(Y||!Q){let te=!1;if(Y&&(K==="&"||K==="!")){let Z=E.indexOf(" ");K==="&"&&Z!==-1&&Z<D&&E[Z+1]==="!"&&(Z=E.indexOf(" ",Z+1)),(Z===-1||D<Z)&&(te=!0)}te||(O=`
46
+ ${r.indent}`)}}else(E===""||E[0]===`
47
+ `)&&(O="");return g+=O+E,r.inFlow?S&&n&&n():b&&!S?g+=ms.lineComment(g,r.indent,f(b)):h&&i&&i(),g}Rw.stringifyPair=fx});var Id=A(Pd=>{"use strict";var Cw=Qa("process");function px(e,...t){e==="debug"&&console.log(...t)}function mx(e,t){(e==="debug"||e==="warn")&&(typeof Cw.emitWarning=="function"?Cw.emitWarning(t):console.warn(t))}Pd.debug=px;Pd.warn=mx});var yc=A(wc=>{"use strict";var gc=we(),Ew=Ze(),mc="<<",hc={identify:e=>e===mc||typeof e=="symbol"&&e.description===mc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ew.Scalar(Symbol(mc)),{addToJSMap:_w}),stringify:()=>mc},hx=(e,t)=>(hc.identify(t)||gc.isScalar(t)&&(!t.type||t.type===Ew.Scalar.PLAIN)&&hc.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===hc.tag&&r.default);function _w(e,t,r){let n=Aw(e,r);if(gc.isSeq(n))for(let i of n.items)Od(e,t,i);else if(Array.isArray(n))for(let i of n)Od(e,t,i);else Od(e,t,n)}function Od(e,t,r){let n=Aw(e,r);if(!gc.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[o,s]of i)t instanceof Map?t.has(o)||t.set(o,s):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function Aw(e,t){return e&&gc.isAlias(t)?t.resolve(e.doc,e):t}wc.addMergeToJSMap=_w;wc.isMergeKey=hx;wc.merge=hc});var Td=A(Iw=>{"use strict";var gx=Id(),xw=yc(),wx=ps(),Pw=we(),Nd=dn();function yx(e,t,{key:r,value:n}){if(Pw.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(xw.isMergeKey(e,r))xw.addMergeToJSMap(e,t,n);else{let i=Nd.toJS(r,"",e);if(t instanceof Map)t.set(i,Nd.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let o=vx(r,i,e),s=Nd.toJS(n,o,e);o in t?Object.defineProperty(t,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[o]=s}}return t}function vx(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Pw.isNode(e)&&r?.doc){let n=wx.createStringifyContext(r.doc,{});n.anchors=new Set;for(let o of r.anchors.keys())n.anchors.add(o.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),gx.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}Iw.addPairToJSMap=yx});var hn=A($d=>{"use strict";var Ow=cs(),kx=Sw(),bx=Td(),vc=we();function Rx(e,t,r){let n=Ow.createNode(e,void 0,r),i=Ow.createNode(t,void 0,r);return new kc(n,i)}var kc=class e{constructor(t,r=null){Object.defineProperty(this,vc.NODE_TYPE,{value:vc.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return vc.isNode(r)&&(r=r.clone(t)),vc.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return bx.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?kx.stringifyPair(this,t,r,n):JSON.stringify(this)}};$d.Pair=kc;$d.createPair=Rx});var jd=A(Tw=>{"use strict";var Zn=we(),Nw=ps(),bc=ls();function Sx(e,t,r){return(t.inFlow??e.flow?Ex:Cx)(e,t,r)}function Cx({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:o,onChompKeep:s,onComment:c}){let{indent:u,options:{commentString:f}}=r,a=Object.assign({},r,{indent:o,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(Zn.isNode(h))!d&&h.spaceBefore&&p.push(""),Rc(r,p,h.commentBefore,d),h.comment&&(g=h.comment);else if(Zn.isPair(h)){let k=Zn.isNode(h.key)?h.key:null;k&&(!d&&k.spaceBefore&&p.push(""),Rc(r,p,k.commentBefore,d))}d=!1;let w=Nw.stringify(h,a,()=>g=null,()=>d=!0);g&&(w+=bc.lineComment(w,o,f(g))),d&&g&&(d=!1),p.push(n+w)}let l;if(p.length===0)l=i.start+i.end;else{l=p[0];for(let m=1;m<p.length;++m){let h=p[m];l+=h?`
48
+ ${u}${h}`:`
49
+ `}}return e?(l+=`
50
+ `+bc.indentComment(f(e),u),c&&c()):d&&s&&s(),l}function Ex({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:o,flowCollectionPadding:s,options:{commentString:c}}=t;n+=o;let u=Object.assign({},t,{indent:n,inFlow:!0,type:null}),f=!1,a=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(Zn.isNode(h))h.spaceBefore&&d.push(""),Rc(t,d,h.commentBefore,!1),h.comment&&(g=h.comment);else if(Zn.isPair(h)){let k=Zn.isNode(h.key)?h.key:null;k&&(k.spaceBefore&&d.push(""),Rc(t,d,k.commentBefore,!1),k.comment&&(f=!0));let b=Zn.isNode(h.value)?h.value:null;b?(b.comment&&(g=b.comment),b.commentBefore&&(f=!0)):h.value==null&&k?.comment&&(g=k.comment)}g&&(f=!0);let w=Nw.stringify(h,u,()=>g=null);f||(f=d.length>a||w.includes(`
51
+ `)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(f||(f=d.reduce((k,b)=>k+b.length+2,2)+(w.length+2)>t.options.lineWidth)),f&&(w+=",")),g&&(w+=bc.lineComment(w,n,c(g))),d.push(w),a=d.length}let{start:p,end:l}=r;if(d.length===0)return p+l;if(!f){let m=d.reduce((h,g)=>h+g.length+2,2);f=t.options.lineWidth>0&&m>t.options.lineWidth}if(f){let m=p;for(let h of d)m+=h?`
52
+ ${o}${i}${h}`:`
53
+ `;return`${m}
54
+ ${i}${l}`}else return`${p}${s}${d.join(" ")}${s}${l}`}function Rc({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let o=bc.indentComment(t(n),e);r.push(o.trimStart())}}Tw.stringifyCollection=Sx});var wn=A(qd=>{"use strict";var _x=jd(),Ax=Td(),xx=cc(),gn=we(),Sc=hn(),Px=Ze();function hs(e,t){let r=gn.isScalar(t)?t.value:t;for(let n of e)if(gn.isPair(n)&&(n.key===t||n.key===r||gn.isScalar(n.key)&&n.key.value===r))return n}var Dd=class extends xx.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(gn.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:o}=n,s=new this(t),c=(u,f)=>{if(typeof o=="function")f=o.call(r,u,f);else if(Array.isArray(o)&&!o.includes(u))return;(f!==void 0||i)&&s.items.push(Sc.createPair(u,f,n))};if(r instanceof Map)for(let[u,f]of r)c(u,f);else if(r&&typeof r=="object")for(let u of Object.keys(r))c(u,r[u]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,r){let n;gn.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Sc.Pair(t,t?.value):n=new Sc.Pair(t.key,t.value);let i=hs(this.items,n.key),o=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);gn.isScalar(i.value)&&Px.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(o){let s=this.items.findIndex(c=>o(n,c)<0);s===-1?this.items.push(n):this.items.splice(s,0,n)}else this.items.push(n)}delete(t){let r=hs(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=hs(this.items,t)?.value;return(!r&&gn.isScalar(i)?i.value:i)??void 0}has(t){return!!hs(this.items,t)}set(t,r){this.add(new Sc.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let o of this.items)Ax.addPairToJSMap(r,i,o);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!gn.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),_x.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};qd.YAMLMap=Dd;qd.findPair=hs});var eo=A(jw=>{"use strict";var Ix=we(),$w=wn(),Ox={collection:"map",default:!0,nodeClass:$w.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Ix.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>$w.YAMLMap.from(e,t,r)};jw.map=Ox});var yn=A(Dw=>{"use strict";var Nx=cs(),Tx=jd(),$x=cc(),Ec=we(),jx=Ze(),Dx=dn(),Ld=class extends $x.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ec.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Cc(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=Cc(t);if(typeof n!="number")return;let i=this.items[n];return!r&&Ec.isScalar(i)?i.value:i}has(t){let r=Cc(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=Cc(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];Ec.isScalar(i)&&jx.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let o of this.items)n.push(Dx.toJS(o,String(i++),r));return n}toString(t,r,n){return t?Tx.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,o=new this(t);if(r&&Symbol.iterator in Object(r)){let s=0;for(let c of r){if(typeof i=="function"){let u=r instanceof Set?c:String(s++);c=i.call(r,u,c)}o.items.push(Nx.createNode(c,void 0,n))}}return o}};function Cc(e){let t=Ec.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Dw.YAMLSeq=Ld});var to=A(Lw=>{"use strict";var qx=we(),qw=yn(),Lx={collection:"seq",default:!0,nodeClass:qw.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return qx.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>qw.YAMLSeq.from(e,t,r)};Lw.seq=Lx});var gs=A(Mw=>{"use strict";var Mx=fs(),Wx={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),Mx.stringifyString(e,t,r,n)}};Mw.string=Wx});var _c=A(Hw=>{"use strict";var Ww=Ze(),Fw={identify:e=>e==null,createNode:()=>new Ww.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ww.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Fw.test.test(e)?e:t.options.nullStr};Hw.nullTag=Fw});var Md=A(Bw=>{"use strict";var Fx=Ze(),Vw={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Fx.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Vw.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};Bw.boolTag=Vw});var ro=A(Uw=>{"use strict";function Hx({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let o=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let c=t-(o.length-s-1);for(;c-- >0;)o+="0"}return o}Uw.stringifyNumber=Hx});var Fd=A(Ac=>{"use strict";var Vx=Ze(),Wd=ro(),Bx={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:Wd.stringifyNumber},Ux={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():Wd.stringifyNumber(e)}},Kx={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 Vx.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Wd.stringifyNumber};Ac.float=Kx;Ac.floatExp=Ux;Ac.floatNaN=Bx});var Vd=A(Pc=>{"use strict";var Kw=ro(),xc=e=>typeof e=="bigint"||Number.isInteger(e),Hd=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function Jw(e,t,r){let{value:n}=e;return xc(n)&&n>=0?r+n.toString(t):Kw.stringifyNumber(e)}var Jx={identify:e=>xc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Hd(e,2,8,r),stringify:e=>Jw(e,8,"0o")},zx={identify:xc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Hd(e,0,10,r),stringify:Kw.stringifyNumber},Gx={identify:e=>xc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Hd(e,2,16,r),stringify:e=>Jw(e,16,"0x")};Pc.int=zx;Pc.intHex=Gx;Pc.intOct=Jx});var Gw=A(zw=>{"use strict";var Yx=eo(),Xx=_c(),Qx=to(),Zx=gs(),eP=Md(),Bd=Fd(),Ud=Vd(),tP=[Yx.map,Qx.seq,Zx.string,Xx.nullTag,eP.boolTag,Ud.intOct,Ud.int,Ud.intHex,Bd.floatNaN,Bd.floatExp,Bd.float];zw.schema=tP});var Qw=A(Xw=>{"use strict";var rP=Ze(),nP=eo(),iP=to();function Yw(e){return typeof e=="bigint"||Number.isInteger(e)}var Ic=({value:e})=>JSON.stringify(e),oP=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ic},{identify:e=>e==null,createNode:()=>new rP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ic},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ic},{identify:Yw,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})=>Yw(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Ic}],sP={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},aP=[nP.map,iP.seq].concat(oP,sP);Xw.schema=aP});var Jd=A(Zw=>{"use strict";var ws=Qa("buffer"),Kd=Ze(),cP=fs(),lP={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ws.Buffer=="function")return ws.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}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},n,i,o){if(!r)return"";let s=r,c;if(typeof ws.Buffer=="function")c=s instanceof ws.Buffer?s.toString("base64"):ws.Buffer.from(s.buffer).toString("base64");else if(typeof btoa=="function"){let u="";for(let f=0;f<s.length;++f)u+=String.fromCharCode(s[f]);c=btoa(u)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Kd.Scalar.BLOCK_LITERAL),t!==Kd.Scalar.QUOTE_DOUBLE){let u=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),f=Math.ceil(c.length/u),a=new Array(f);for(let d=0,p=0;d<f;++d,p+=u)a[d]=c.substr(p,u);c=a.join(t===Kd.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return cP.stringifyString({comment:e,type:t,value:c},n,i,o)}};Zw.binary=lP});var Tc=A(Nc=>{"use strict";var Oc=we(),zd=hn(),uP=Ze(),dP=yn();function ey(e,t){if(Oc.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!Oc.isPair(n)){if(Oc.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new zd.Pair(new uP.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
56
+ ${i.key.commentBefore}`:n.commentBefore),n.comment){let o=i.value??i.key;o.comment=o.comment?`${n.comment}
57
+ ${o.comment}`:n.comment}n=i}e.items[r]=Oc.isPair(n)?n:new zd.Pair(n)}}else t("Expected a sequence for this tag");return e}function ty(e,t,r){let{replacer:n}=r,i=new dP.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let s of t){typeof n=="function"&&(s=n.call(t,String(o++),s));let c,u;if(Array.isArray(s))if(s.length===2)c=s[0],u=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let f=Object.keys(s);if(f.length===1)c=f[0],u=s[c];else throw new TypeError(`Expected tuple with one key, not ${f.length} keys`)}else c=s;i.items.push(zd.createPair(c,u,r))}return i}var fP={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ey,createNode:ty};Nc.createPairs=ty;Nc.pairs=fP;Nc.resolvePairs=ey});var Xd=A(Yd=>{"use strict";var ry=we(),Gd=dn(),ys=wn(),pP=yn(),ny=Tc(),ei=class e extends pP.YAMLSeq{constructor(){super(),this.add=ys.YAMLMap.prototype.add.bind(this),this.delete=ys.YAMLMap.prototype.delete.bind(this),this.get=ys.YAMLMap.prototype.get.bind(this),this.has=ys.YAMLMap.prototype.has.bind(this),this.set=ys.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let o,s;if(ry.isPair(i)?(o=Gd.toJS(i.key,"",r),s=Gd.toJS(i.value,o,r)):o=Gd.toJS(i,"",r),n.has(o))throw new Error("Ordered maps must not include duplicate keys");n.set(o,s)}return n}static from(t,r,n){let i=ny.createPairs(t,r,n),o=new this;return o.items=i.items,o}};ei.tag="tag:yaml.org,2002:omap";var mP={collection:"seq",identify:e=>e instanceof Map,nodeClass:ei,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=ny.resolvePairs(e,t),n=[];for(let{key:i}of r.items)ry.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ei,r)},createNode:(e,t,r)=>ei.from(e,t,r)};Yd.YAMLOMap=ei;Yd.omap=mP});var cy=A(Qd=>{"use strict";var iy=Ze();function oy({value:e,source:t},r){return t&&(e?sy:ay).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var sy={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 iy.Scalar(!0),stringify:oy},ay={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 iy.Scalar(!1),stringify:oy};Qd.falseTag=ay;Qd.trueTag=sy});var ly=A($c=>{"use strict";var hP=Ze(),Zd=ro(),gP={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:Zd.stringifyNumber},wP={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():Zd.stringifyNumber(e)}},yP={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 hP.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:Zd.stringifyNumber};$c.float=yP;$c.floatExp=wP;$c.floatNaN=gP});var dy=A(ks=>{"use strict";var uy=ro(),vs=e=>typeof e=="bigint"||Number.isInteger(e);function jc(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let s=BigInt(e);return i==="-"?BigInt(-1)*s:s}let o=parseInt(e,r);return i==="-"?-1*o:o}function ef(e,t,r){let{value:n}=e;if(vs(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return uy.stringifyNumber(e)}var vP={identify:vs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>jc(e,2,2,r),stringify:e=>ef(e,2,"0b")},kP={identify:vs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>jc(e,1,8,r),stringify:e=>ef(e,8,"0")},bP={identify:vs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>jc(e,0,10,r),stringify:uy.stringifyNumber},RP={identify:vs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>jc(e,2,16,r),stringify:e=>ef(e,16,"0x")};ks.int=bP;ks.intBin=vP;ks.intHex=RP;ks.intOct=kP});var rf=A(tf=>{"use strict";var Lc=we(),Dc=hn(),qc=wn(),ti=class e extends qc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Lc.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Dc.Pair(t.key,null):r=new Dc.Pair(t,null),qc.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=qc.findPair(this.items,t);return!r&&Lc.isPair(n)?Lc.isScalar(n.key)?n.key.value:n.key:n}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 n=qc.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new Dc.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,o=new this(t);if(r&&Symbol.iterator in Object(r))for(let s of r)typeof i=="function"&&(s=i.call(r,s,s)),o.items.push(Dc.createPair(s,null,n));return o}};ti.tag="tag:yaml.org,2002:set";var SP={collection:"map",identify:e=>e instanceof Set,nodeClass:ti,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>ti.from(e,t,r),resolve(e,t){if(Lc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ti,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};tf.YAMLSet=ti;tf.set=SP});var of=A(Mc=>{"use strict";var CP=ro();function nf(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=s=>t?BigInt(s):Number(s),o=n.replace(/_/g,"").split(":").reduce((s,c)=>s*i(60)+i(c),i(0));return r==="-"?i(-1)*o:o}function fy(e){let{value:t}=e,r=s=>s;if(typeof t=="bigint")r=s=>BigInt(s);else if(isNaN(t)||!isFinite(t))return CP.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),o=[t%i];return t<60?o.unshift(0):(t=(t-o[0])/i,o.unshift(t%i),t>=60&&(t=(t-o[0])/i,o.unshift(t))),n+o.map(s=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var EP={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})=>nf(e,r),stringify:fy},_P={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=>nf(e,!1),stringify:fy},py={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(py.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,o,s,c]=t.map(Number),u=t[7]?Number((t[7]+"00").substr(1,3)):0,f=Date.UTC(r,n-1,i,o||0,s||0,c||0,u),a=t[8];if(a&&a!=="Z"){let d=nf(a,!1);Math.abs(d)<30&&(d*=60),f-=6e4*d}return new Date(f)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Mc.floatTime=_P;Mc.intTime=EP;Mc.timestamp=py});var gy=A(hy=>{"use strict";var AP=eo(),xP=_c(),PP=to(),IP=gs(),OP=Jd(),my=cy(),sf=ly(),Wc=dy(),NP=yc(),TP=Xd(),$P=Tc(),jP=rf(),af=of(),DP=[AP.map,PP.seq,IP.string,xP.nullTag,my.trueTag,my.falseTag,Wc.intBin,Wc.intOct,Wc.int,Wc.intHex,sf.floatNaN,sf.floatExp,sf.float,OP.binary,NP.merge,TP.omap,$P.pairs,jP.set,af.intTime,af.floatTime,af.timestamp];hy.schema=DP});var _y=A(uf=>{"use strict";var ky=eo(),qP=_c(),by=to(),LP=gs(),MP=Md(),cf=Fd(),lf=Vd(),WP=Gw(),FP=Qw(),Ry=Jd(),bs=yc(),Sy=Xd(),Cy=Tc(),wy=gy(),Ey=rf(),Fc=of(),yy=new Map([["core",WP.schema],["failsafe",[ky.map,by.seq,LP.string]],["json",FP.schema],["yaml11",wy.schema],["yaml-1.1",wy.schema]]),vy={binary:Ry.binary,bool:MP.boolTag,float:cf.float,floatExp:cf.floatExp,floatNaN:cf.floatNaN,floatTime:Fc.floatTime,int:lf.int,intHex:lf.intHex,intOct:lf.intOct,intTime:Fc.intTime,map:ky.map,merge:bs.merge,null:qP.nullTag,omap:Sy.omap,pairs:Cy.pairs,seq:by.seq,set:Ey.set,timestamp:Fc.timestamp},HP={"tag:yaml.org,2002:binary":Ry.binary,"tag:yaml.org,2002:merge":bs.merge,"tag:yaml.org,2002:omap":Sy.omap,"tag:yaml.org,2002:pairs":Cy.pairs,"tag:yaml.org,2002:set":Ey.set,"tag:yaml.org,2002:timestamp":Fc.timestamp};function VP(e,t,r){let n=yy.get(t);if(n&&!e)return r&&!n.includes(bs.merge)?n.concat(bs.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let o=Array.from(yy.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)i=i.concat(o);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(bs.merge)),i.reduce((o,s)=>{let c=typeof s=="string"?vy[s]:s;if(!c){let u=JSON.stringify(s),f=Object.keys(vy).map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown custom tag ${u}; use one of ${f}`)}return o.includes(c)||o.push(c),o},[])}uf.coreKnownTags=HP;uf.getTags=VP});var pf=A(Ay=>{"use strict";var df=we(),BP=eo(),UP=to(),KP=gs(),Hc=_y(),JP=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ff=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:o,sortMapEntries:s,toStringDefaults:c}){this.compat=Array.isArray(t)?Hc.getTags(t,"compat"):t?Hc.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?Hc.coreKnownTags:{},this.tags=Hc.getTags(r,this.name,n),this.toStringOptions=c??null,Object.defineProperty(this,df.MAP,{value:BP.map}),Object.defineProperty(this,df.SCALAR,{value:KP.string}),Object.defineProperty(this,df.SEQ,{value:UP.seq}),this.sortMapEntries=typeof s=="function"?s:s===!0?JP:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ay.Schema=ff});var Py=A(xy=>{"use strict";var zP=we(),mf=ps(),Rs=ls();function GP(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let u=e.directives.toString(e);u?(r.push(u),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=mf.createStringifyContext(e,t),{commentString:o}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let u=o(e.commentBefore);r.unshift(Rs.indentComment(u,""))}let s=!1,c=null;if(e.contents){if(zP.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let a=o(e.contents.commentBefore);r.push(Rs.indentComment(a,""))}i.forceBlockIndent=!!e.comment,c=e.contents.comment}let u=c?void 0:()=>s=!0,f=mf.stringify(e.contents,i,()=>c=null,u);c&&(f+=Rs.lineComment(f,"",o(c))),(f[0]==="|"||f[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${f}`:r.push(f)}else r.push(mf.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let u=o(e.comment);u.includes(`
58
+ `)?(r.push("..."),r.push(Rs.indentComment(u,""))):r.push(`... ${u}`)}else r.push("...");else{let u=e.comment;u&&s&&(u=u.replace(/^\n+/,"")),u&&((!s||c)&&r[r.length-1]!==""&&r.push(""),r.push(Rs.indentComment(o(u),"")))}return r.join(`
59
+ `)+`
60
+ `}xy.stringifyDocument=GP});var Ss=A(Iy=>{"use strict";var YP=as(),no=cc(),er=we(),XP=hn(),QP=dn(),ZP=pf(),eI=Py(),hf=ic(),tI=yd(),rI=cs(),gf=wd(),wf=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,er.NODE_TYPE,{value:er.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=o;let{version:s}=o;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new gf.Directives({version:s}),this.setSchema(s,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[er.NODE_TYPE]:{value:er.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=er.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){io(this.contents)&&this.contents.add(t)}addIn(t,r){io(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=hf.anchorNames(this);t.anchor=!r||n.has(r)?hf.findNewAnchor(r||"a",n):r}return new YP.Alias(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let g=k=>typeof k=="number"||k instanceof String||k instanceof Number,w=r.filter(g).map(String);w.length>0&&(r=r.concat(w)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:o,anchorPrefix:s,flow:c,keepUndefined:u,onTagObj:f,tag:a}=n??{},{onAnchor:d,setAnchors:p,sourceObjects:l}=hf.createNodeAnchors(this,s||"a"),m={aliasDuplicateObjects:o??!0,keepUndefined:u??!1,onAnchor:d,onTagObj:f,replacer:i,schema:this.schema,sourceObjects:l},h=rI.createNode(t,a,m);return c&&er.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,r,n={}){let i=this.createNode(t,null,n),o=this.createNode(r,null,n);return new XP.Pair(i,o)}delete(t){return io(this.contents)?this.contents.delete(t):!1}deleteIn(t){return no.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):io(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return er.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return no.isEmptyPath(t)?!r&&er.isScalar(this.contents)?this.contents.value:this.contents:er.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return er.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return no.isEmptyPath(t)?this.contents!==void 0:er.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=no.collectionFromPath(this.schema,[t],r):io(this.contents)&&this.contents.set(t,r)}setIn(t,r){no.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=no.collectionFromPath(this.schema,Array.from(t),r):io(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new gf.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new gf.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new ZP.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:o,reviver:s}={}){let c={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},u=QP.toJS(this.contents,r??"",c);if(typeof o=="function")for(let{count:f,res:a}of c.anchors.values())o(a,f);return typeof s=="function"?tI.applyReviver(s,{"":u},"",u):u}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 eI.stringifyDocument(this,t)}};function io(e){if(er.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Iy.Document=wf});var _s=A(Es=>{"use strict";var Cs=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},yf=class extends Cs{constructor(t,r,n){super("YAMLParseError",t,r,n)}},vf=class extends Cs{constructor(t,r,n){super("YAMLWarning",t,r,n)}},nI=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(c=>t.linePos(c));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let o=i-1,s=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(o>=60&&s.length>80){let c=Math.min(o-39,s.length-79);s="…"+s.substring(c),o-=c-1}if(s.length>80&&(s=s.substring(0,79)+"…"),n>1&&/^ *$/.test(s.substring(0,o))){let c=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);c.length>80&&(c=c.substring(0,79)+`…
61
+ `),s=c+s}if(/[^ ]/.test(s)){let c=1,u=r.linePos[1];u?.line===n&&u.col>i&&(c=Math.max(1,Math.min(u.col-i,80-o)));let f=" ".repeat(o)+"^".repeat(c);r.message+=`:
62
+
63
+ ${s}
64
+ ${f}
65
+ `}};Es.YAMLError=Cs;Es.YAMLParseError=yf;Es.YAMLWarning=vf;Es.prettifyError=nI});var As=A(Oy=>{"use strict";function iI(e,{flow:t,indicator:r,next:n,offset:i,onError:o,parentIndent:s,startOnNewline:c}){let u=!1,f=c,a=c,d="",p="",l=!1,m=!1,h=null,g=null,w=null,k=null,b=null,S=null,E=null;for(let D of e)switch(m&&(D.type!=="space"&&D.type!=="newline"&&D.type!=="comma"&&o(D.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(f&&D.type!=="comment"&&D.type!=="newline"&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),D.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&D.source.includes(" ")&&(h=D),a=!0;break;case"comment":{a||o(D,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let Y=D.source.substring(1)||" ";d?d+=p+Y:d=Y,p="",f=!1;break}case"newline":f?d?d+=D.source:(!S||r!=="seq-item-ind")&&(u=!0):p+=D.source,f=!0,l=!0,(g||w)&&(k=D),a=!0;break;case"anchor":g&&o(D,"MULTIPLE_ANCHORS","A node can have at most one anchor"),D.source.endsWith(":")&&o(D.offset+D.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=D,E??(E=D.offset),f=!1,a=!1,m=!0;break;case"tag":{w&&o(D,"MULTIPLE_TAGS","A node can have at most one tag"),w=D,E??(E=D.offset),f=!1,a=!1,m=!0;break}case r:(g||w)&&o(D,"BAD_PROP_ORDER",`Anchors and tags must be after the ${D.source} indicator`),S&&o(D,"UNEXPECTED_TOKEN",`Unexpected ${D.source} in ${t??"collection"}`),S=D,f=r==="seq-item-ind"||r==="explicit-key-ind",a=!1;break;case"comma":if(t){b&&o(D,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=D,f=!1,a=!1;break}default:o(D,"UNEXPECTED_TOKEN",`Unexpected ${D.type} token`),f=!1,a=!1}let O=e[e.length-1],K=O?O.offset+O.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&o(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(f&&h.indent<=s||n?.type==="block-map"||n?.type==="block-seq")&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:S,spaceBefore:u,comment:d,hasNewline:l,anchor:g,tag:w,newlineAfterProp:k,end:K,start:E??K}}Oy.resolveProps=iI});var Vc=A(Ny=>{"use strict";function kf(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(kf(t.key)||kf(t.value))return!0}return!1;default:return!0}}Ny.containsNewline=kf});var bf=A(Ty=>{"use strict";var oI=Vc();function sI(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&oI.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ty.flowIndentCheck=sI});var Rf=A(jy=>{"use strict";var $y=we();function aI(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(o,s)=>o===s||$y.isScalar(o)&&$y.isScalar(s)&&o.value===s.value;return t.some(o=>i(o.key,r))}jy.mapIncludes=aI});var Fy=A(Wy=>{"use strict";var Dy=hn(),cI=wn(),qy=As(),lI=Vc(),Ly=bf(),uI=Rf(),My="All mapping items must start at the same column";function dI({composeNode:e,composeEmptyNode:t},r,n,i,o){let s=o?.nodeClass??cI.YAMLMap,c=new s(r.schema);r.atRoot&&(r.atRoot=!1);let u=n.offset,f=null;for(let a of n.items){let{start:d,key:p,sep:l,value:m}=a,h=qy.resolveProps(d,{indicator:"explicit-key-ind",next:p??l?.[0],offset:u,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!h.found;if(g){if(p&&(p.type==="block-seq"?i(u,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&i(u,"BAD_INDENT",My)),!h.anchor&&!h.tag&&!l){f=h.end,h.comment&&(c.comment?c.comment+=`
67
+ `+h.comment:c.comment=h.comment);continue}(h.newlineAfterProp||lI.containsNewline(p))&&i(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(u,"BAD_INDENT",My);r.atKey=!0;let w=h.end,k=p?e(r,p,h,i):t(r,w,d,null,h,i);r.schema.compat&&Ly.flowIndentCheck(n.indent,p,i),r.atKey=!1,uI.mapIncludes(r,c.items,k)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let b=qy.resolveProps(l??[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(u=b.end,b.found){g&&(m?.type==="block-map"&&!b.hasNewline&&i(u,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<b.found.offset-1024&&i(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=m?e(r,m,b,i):t(r,u,l,null,b,i);r.schema.compat&&Ly.flowIndentCheck(n.indent,m,i),u=S.range[2];let E=new Dy.Pair(k,S);r.options.keepSourceTokens&&(E.srcToken=a),c.items.push(E)}else{g&&i(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(k.comment?k.comment+=`
68
+ `+b.comment:k.comment=b.comment);let S=new Dy.Pair(k);r.options.keepSourceTokens&&(S.srcToken=a),c.items.push(S)}}return f&&f<u&&i(f,"IMPOSSIBLE","Map comment with trailing content"),c.range=[n.offset,u,f??u],c}Wy.resolveBlockMap=dI});var Vy=A(Hy=>{"use strict";var fI=yn(),pI=As(),mI=bf();function hI({composeNode:e,composeEmptyNode:t},r,n,i,o){let s=o?.nodeClass??fI.YAMLSeq,c=new s(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=n.offset,f=null;for(let{start:a,value:d}of n.items){let p=pI.resolveProps(a,{indicator:"seq-item-ind",next:d,offset:u,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?i(p.end,"BAD_INDENT","All sequence items must start at the same column"):i(u,"MISSING_CHAR","Sequence item without - indicator");else{f=p.end,p.comment&&(c.comment=p.comment);continue}let l=d?e(r,d,p,i):t(r,p.end,a,null,p,i);r.schema.compat&&mI.flowIndentCheck(n.indent,d,i),u=l.range[2],c.items.push(l)}return c.range=[n.offset,u,f??u],c}Hy.resolveBlockSeq=hI});var oo=A(By=>{"use strict";function gI(e,t,r,n){let i="";if(e){let o=!1,s="";for(let c of e){let{source:u,type:f}=c;switch(f){case"space":o=!0;break;case"comment":{r&&!o&&n(c,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let a=u.substring(1)||" ";i?i+=s+a:i=a,s="";break}case"newline":i&&(s+=u),o=!0;break;default:n(c,"UNEXPECTED_TOKEN",`Unexpected ${f} at node end`)}t+=u.length}}return{comment:i,offset:t}}By.resolveEnd=gI});var zy=A(Jy=>{"use strict";var wI=we(),yI=hn(),Uy=wn(),vI=yn(),kI=oo(),Ky=As(),bI=Vc(),RI=Rf(),Sf="Block collections are not allowed within flow collections",Cf=e=>e&&(e.type==="block-map"||e.type==="block-seq");function SI({composeNode:e,composeEmptyNode:t},r,n,i,o){let s=n.start.source==="{",c=s?"flow map":"flow sequence",u=o?.nodeClass??(s?Uy.YAMLMap:vI.YAMLSeq),f=new u(r.schema);f.flow=!0;let a=r.atRoot;a&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let w=n.items[g],{start:k,key:b,sep:S,value:E}=w,O=Ky.resolveProps(k,{flow:c,indicator:"explicit-key-ind",next:b??S?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!S&&!E){g===0&&O.comma?i(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`):g<n.items.length-1&&i(O.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${c}`),O.comment&&(f.comment?f.comment+=`
69
+ `+O.comment:f.comment=O.comment),d=O.end;continue}!s&&r.options.strict&&bI.containsNewline(b)&&i(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)O.comma&&i(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`);else if(O.comma||i(O.start,"MISSING_CHAR",`Missing , between ${c} items`),O.comment){let K="";e:for(let D of k)switch(D.type){case"comma":case"space":break;case"comment":K=D.source.substring(1);break e;default:break e}if(K){let D=f.items[f.items.length-1];wI.isPair(D)&&(D=D.value??D.key),D.comment?D.comment+=`
70
+ `+K:D.comment=K,O.comment=O.comment.substring(K.length+1)}}if(!s&&!S&&!O.found){let K=E?e(r,E,O,i):t(r,O.end,S,null,O,i);f.items.push(K),d=K.range[2],Cf(E)&&i(K.range,"BLOCK_IN_FLOW",Sf)}else{r.atKey=!0;let K=O.end,D=b?e(r,b,O,i):t(r,K,k,null,O,i);Cf(b)&&i(D.range,"BLOCK_IN_FLOW",Sf),r.atKey=!1;let Y=Ky.resolveProps(S??[],{flow:c,indicator:"map-value-ind",next:E,offset:D.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(Y.found){if(!s&&!O.found&&r.options.strict){if(S)for(let Z of S){if(Z===Y.found)break;if(Z.type==="newline"){i(Z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}O.start<Y.found.offset-1024&&i(Y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?i(E,"MISSING_CHAR",`Missing space after : in ${c}`):i(Y.start,"MISSING_CHAR",`Missing , or : between ${c} items`));let Q=E?e(r,E,Y,i):Y.found?t(r,Y.end,S,null,Y,i):null;Q?Cf(E)&&i(Q.range,"BLOCK_IN_FLOW",Sf):Y.comment&&(D.comment?D.comment+=`
71
+ `+Y.comment:D.comment=Y.comment);let te=new yI.Pair(D,Q);if(r.options.keepSourceTokens&&(te.srcToken=w),s){let Z=f;RI.mapIncludes(r,Z.items,D)&&i(K,"DUPLICATE_KEY","Map keys must be unique"),Z.items.push(te)}else{let Z=new Uy.YAMLMap(r.schema);Z.flow=!0,Z.items.push(te);let Pe=(Q??D).range;Z.range=[D.range[0],Pe[1],Pe[2]],f.items.push(Z)}d=Q?Q.range[2]:Y.end}}let p=s?"}":"]",[l,...m]=n.end,h=d;if(l?.source===p)h=l.offset+l.source.length;else{let g=c[0].toUpperCase()+c.substring(1),w=a?`${g} must end with a ${p}`:`${g} in block collection must be sufficiently indented and end with a ${p}`;i(d,a?"MISSING_CHAR":"BAD_INDENT",w),l&&l.source.length!==1&&m.unshift(l)}if(m.length>0){let g=kI.resolveEnd(m,h,r.options.strict,i);g.comment&&(f.comment?f.comment+=`
72
+ `+g.comment:f.comment=g.comment),f.range=[n.offset,h,g.offset]}else f.range=[n.offset,h,h];return f}Jy.resolveFlowCollection=SI});var Yy=A(Gy=>{"use strict";var CI=we(),EI=Ze(),_I=wn(),AI=yn(),xI=Fy(),PI=Vy(),II=zy();function Ef(e,t,r,n,i,o){let s=r.type==="block-map"?xI.resolveBlockMap(e,t,r,n,o):r.type==="block-seq"?PI.resolveBlockSeq(e,t,r,n,o):II.resolveFlowCollection(e,t,r,n,o),c=s.constructor;return i==="!"||i===c.tagName?(s.tag=c.tagName,s):(i&&(s.tag=i),s)}function OI(e,t,r,n,i){let o=n.tag,s=o?t.directives.tagName(o.source,p=>i(o,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:l}=n,m=p&&o?p.offset>o.offset?p:o:p??o;m&&(!l||l.offset<m.offset)&&i(m,"MISSING_CHAR","Missing newline after block sequence props")}let c=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!o||!s||s==="!"||s===_I.YAMLMap.tagName&&c==="map"||s===AI.YAMLSeq.tagName&&c==="seq")return Ef(e,t,r,i,s);let u=t.schema.tags.find(p=>p.tag===s&&p.collection===c);if(!u){let p=t.schema.knownTags[s];if(p?.collection===c)t.schema.tags.push(Object.assign({},p,{default:!1})),u=p;else return p?i(o,"BAD_COLLECTION_TYPE",`${p.tag} used for ${c} collection, but expects ${p.collection??"scalar"}`,!0):i(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),Ef(e,t,r,i,s)}let f=Ef(e,t,r,i,s,u),a=u.resolve?.(f,p=>i(o,"TAG_RESOLVE_FAILED",p),t.options)??f,d=CI.isNode(a)?a:new EI.Scalar(a);return d.range=f.range,d.tag=s,u?.format&&(d.format=u.format),d}Gy.composeCollection=OI});var Af=A(Xy=>{"use strict";var _f=Ze();function NI(e,t,r){let n=t.offset,i=TI(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let o=i.mode===">"?_f.Scalar.BLOCK_FOLDED:_f.Scalar.BLOCK_LITERAL,s=t.source?$I(t.source):[],c=s.length;for(let h=s.length-1;h>=0;--h){let g=s[h][1];if(g===""||g==="\r")c=h;else break}if(c===0){let h=i.chomp==="+"&&s.length>0?`
73
+ `.repeat(Math.max(1,s.length-1)):"",g=n+i.length;return t.source&&(g+=t.source.length),{value:h,type:o,comment:i.comment,range:[n,g,g]}}let u=t.indent+i.indent,f=t.offset+i.length,a=0;for(let h=0;h<c;++h){let[g,w]=s[h];if(w===""||w==="\r")i.indent===0&&g.length>u&&(u=g.length);else{g.length<u&&r(f+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(u=g.length),a=h,u===0&&!e.atRoot&&r(f,"BAD_INDENT","Block scalar values in collections must be indented");break}f+=g.length+w.length+1}for(let h=s.length-1;h>=c;--h)s[h][0].length>u&&(c=h+1);let d="",p="",l=!1;for(let h=0;h<a;++h)d+=s[h][0].slice(u)+`
74
+ `;for(let h=a;h<c;++h){let[g,w]=s[h];f+=g.length+w.length+1;let k=w[w.length-1]==="\r";if(k&&(w=w.slice(0,-1)),w&&g.length<u){let S=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(f-w.length-(k?2:1),"BAD_INDENT",S),g=""}o===_f.Scalar.BLOCK_LITERAL?(d+=p+g.slice(u)+w,p=`
75
+ `):g.length>u||w[0]===" "?(p===" "?p=`
76
+ `:!l&&p===`
77
+ `&&(p=`
78
+
79
+ `),d+=p+g.slice(u)+w,p=`
80
+ `,l=!0):w===""?p===`
81
+ `?d+=`
82
+ `:p=`
83
+ `:(d+=p+w,p=" ",l=!1)}switch(i.chomp){case"-":break;case"+":for(let h=c;h<s.length;++h)d+=`
84
+ `+s[h][0].slice(u);d[d.length-1]!==`
85
+ `&&(d+=`
86
+ `);break;default:d+=`
87
+ `}let m=n+i.length+t.source.length;return{value:d,type:o,comment:i.comment,range:[n,m,m]}}function TI({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],o=i[0],s=0,c="",u=-1;for(let p=1;p<i.length;++p){let l=i[p];if(!c&&(l==="-"||l==="+"))c=l;else{let m=Number(l);!s&&m?s=m:u===-1&&(u=e+p)}}u!==-1&&n(u,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let f=!1,a="",d=i.length;for(let p=1;p<t.length;++p){let l=t[p];switch(l.type){case"space":f=!0;case"newline":d+=l.source.length;break;case"comment":r&&!f&&n(l,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=l.source.length,a=l.source.substring(1);break;case"error":n(l,"UNEXPECTED_TOKEN",l.message),d+=l.source.length;break;default:{let m=`Unexpected token in block scalar header: ${l.type}`;n(l,"UNEXPECTED_TOKEN",m);let h=l.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:o,indent:s,chomp:c,comment:a,length:d}}function $I(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),o=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let s=1;s<t.length;s+=2)o.push([t[s],t[s+1]]);return o}Xy.resolveBlockScalar=NI});var Pf=A(Zy=>{"use strict";var xf=Ze(),jI=oo();function DI(e,t,r){let{offset:n,type:i,source:o,end:s}=e,c,u,f=(p,l,m)=>r(n+p,l,m);switch(i){case"scalar":c=xf.Scalar.PLAIN,u=qI(o,f);break;case"single-quoted-scalar":c=xf.Scalar.QUOTE_SINGLE,u=LI(o,f);break;case"double-quoted-scalar":c=xf.Scalar.QUOTE_DOUBLE,u=MI(o,f);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+o.length,n+o.length]}}let a=n+o.length,d=jI.resolveEnd(s,a,t,r);return{value:u,type:c,comment:d.comment,range:[n,a,d.offset]}}function qI(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}`),Qy(e)}function LI(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Qy(e.slice(1,-1)).replace(/''/g,"'")}function Qy(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
+ `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
+ `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],o=" ",s=t.lastIndex;for(r.lastIndex=s;n=r.exec(e);)n[1]===""?o===`
90
+ `?i+=o:o=`
91
+ `:(i+=o+n[1],o=" "),s=r.lastIndex;let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),i+o+(n?.[1]??"")}function MI(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
92
+ `))if(i===`
93
+ `){let{fold:o,offset:s}=WI(e,n);r+=o,n=s}else if(i==="\\"){let o=e[++n],s=FI[o];if(s)r+=s;else if(o===`
94
+ `)for(o=e[n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="\r"&&e[n+1]===`
95
+ `)for(o=e[++n+1];o===" "||o===" ";)o=e[++n+1];else if(o==="x"||o==="u"||o==="U"){let c=o==="x"?2:o==="u"?4:8;r+=HI(e,n+1,c,t),n+=c}else{let c=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),r+=c}}else if(i===" "||i===" "){let o=n,s=e[n+1];for(;s===" "||s===" ";)s=e[++n+1];s!==`
96
+ `&&!(s==="\r"&&e[n+2]===`
97
+ `)&&(r+=n>o?e.slice(o,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function WI(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
98
+ `||n==="\r")&&!(n==="\r"&&e[t+2]!==`
99
+ `);)n===`
100
+ `&&(r+=`
101
+ `),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var FI={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function HI(e,t,r,n){let i=e.substr(t,r),s=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(s)}catch{let c=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}Zy.resolveFlowScalar=DI});var rv=A(tv=>{"use strict";var ri=we(),ev=Ze(),VI=Af(),BI=Pf();function UI(e,t,r,n){let{value:i,type:o,comment:s,range:c}=t.type==="block-scalar"?VI.resolveBlockScalar(e,t,n):BI.resolveFlowScalar(t,e.options.strict,n),u=r?e.directives.tagName(r.source,d=>n(r,"TAG_RESOLVE_FAILED",d)):null,f;e.options.stringKeys&&e.atKey?f=e.schema[ri.SCALAR]:u?f=KI(e.schema,i,u,r,n):t.type==="scalar"?f=JI(e,i,t,n):f=e.schema[ri.SCALAR];let a;try{let d=f.resolve(i,p=>n(r??t,"TAG_RESOLVE_FAILED",p),e.options);a=ri.isScalar(d)?d:new ev.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);n(r??t,"TAG_RESOLVE_FAILED",p),a=new ev.Scalar(i)}return a.range=c,a.source=i,o&&(a.type=o),u&&(a.tag=u),f.format&&(a.format=f.format),s&&(a.comment=s),a}function KI(e,t,r,n,i){if(r==="!")return e[ri.SCALAR];let o=[];for(let c of e.tags)if(!c.collection&&c.tag===r)if(c.default&&c.test)o.push(c);else return c;for(let c of o)if(c.test?.test(t))return c;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[ri.SCALAR])}function JI({atKey:e,directives:t,schema:r},n,i,o){let s=r.tags.find(c=>(c.default===!0||e&&c.default==="key")&&c.test?.test(n))||r[ri.SCALAR];if(r.compat){let c=r.compat.find(u=>u.default&&u.test?.test(n))??r[ri.SCALAR];if(s.tag!==c.tag){let u=t.tagString(s.tag),f=t.tagString(c.tag),a=`Value may be parsed as either ${u} or ${f}`;o(i,"TAG_RESOLVE_FAILED",a,!0)}}return s}tv.composeScalar=UI});var iv=A(nv=>{"use strict";function zI(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}nv.emptyScalarPosition=zI});var av=A(Of=>{"use strict";var GI=as(),YI=we(),XI=Yy(),ov=rv(),QI=oo(),ZI=iv(),eO={composeNode:sv,composeEmptyNode:If};function sv(e,t,r,n){let i=e.atKey,{spaceBefore:o,comment:s,anchor:c,tag:u}=r,f,a=!0;switch(t.type){case"alias":f=tO(e,t,n),(c||u)&&n(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":f=ov.composeScalar(e,t,u,n),c&&(f.anchor=c.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{f=XI.composeCollection(eO,e,t,r,n),c&&(f.anchor=c.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);n(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",d),a=!1}}return f??(f=If(e,t.offset,void 0,null,r,n)),c&&f.anchor===""&&n(c,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!YI.isScalar(f)||typeof f.value!="string"||f.tag&&f.tag!=="tag:yaml.org,2002:str")&&n(u??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(f.spaceBefore=!0),s&&(t.type==="scalar"&&t.source===""?f.comment=s:f.commentBefore=s),e.options.keepSourceTokens&&a&&(f.srcToken=t),f}function If(e,t,r,n,{spaceBefore:i,comment:o,anchor:s,tag:c,end:u},f){let a={type:"scalar",offset:ZI.emptyScalarPosition(t,r,n),indent:-1,source:""},d=ov.composeScalar(e,a,c,f);return s&&(d.anchor=s.source.substring(1),d.anchor===""&&f(s,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),o&&(d.comment=o,d.range[2]=u),d}function tO({options:e},{offset:t,source:r,end:n},i){let o=new GI.Alias(r.substring(1));o.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=t+r.length,c=QI.resolveEnd(n,s,e.strict,i);return o.range=[t,s,c.offset],c.comment&&(o.comment=c.comment),o}Of.composeEmptyNode=If;Of.composeNode=sv});var uv=A(lv=>{"use strict";var rO=Ss(),cv=av(),nO=oo(),iO=As();function oO(e,t,{offset:r,start:n,value:i,end:o},s){let c=Object.assign({_directives:t},e),u=new rO.Document(void 0,c),f={atKey:!1,atRoot:!0,directives:u.directives,options:u.options,schema:u.schema},a=iO.resolveProps(n,{indicator:"doc-start",next:i??o?.[0],offset:r,onError:s,parentIndent:0,startOnNewline:!0});a.found&&(u.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!a.hasNewline&&s(a.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),u.contents=i?cv.composeNode(f,i,a,s):cv.composeEmptyNode(f,a.end,n,null,a,s);let d=u.contents.range[2],p=nO.resolveEnd(o,d,!1,s);return p.comment&&(u.comment=p.comment),u.range=[r,d,p.offset],u}lv.composeDoc=oO});var Tf=A(pv=>{"use strict";var sO=Qa("process"),aO=wd(),cO=Ss(),xs=_s(),dv=we(),lO=uv(),uO=oo();function Ps(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 fv(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let o=e[i];switch(o[0]){case"#":t+=(t===""?"":n?`
103
+
104
+ `:`
105
+ `)+(o.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var Nf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,o)=>{let s=Ps(r);o?this.warnings.push(new xs.YAMLWarning(s,n,i)):this.errors.push(new xs.YAMLParseError(s,n,i))},this.directives=new aO.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=fv(this.prelude);if(n){let o=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
+ ${n}`:n;else if(i||t.directives.docStart||!o)t.commentBefore=n;else if(dv.isCollection(o)&&!o.flow&&o.items.length>0){let s=o.items[0];dv.isPair(s)&&(s=s.key);let c=s.commentBefore;s.commentBefore=c?`${n}
107
+ ${c}`:n}else{let s=o.commentBefore;o.commentBefore=s?`${n}
108
+ ${s}`:n}}if(r){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:fv(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(sO.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let o=Ps(t);o[0]+=r,this.onError(o,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=lO.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,n=new xs.YAMLParseError(Ps(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new xs.YAMLParseError(Ps(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=uO.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
109
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new xs.YAMLParseError(Ps(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 n=Object.assign({_directives:this.directives},this.options),i=new cO.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};pv.Composer=Nf});var gv=A(Bc=>{"use strict";var dO=Af(),fO=Pf(),pO=_s(),mv=fs();function mO(e,t=!0,r){if(e){let n=(i,o,s)=>{let c=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(c,o,s);else throw new pO.YAMLParseError([c,c+1],o,s)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return fO.resolveFlowScalar(e,t,n);case"block-scalar":return dO.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function hO(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:o=-1,type:s="PLAIN"}=t,c=mv.stringifyString({type:s,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),u=t.end??[{type:"newline",offset:-1,indent:n,source:`
110
+ `}];switch(c[0]){case"|":case">":{let f=c.indexOf(`
111
+ `),a=c.substring(0,f),d=c.substring(f+1)+`
112
+ `,p=[{type:"block-scalar-header",offset:o,indent:n,source:a}];return hv(p,u)||p.push({type:"newline",offset:-1,indent:n,source:`
113
+ `}),{type:"block-scalar",offset:o,indent:n,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:o,indent:n,source:c,end:u};case"'":return{type:"single-quoted-scalar",offset:o,indent:n,source:c,end:u};default:return{type:"scalar",offset:o,indent:n,source:c,end:u}}}function gO(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:o=!1,type:s}=r,c="indent"in e?e.indent:null;if(n&&typeof c=="number"&&(c+=2),!s)switch(e.type){case"single-quoted-scalar":s="QUOTE_SINGLE";break;case"double-quoted-scalar":s="QUOTE_DOUBLE";break;case"block-scalar":{let f=e.props[0];if(f.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s=f.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:s="PLAIN"}let u=mv.stringifyString({type:s,value:t},{implicitKey:i||c===null,indent:c!==null&&c>0?" ".repeat(c):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(u[0]){case"|":case">":wO(e,u);break;case'"':$f(e,u,"double-quoted-scalar");break;case"'":$f(e,u,"single-quoted-scalar");break;default:$f(e,u,"scalar")}}function wO(e,t){let r=t.indexOf(`
114
+ `),n=t.substring(0,r),i=t.substring(r+1)+`
115
+ `;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=n,e.source=i}else{let{offset:o}=e,s="indent"in e?e.indent:-1,c=[{type:"block-scalar-header",offset:o,indent:s,source:n}];hv(c,"end"in e?e.end:void 0)||c.push({type:"newline",offset:-1,indent:s,source:`
116
+ `});for(let u of Object.keys(e))u!=="type"&&u!=="offset"&&delete e[u];Object.assign(e,{type:"block-scalar",indent:s,props:c,source:i})}}function hv(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 $f(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 n=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let o of n)o.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}Bc.createScalarToken=hO;Bc.resolveAsScalar=mO;Bc.setScalarValue=gO});var yv=A(wv=>{"use strict";var yO=e=>"type"in e?Kc(e):Uc(e);function Kc(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Kc(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Uc(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Uc(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Uc(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 Uc({start:e,key:t,sep:r,value:n}){let i="";for(let o of e)i+=o.source;if(t&&(i+=Kc(t)),r)for(let o of r)i+=o.source;return n&&(i+=Kc(n)),i}wv.stringify=yO});var Rv=A(bv=>{"use strict";var jf=Symbol("break visit"),vO=Symbol("skip children"),vv=Symbol("remove item");function ni(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),kv(Object.freeze([]),e,t)}ni.BREAK=jf;ni.SKIP=vO;ni.REMOVE=vv;ni.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let o=r?.[n];if(o&&"items"in o)r=o.items[i];else return}return r};ni.parentCollection=(e,t)=>{let r=ni.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function kv(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let o=t[i];if(o&&"items"in o){for(let s=0;s<o.items.length;++s){let c=kv(Object.freeze(e.concat([[i,s]])),o.items[s],r);if(typeof c=="number")s=c-1;else{if(c===jf)return jf;c===vv&&(o.items.splice(s,1),s-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}bv.visit=ni});var Jc=A(jt=>{"use strict";var Df=gv(),kO=yv(),bO=Rv(),qf="\uFEFF",Lf="",Mf="",Wf="",RO=e=>!!e&&"items"in e,SO=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function CO(e){switch(e){case qf:return"<BOM>";case Lf:return"<DOC>";case Mf:return"<FLOW_END>";case Wf:return"<SCALAR>";default:return JSON.stringify(e)}}function EO(e){switch(e){case qf:return"byte-order-mark";case Lf:return"doc-mode";case Mf:return"flow-error-end";case Wf:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
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}jt.createScalarToken=Df.createScalarToken;jt.resolveAsScalar=Df.resolveAsScalar;jt.setScalarValue=Df.setScalarValue;jt.stringify=kO.stringify;jt.visit=bO.visit;jt.BOM=qf;jt.DOCUMENT=Lf;jt.FLOW_END=Mf;jt.SCALAR=Wf;jt.isCollection=RO;jt.isScalar=SO;jt.prettyToken=CO;jt.tokenType=EO});var Vf=A(Cv=>{"use strict";var Is=Jc();function vr(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Sv=new Set("0123456789ABCDEFabcdef"),_O=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),zc=new Set(",[]{}"),AO=new Set(` ,[]{}
121
+ \r `),Ff=e=>!e||AO.has(e),Hf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,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 n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
+ `?!0:r==="\r"?this.buffer[t+1]===`
123
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
124
+ `||!i&&!this.atEnd)return t+n+1}return r===`
125
+ `||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&vr(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]===Is.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let o=t[n-1];if(o===" "||o===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let o=t[r-1];if(o===" "||o===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),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 Is.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==="...")&&vr(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&&!vr(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===":")&&vr(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"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(Ff),"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,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&vr(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Is.FLOW_END,yield*this.parseLineStart();let o=0;for(;i[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),i[o]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-o),"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(Ff),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let s=this.charAt(1);if(this.flowKey||vr(s)||s===",")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 o=0;for(;this.buffer[r-1-o]==="\\";)o+=1;if(o%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
127
+ `,this.pos);if(i!==-1){for(;i!==-1;){let o=this.continueScalar(i+1);if(o===-1)break;i=n.indexOf(`
128
+ `,o)}i!==-1&&(r=i-(n[i-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=>vr(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let o=this.pos;n=this.buffer[o];++o)switch(n){case" ":r+=1;break;case`
129
+ `:t=o,r=0;break;case"\r":{let s=this.buffer[o+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===`
130
+ `)break}default:break e}if(!n&&!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 o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
131
+ `,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
132
+ `;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let o=t-1,s=this.buffer[o];s==="\r"&&(s=this.buffer[--o]);let c=o;for(;s===" ";)s=this.buffer[--o];if(s===`
133
+ `&&o>=this.pos&&o+1+r>c)t=o;else break}while(!0);return yield Is.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let o=this.buffer[n+1];if(vr(o)||t&&zc.has(o))break;r=n}else if(vr(i)){let o=this.buffer[n+1];if(i==="\r"&&(o===`
134
+ `?(n+=1,i=`
135
+ `,o=this.buffer[n+1]):r=n),o==="#"||t&&zc.has(o))break;if(i===`
136
+ `){let s=this.continueScalar(n+1);if(s===-1)break;n=Math.max(n,s-2)}}else{if(t&&zc.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Is.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 n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.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(Ff),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(vr(n)||r&&zc.has(n)){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(;!vr(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(_O.has(r))r=this.buffer[++t];else if(r==="%"&&Sv.has(this.buffer[t+1])&&Sv.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
+ `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Cv.Lexer=Hf});var Uf=A(Ev=>{"use strict";var Bf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let o=r+n>>1;this.lineStarts[o]<t?r=o+1:n=o}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};Ev.LineCounter=Bf});var Jf=A(Iv=>{"use strict";var xO=Qa("process"),_v=Jc(),PO=Vf();function vn(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Av(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 Pv(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 Gc(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 so(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 Yc(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 xv(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!vn(t.start,"explicit-key-ind")&&!vn(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Pv(t.value)?t.value.end?Yc(t.value.end,t.sep):t.value.end=t.sep:Yc(t.start,t.sep),delete t.sep)}var Kf=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 PO.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,xO.env.LOG_TOKENS&&console.log("|",_v.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=_v.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 n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,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 n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&xv(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&Av(i.start)===-1&&(r.indent===0||i.start.every(o=>o.type!=="comment"||o.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.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":{Av(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=Gc(this.peek(2)),n=so(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}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
+ `)+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 n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.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 i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Yc(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&r.sep&&!r.value){let s=[];for(let c=0;c<r.sep.length;++c){let u=r.sep[c];switch(u.type){case"newline":s.push(c);break;case"space":break;case"comment":u.indent>t.indent&&(s.length=0);break;default:s.length=0}}s.length>=2&&(o=r.sep.splice(s[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(o.push(this.sourceToken),t.items.push({start:o}),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):i||r.value?(o.push(this.sourceToken),t.items.push({start:o,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(vn(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Pv(r.key)&&!vn(r.sep,"newline")){let s=so(r.start),c=r.key,u=r.sep;u.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:c,sep:u}]})}else o.length>0?r.sep=r.sep.concat(o,this.sourceToken):r.sep.push(this.sourceToken);else if(vn(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let s=so(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:o,key:null,sep:[this.sourceToken]}):vn(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 s=this.flowScalar(this.type);i||r.value?(t.items.push({start:o,key:s,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(s):(Object.assign(r,{key:s,sep:[]}),this.onKeyLine=!0);return}default:{let s=this.startBlockValue(t);if(s){if(s.type==="block-seq"){if(!r.explicitKey&&r.sep&&!vn(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 n&&t.items.push({start:o});this.stack.push(s);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 n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.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 i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){Yc(i,r.start),i.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||vn(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.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 i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=Gc(n),o=so(i);xv(t);let s=t.end.splice(1,t.end.length);s.push(this.sourceToken);let c={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=c}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
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=Gc(t),n=so(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Gc(t),n=so(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.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())}}};Iv.Parser=Kf});var jv=A(Ns=>{"use strict";var Ov=Tf(),IO=Ss(),Os=_s(),OO=Id(),NO=we(),TO=Uf(),Nv=Jf();function Tv(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new TO.LineCounter||null,prettyErrors:t}}function $O(e,t={}){let{lineCounter:r,prettyErrors:n}=Tv(t),i=new Nv.Parser(r?.addNewLine),o=new Ov.Composer(t),s=Array.from(o.compose(i.parse(e)));if(n&&r)for(let c of s)c.errors.forEach(Os.prettifyError(e,r)),c.warnings.forEach(Os.prettifyError(e,r));return s.length>0?s:Object.assign([],{empty:!0},o.streamInfo())}function $v(e,t={}){let{lineCounter:r,prettyErrors:n}=Tv(t),i=new Nv.Parser(r?.addNewLine),o=new Ov.Composer(t),s=null;for(let c of o.compose(i.parse(e),!0,e.length))if(!s)s=c;else if(s.options.logLevel!=="silent"){s.errors.push(new Os.YAMLParseError(c.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(s.errors.forEach(Os.prettifyError(e,r)),s.warnings.forEach(Os.prettifyError(e,r))),s}function jO(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=$v(e,r);if(!i)return null;if(i.warnings.forEach(o=>OO.warn(i.options.logLevel,o)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function DO(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=r??t??{};if(!i)return}return NO.isDocument(e)&&!n?e.toString(r):new IO.Document(e,n,r).toString(r)}Ns.parse=jO;Ns.parseAllDocuments=$O;Ns.parseDocument=$v;Ns.stringify=DO});var Gt=A(_e=>{"use strict";var qO=Tf(),LO=Ss(),MO=pf(),zf=_s(),WO=as(),kn=we(),FO=hn(),HO=Ze(),VO=wn(),BO=yn(),UO=Jc(),KO=Vf(),JO=Uf(),zO=Jf(),Xc=jv(),Dv=ns();_e.Composer=qO.Composer;_e.Document=LO.Document;_e.Schema=MO.Schema;_e.YAMLError=zf.YAMLError;_e.YAMLParseError=zf.YAMLParseError;_e.YAMLWarning=zf.YAMLWarning;_e.Alias=WO.Alias;_e.isAlias=kn.isAlias;_e.isCollection=kn.isCollection;_e.isDocument=kn.isDocument;_e.isMap=kn.isMap;_e.isNode=kn.isNode;_e.isPair=kn.isPair;_e.isScalar=kn.isScalar;_e.isSeq=kn.isSeq;_e.Pair=FO.Pair;_e.Scalar=HO.Scalar;_e.YAMLMap=VO.YAMLMap;_e.YAMLSeq=BO.YAMLSeq;_e.CST=UO;_e.Lexer=KO.Lexer;_e.LineCounter=JO.LineCounter;_e.Parser=zO.Parser;_e.parse=Xc.parse;_e.parseAllDocuments=Xc.parseAllDocuments;_e.parseDocument=Xc.parseDocument;_e.stringify=Xc.stringify;_e.visit=Dv.visit;_e.visitAsync=Dv.visitAsync});import bn from"path";function ZO(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||bn.posix.isAbsolute(r)||bn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function Qc(e){let t=ZO(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Vv(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 et(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||bn.posix.isAbsolute(n)||bn.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let i=n.split("/");if(i.some(o=>o===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(o=>o===""||o==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function Rn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Bv(e,t,r){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function e0(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function Hv(e,t,r){let n=e0(e,t,r);if(n>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return n}function t0(e){if(e===void 0)return;let t=Rn(e,"native.pending_root_move"),r=t.id,n=t.from_artifact_root,i=t.to_artifact_root,o=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 n!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(o!=="copying"&&o!=="ready"&&o!=="switched")throw new Error("native.pending_root_move.stage is invalid");let s;if(t.cleanup!==void 0){let c=Rn(t.cleanup,"native.pending_root_move.cleanup"),u=c.kind,f=c.state,a=c.manifest_hash;if(u!=="forward-source"&&u!=="restart-staging"&&u!=="rollback-destination"&&u!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(f!=="prepared"&&f!=="quarantined"&&f!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof a!="string"||!/^[a-f0-9]{64}$/u.test(a))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");s={kind:u,state:f,manifestHash:a}}return{id:r,fromArtifactRoot:Qc(n),toArtifactRoot:Qc(i),stage:o,...s?{cleanup:s}:{}}}function r0(e){if(e===void 0)return;let t=Rn(e,"native.finish");if(t.pull_request===void 0)return{};let r=Rn(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 n=r.command.map((o,s)=>{if(typeof o!="string"||o.trim().length===0||o.length>4096||/[\0\r\n]/u.test(o))throw new Error(`native.finish.pull_request.command[${s}] must be a non-empty single-line string of at most 4096 characters`);return o});if(bn.posix.isAbsolute(n[0])||bn.win32.isAbsolute(n[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=r.timeout_ms??QO;if(!Number.isSafeInteger(i)||i<1||i>Fv)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Fv}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function n0(e,t={}){let r=Rn(e,"native"),n=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let o=r.archive_confirmation??"automatic";if(o!=="automatic"&&o!=="required")throw new Error("native.archive_confirmation must be automatic or required");let s=r.max_verify_failures??GO;if(!Number.isSafeInteger(s)||s<1)throw new Error("native.max_verify_failures must be a positive integer");let c=r.max_parallel_children===void 0?YO:r.max_parallel_children;if(!Number.isSafeInteger(c)||c<1)throw new Error("native.max_parallel_children must be a positive integer");let u=r.document_writes??"allow";if(u!=="allow"&&u!=="revert")throw new Error("native.document_writes must be allow or revert");let f=t0(r.pending_root_move),a=r0(r.finish);return{artifact_root:Qc(n),language:Bv(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:o,max_verify_failures:s,max_parallel_children:c,...u==="revert"?{document_writes:u}:{},...a?{finish:a}:{},...f?{pending_root_move:f}:{}}}function i0(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>Wv)throw new Error(`${t} must be an integer between 1 and ${Wv} milliseconds`);return e}function o0(e){let t=Rn(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=t.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");t.check_timeout_ms!==void 0&&i0(t.check_timeout_ms,"classic.check_timeout_ms");let o=t.document_evidence??"neutral";if(o!=="neutral"&&o!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Vv(t.artifact_layout),language:Bv(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i,...o==="strict"?{document_evidence:o}:{},...t.check_timeout_ms!==void 0?{check_timeout_ms:t.check_timeout_ms}:{}}}function s0(e){let r=Rn(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((n,i)=>et(n,`hook.allow_paths[${i}]`)))]}}function a0(e){if(e===void 0)return{...Gf};let t=Rn(e,"memory"),r=t.learning??Gf.learning,n=t.retrieval??Gf.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof n!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:n}}function Yf(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function c0(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")||bn.posix.isAbsolute(r)||bn.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(i=>i===""||i==="."||i===".."))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>qv)throw new Error(`${t} exceeds ${qv} characters`);let n=0;for(let i=0;i<r.length;i+=1)r[i]==="?"?n+=1:r[i]==="*"&&(n+=1,r[i+1]==="*"&&(i+=1));if(n>Lv)throw new Error(`${t} contains more than ${Lv} wildcard tokens`);return r}function l0(e){let t=Yf(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let n={include:[...new Set(r.map((i,o)=>c0(i,`knowledge.local.include[${o}]`)))],max_file_mb:Hv(t.max_file_mb,Mv.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Hv(t.max_total_mb,Mv.max_total_mb,"knowledge.local.max_total_mb")};if(n.max_file_mb>n.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return n}function u0(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,""),n=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function d0(e){let t=Yf(e,"knowledge.remote"),r=u0(t.endpoint),n=t.token_env;if(n!==void 0&&(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(n)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=t.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let o=t.timeout_ms??5e3;if(typeof o!="number"||!Number.isSafeInteger(o)||o<100||o>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...n===void 0?{}:{token_env:n},...i===void 0?{}:{scope:i},timeout_ms:o}}function f0(e){if(e===void 0)return{...XO};let t=Yf(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let n=t.local===void 0?void 0:l0(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:d0(t.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...n?{local:n}:{},remote:i}}function Uv(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function p0(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function m0(e,t,r,n,i,o,s,c){let u=e.schema!==void 0;if(!(u||e.default_workflow!==void 0||e.workflows!==void 0||!c.allowPartialProject&&e.native!==void 0)||c.allowPartialProject&&!u)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 a=e.workflows??[e.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(p=>p!=="native"&&p!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(a)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:s,change_walkthrough:Uv(e.change_walkthrough),...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...o?{classic:o}:{}}}function Kv(e){let t=(0,tr.parseDocument)(e),r=n=>{let i=(0,tr.isAlias)(n)?n.resolve(t):n;return(0,tr.isScalar)(i)?i.value:void 0};return(0,tr.isMap)(t.contents)&&t.contents.items.some(({key:n,value:i})=>r(n)==="schema"&&r(i)==="comet.project.v1")}function oi(e,t={}){let r=(0,tr.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0,change_walkthrough:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=n,o=p0(i.ambient_resume),s=Uv(i.change_walkthrough),c=i.hook===void 0?void 0:s0(i.hook),u=a0(i.memory),f=f0(i.knowledge),a=i.native===void 0?void 0:n0(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),d=i.classic===void 0?void 0:o0(i.classic),p=m0(i,c,u,f,a,d,o,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:p,ambient_resume:o,change_walkthrough:s,memory:u,knowledge:f,...c?{hook:c}:{},...a?{native:a}:{},...d?{classic:d}:{}}}var tr,ii,qv,Lv,GO,YO,Gf,Mv,XO,Wv,QO,Fv,Yt=je(()=>{"use strict";tr=Tt(Gt(),1),ii=Number.MAX_SAFE_INTEGER,qv=1024,Lv=64,GO=5,YO=2,Gf={learning:!0,retrieval:!0},Mv={include:[],max_file_mb:1,max_total_mb:32},XO={provider:"local"},Wv=36e5,QO=12e4,Fv=6e5});function Sn(e){return e!==0&&e!==0n&&e!=="0"}function Zc(e,t){return Sn(e.dev)&&Sn(t.dev)&&Sn(e.ino)&&Sn(t.ino)}function rr(e,t){let r=Sn(e.dev)&&Sn(t.dev);if(r&&e.dev!==t.dev)return!1;let n=Sn(e.ino)&&Sn(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var Ts=je(()=>{"use strict"});import{constants as Cn,promises as Dt}from"fs";import{createHash as h0}from"node:crypto";function Xf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function el(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function _n(e){return{dev:e.dev,ino:e.ino,birthtime:Xf(e)}}function g0(e,t){let r=_n(e),n=_n(t);return Zc(r,n)?rr(r,n):rr(r,n)&&Xf(e)===Xf(t)&&el(e)===el(t)&&e.size===t.size}function En(e,t){let r=n=>"mtimeNs"in n?n.mtimeNs:n.mtimeMs;return g0(e,t)&&e.size===t.size&&e.mode===t.mode&&r(e)===r(t)&&el(e)===el(t)}async function si(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,o=await Dt.lstat(e,{bigint:i});if(!o.isFile()||o.isSymbolicLink())throw new ut("not-regular-file",`${n} must be a regular file`);if(BigInt(o.size)>BigInt(t))throw new ut("too-large",`${n} exceeds ${t} bytes`);let s=await Dt.realpath(e);await r.verify?.("pre-open",{realPath:s,identity:_n(o)});let c=process.platform==="win32"?Cn.O_RDONLY:Cn.O_RDONLY|Cn.O_NOFOLLOW|Cn.O_NONBLOCK,u;try{u=await Dt.open(e,c)}catch(f){throw f.code==="ELOOP"?new ut("not-regular-file",`${n} must be a regular file`,{cause:f}):f}try{let[f,a,d]=await Promise.all([u.stat({bigint:i}),Dt.lstat(e,{bigint:i}),Dt.realpath(e)]);if(!f.isFile()||!a.isFile()||a.isSymbolicLink()||d!==s||!En(o,f)||!En(o,a))throw new ut("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:_n(f)}),await r.hooks?.afterOpen?.();let p=[],l=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-l,{bytesRead:S}=await u.read(m,0,Math.min(m.length,b),null);if(S===0)break;if(l+=S,l>t)throw new ut("too-large",`${n} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,S)))}let h=Buffer.concat(p,l);if(await r.hooks?.beforeFinalCheck?.(),process.platform==="win32"){let b=0;for(;;){let{bytesRead:S}=await u.read(m,0,Math.min(m.length,l+1-b),b);if(S===0&&b===l)break;if(S===0||b+S>l||!m.subarray(0,S).equals(h.subarray(b,b+S)))throw new ut("changed",`${n} changed while reading`);b+=S}}let[g,w,k]=await Promise.all([u.stat({bigint:i}),Dt.lstat(e,{bigint:i}),Dt.realpath(e)]);if(!w.isFile()||w.isSymbolicLink()||k!==s||!En(o,g)||!En(o,w))throw new ut("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:k,identity:_n(g)}),{bytes:h,stat:g,realPath:k}}finally{await u.close()}}async function zv(e,t={}){let r=t.label??"file",n=t.bigint===!0,i=await Dt.lstat(e,{bigint:n});if(!i.isFile()||i.isSymbolicLink())throw new ut("not-regular-file",`${r} must be a regular file`);let o=await Dt.realpath(e);await t.verify?.("pre-open",{realPath:o,identity:_n(i)});let s=process.platform==="win32"?Cn.O_RDONLY:Cn.O_RDONLY|Cn.O_NOFOLLOW|Cn.O_NONBLOCK,c;try{c=await Dt.open(e,s)}catch(u){throw u.code==="ELOOP"?new ut("not-regular-file",`${r} must be a regular file`,{cause:u}):u}try{let[u,f,a]=await Promise.all([c.stat({bigint:n}),Dt.lstat(e,{bigint:n}),Dt.realpath(e)]);if(!u.isFile()||!f.isFile()||f.isSymbolicLink()||a!==o||!En(i,u)||!En(i,f))throw new ut("changed",`${r} changed while opening`);await t.verify?.("post-open",{realPath:a,identity:_n(u)}),await t.hooks?.afterOpen?.();let d=t.algorithm??"sha256",p=await Jv(c,d);if(await t.hooks?.beforeFinalCheck?.(),process.platform==="win32"&&await Jv(c,d)!==p)throw new ut("changed",`${r} changed while reading`);let[l,m,h]=await Promise.all([c.stat({bigint:n}),Dt.lstat(e,{bigint:n}),Dt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||h!==o||!En(i,l)||!En(i,m))throw new ut("changed",`${r} changed while reading`);return await t.verify?.("post-read",{realPath:h,identity:_n(l)}),{digest:p,stat:l,realPath:h}}finally{await c.close()}}async function Jv(e,t){let r=h0(t),n=Buffer.allocUnsafe(64*1024),i=0;for(;;){let{bytesRead:o}=await e.read(n,0,n.length,i);if(o===0)break;r.update(n.subarray(0,o)),i+=o}return r.digest("hex")}var ut,ai=je(()=>{"use strict";Ts();ut=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});import{AsyncLocalStorage as w0}from"node:async_hooks";function tl(){let e=Qf.getStore();return e?.active?e:null}function Gv(){tl()?.entries.clear()}async function Yv(e){if(tl()!==null)return e();let t={entries:new Map,active:!0};return Qf.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function An(e){return Qf.run({entries:new Map,active:!1},e)}function Xv(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function gt(e,t){return(...r)=>{let n=tl();if(n===null)return t(...r);let i=Xv(`async:${e}`,r),o=n.entries.get(i);if(o)return o.value;let s=t(...r).catch(c=>{throw n.entries.get(i)?.value===s&&n.entries.delete(i),c});return n.entries.set(i,{value:s}),s}}function $r(e,t){return(...r)=>{let n=tl();if(n===null)return t(...r);let i=Xv(`sync:${e}`,r),o=n.entries.get(i);if(o)return o.value;let s=t(...r);return n.entries.set(i,{value:s}),s}}var Qf,jr=je(()=>{"use strict";Qf=new w0});import{promises as qt}from"fs";import Ae from"path";import{AsyncLocalStorage as y0}from"node:async_hooks";async function $s(e,t,r={}){let n=Ae.resolve(e),i=await ep(n,t),o=new Map,s=!1,c=p=>[p.dev,p.ino,p.mode,p.birthtimeNs,p.mtimeNs,p.ctimeNs].join(":"),u=p=>[p.dev,p.ino,p.mode,p.birthtimeNs].join(":"),f=async(p,l)=>JSON.stringify((await qt.readdir(p,{withFileTypes:!0})).filter(m=>!l(m)).map(m=>[m.name,m.isDirectory(),m.isSymbolicLink()]).sort((m,h)=>String(m[0]).localeCompare(String(h[0]),"en"))),a=p=>{let l=o.get(p);return l||(l=(async()=>{let m=await qt.lstat(p,{bigint:!0});if(!m.isDirectory()||m.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Ae.relative(n,p)||"."}`);let h=await qt.realpath(p);if(!ao(i,h))throw new Error(`${t} resolves outside the project root`);let g=r.ignoredDirectoryEntries?.(Ae.relative(n,p).replaceAll("\\","/")||".");return{stat:m,real:h,...g?{ignoreEntry:g,namespace:await f(p,g)}:{}}})(),l=l.catch(m=>{throw o.delete(p),m}),o.set(p,l)),l};await a(n);let d=async p=>{if(s)throw new Error(`${t} read session is already finished`);let l=et(p,t),m=n;for(let h of l.split("/").slice(0,-1))m=Ae.join(m,h),await a(m);return Ae.resolve(n,...l.split("/"))};return{observePath:d,async observeDirectory(p){let l=await d(p);return await a(l),l},async stat(p){let l=await d(p),m=await qt.lstat(l,{bigint:!0});if(!m.isFile()||m.isSymbolicLink())throw new Error(`${t} must be a real file: ${p}`);return{target:l,stat:m}},async hash(p){let l=await d(p);return zv(l,{bigint:!0,label:`${t} ${p}`,verify:async(m,h)=>{if(!ao(i,h.realPath))throw new Error(`${t} resolves outside the project root`);let g=n,w=[n];for(let k of Ae.relative(n,Ae.dirname(l)).split(Ae.sep).filter(Boolean))g=Ae.join(g,k),w.push(g);for(let k of w){let b=await o.get(k),S=await qt.lstat(k,{bigint:!0});if(!S.isDirectory()||S.isSymbolicLink()||u(S)!==u(b.stat))throw new Error(`${t} directory changed while reading: ${Ae.relative(n,k)||"."}`)}}})},async read(p,l,m={}){let h=await d(p);return si(h,l,{...m,label:`${t} ${p}`,verify:async(g,w)=>{if(!ao(i,w.realPath))throw new Error(`${t} resolves outside the project root`);if(r.deferDirectoryChecks)return;let k=n,b=[n];for(let S of Ae.relative(n,Ae.dirname(h)).split(Ae.sep).filter(Boolean))k=Ae.join(k,S),b.push(k);for(let S of b){let E=await o.get(S),O=await qt.lstat(S,{bigint:!0});if(!O.isDirectory()||O.isSymbolicLink()||u(O)!==u(E.stat))throw new Error(`${t} directory changed while reading: ${Ae.relative(n,S)||"."}`)}}})},async finish(p={}){if(s)throw new Error(`${t} read session is already finished`);s=!0;let l=[];for(let[m,h]of o){let g=await h,w=await qt.lstat(m,{bigint:!0});if(!w.isDirectory()||w.isSymbolicLink()||u(g.stat)!==u(w)||!p.allowDirectoryContentChanges&&c(g.stat)!==c(w)&&(!g.ignoreEntry||await f(m,g.ignoreEntry)!==g.namespace)||await qt.realpath(m)!==g.real)throw new Error(`${t} directory changed while observing: ${Ae.relative(n,m)||"."}`);c(g.stat)!==c(w)&&l.push(Ae.relative(n,m).replaceAll("\\","/")||".")}return{changedDirectories:l}}}}function Qv(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ao(e,t){let r=Ae.relative(e,t);return r===""||!Ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ae.sep}`)}async function ep(e,t){let r=Ae.resolve(e),n=await Zv(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ek(r)}async function tk(e,t,r,n){let i=e;for(let o=0;o<r.length;o++){i=Ae.join(i,r[o]);let s;try{s=await Zv(i)}catch(f){if(Qv(f))return{exists:!1,kind:"missing"};throw f}if(s.isSymbolicLink()){let f=Ae.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} crosses a symbolic link or junction at ${f}`)}let c=o===r.length-1;if(!c&&!s.isDirectory()){let f=Ae.relative(e,i).replaceAll("\\","/");throw new Error(`${n.label} ancestor ${f} must be a real directory`)}if(c&&(n.expected==="file"&&!s.isFile()||n.expected==="directory"&&!s.isDirectory()||n.expected==="any"&&!s.isFile()&&!s.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let u=await ek(i);if(!k0(t,u))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:s.isFile()?"file":s.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function rk(e,t,r){let n=et(t,r.label),i=Ae.resolve(e),o=await ep(i,r.label),s=n.split("/"),c=Ae.resolve(i,...s);if(!ao(i,c))throw new Error(`${r.label} must stay inside the project root`);let u=await tk(i,o,s,r);return{projectRoot:i,target:c,relative:n,exists:u.exists,kind:u.kind}}async function U(e,t,r){if(r.expected===void 0)return rk(e,t,r);try{return await b0(e,t,r.expected)}catch(n){throw n instanceof Error&&n.message.includes("Protected project path")&&(n.message=n.message.replaceAll("Protected project path",r.label)),n}}async function ft(e,t,r){let n=et(t,r.label),i=Ae.resolve(e),o=await ep(i,r.label),s=n.split("/"),c=i;for(let u of s){c=Ae.join(c,u);let f;try{f=await qt.lstat(c)}catch(p){if(!Qv(p))throw p;try{await qt.mkdir(c)}catch(l){if(l.code!=="EEXIST")throw l}f=await qt.lstat(c)}let a=Ae.relative(i,c).replaceAll("\\","/");if(f.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${a}`);if(!f.isDirectory())throw new Error(`${r.label} directory ${a} must be a real directory`);let d=await qt.realpath(c);if(!ao(o,d))throw new Error(`${r.label} resolves outside the project root`)}return await tk(i,o,s,{label:r.label,expected:"directory"}),c}async function tp(e,t,r){return(await U(e,t,{...r,expected:"file"})).exists}async function nk(e,t,r,n){let i=!n.hooks&&!n.bigint?v0.getStore():void 0;if(i){let c=Ae.resolve(e),u=i.get(c);return u||(u=$s(c,n.label,{deferDirectoryChecks:!0}).catch(f=>{throw i.delete(c),f}),i.set(c,u)),(await u).read(t,r,n)}let o=await $s(e,n.label),s=await o.read(t,r,n);return await o.finish({allowDirectoryContentChanges:!0}),s}async function ae(e,t,r,n){if(n.hooks||n.bigint)return nk(e,t,r,n);try{return await R0(e,t,r)}catch(i){throw i instanceof Error&&i.message.includes(Zf)&&(i.message=i.message.replaceAll(Zf,n.label)),i}}var v0,Zv,ek,k0,b0,Zf,R0,ye=je(()=>{"use strict";ai();Yt();jr();v0=new y0;Zv=gt("protectedChainLstat",e=>qt.lstat(e)),ek=gt("protectedChainRealpath",e=>qt.realpath(e)),k0=$r("protectedChainInside",ao);b0=gt("protectedInspectPath",(e,t,r)=>rk(e,t,{label:"Protected project path",expected:r}));Zf="Cached protected project read",R0=gt("protectedReadFile",(e,t,r)=>nk(e,t,r,{label:Zf}))});import{createHash as S0}from"crypto";function C0(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function co(e,t={}){return(await rl(e,t)).document}async function E0(e){try{return(await ae(e,js,ii,{label:js})).bytes}catch(t){if(C0(t))return null;throw t}}function _0(e){return e?{exists:!0,sha256:S0("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function rl(e,t={}){let r=await E0(e);return{source:r?.toString("utf8")??null,document:r?oi(r.toString("utf8"),t):null,identity:_0(r)}}async function rp(e){return(await co(e))?.config??null}var js,ci=je(()=>{"use strict";Yt();ye();js=".comet/config.yaml"});import{promises as ip}from"node:fs";async function op(e,t){let r;for(let n=0;n<=np.length;n+=1)try{return await e()}catch(i){r=i;let o=i.code;if(n===np.length||!A0.has(o??""))throw i;await new Promise(s=>setTimeout(s,np[n]))}throw r}async function sp(e,t){await op(()=>ip.rename(e,t),`rename ${t}`)}async function ap(e){await op(()=>ip.unlink(e),`unlink ${e}`)}async function nl(e,t){await op(()=>ip.link(e,t),`link ${t}`)}var A0,np,ik=je(()=>{"use strict";A0=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),np=[50,100,200]});import{randomUUID as ok}from"crypto";import{constants as x0,promises as We}from"fs";import Be from"path";async function cp(e,t){try{return await nl(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await We.copyFile(e,t,x0.COPYFILE_EXCL),{linked:!1}}function ui(e,t){let r=Be.relative(e,t);return r===""||!Be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Be.sep}`)}function il(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function P0(e,t){return rr(e,il(t))}function li(e,t){return rr(il(e),il(t))}function sk(e,t){return li(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ol(e){let t=await We.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await We.realpath(e),...il(t)}}async function wt(e){for(let t of e){let r=await We.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!P0(t,r)||await We.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function I0(e,t,r){let[n,i]=await Promise.all([We.lstat(e),We.realpath(e),wt(r)]);if(!n.isFile()||n.isSymbolicLink()||!li(n,t)||!ui(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function ak(e,t){let r=await lp(e,t);if(r)return r;let n=Be.resolve(e),i=Be.resolve(t);if(!ui(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let o=[await ol(n)],s=Be.relative(n,i).split(Be.sep).filter(Boolean),c=n;for(let u of s){await wt(o),c=Be.join(c,u);try{await We.mkdir(c)}catch(a){if(a.code!=="EEXIST")throw a}let f=await ol(c);if(!ui(o[0].realPath,f.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${c}`);o.push(f)}return await wt(o),o}async function lp(e,t){let r=Be.resolve(e),n=Be.resolve(t);if(!ui(r,n))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await ol(r)],o=Be.relative(r,n).split(Be.sep).filter(Boolean),s=r;for(let c of o){s=Be.join(s,c);try{let u=await ol(s);if(!ui(i[0].realPath,u.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${s}`);i.push(u)}catch(u){if(u.code==="ENOENT")return null;throw u}}return await wt(i),i}async function up(e){let t;try{t=await We.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function O0(e,t,r){let n=Be.dirname(e),i=await ak(r.containedRoot,n),o=Be.join(n,`.${Be.basename(e)}.${ok()}.tmp`),s,c,u;try{await r.beforeTemporaryOpen?.(),s=await We.open(o,"wx"),c=await s.stat();let[f,a]=await Promise.all([We.lstat(o),We.realpath(o)]);if(await wt(i),!f.isFile()||f.isSymbolicLink()||!li(c,f)||!ui(i[0].realPath,a))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await s.writeFile(t,"utf8"):await s.writeFile(t),await s.sync(),u=await s.stat(),!li(c,u))throw new Error("Contained atomic write temporary file changed while writing");if(await s.close(),s=void 0,await r.afterTemporaryClose?.(),!u)throw new Error("Contained atomic write temporary file was not written");u=await I0(o,u,i),await r.beforeCommit?.(),await wt(i);let d=await We.lstat(o);if(!d.isFile()||d.isSymbolicLink()||!u||!sk(d,u))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(r.requireAtomicPublication?await nl(o,e):await cp(o,e),await We.unlink(o)):await sp(o,e),await up(n)}catch(f){await s?.close();try{await wt(i),await We.rm(o,{force:!0})}catch{}throw f}}async function $e(e,t,r){await O0(e,t,r)}async function ck(e,t,r){let n=await lp(r.containedRoot,Be.dirname(e));if(!n)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await ak(r.containedRoot,Be.dirname(t)),o=await We.lstat(e);if(!o.isFile()||o.isSymbolicLink())throw new Error("Contained link source must be a regular file");let s=Be.join(Be.dirname(t),`.${Be.basename(t)}.${ok()}.tmp`);try{await wt(n),await wt(i),await nl(e,s),await r.beforeCommit?.(),await wt(n),await wt(i);let c=await We.lstat(s),u=await We.lstat(e);if(!c.isFile()||c.isSymbolicLink()||!u.isFile()||u.isSymbolicLink()||!li(o,u)||!li(u,c)||o.size!==u.size||o.mtimeMs!==u.mtimeMs)throw new Error("Contained link source changed before publication");let f=await We.lstat(t).catch(a=>{if(a.code==="ENOENT")return null;throw a});f?.isFile()&&!f.isSymbolicLink()&&li(u,f)?await ap(s):await sp(s,t),await up(Be.dirname(t)),await wt(n),await wt(i)}catch(c){try{await wt(i),await We.unlink(s)}catch{}throw c}}async function Dr(e,t){let r=Be.dirname(e),n=await lp(t.containedRoot,r);if(!n)return!1;let i,o;try{i=await We.lstat(e),o=await We.realpath(e)}catch(u){if(u.code==="ENOENT")return!1;throw u}if(!i.isFile()||i.isSymbolicLink()||!ui(n[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await wt(n);let[s,c]=await Promise.all([We.lstat(e),We.realpath(e)]);if(!s.isFile()||s.isSymbolicLink()||!sk(i,s)||c!==o)throw new Error("Contained file removal target changed before removal");return await ap(e),await wt(n),await up(r),!0}var Lt=je(()=>{"use strict";ik();Ts()});var gB,dp=je(()=>{"use strict";Lt();ci();ye();gB=Number.MAX_SAFE_INTEGER});var pp=je(()=>{"use strict";Lt();Yt();ci();ye();dp()});var fl=je(()=>{"use strict"});var Ck=je(()=>{"use strict"});var bp=je(()=>{"use strict";fl()});var Ek=je(()=>{"use strict";fl();bp()});var sN,_k=je(()=>{"use strict";sN=Tt(Gt(),1);Lt();Yt();ye()});var b2,Ak=je(()=>{"use strict";Lt();ye();b2=Number.MAX_SAFE_INTEGER});var xk=je(()=>{"use strict"});var Pk=je(()=>{"use strict"});var Ik=je(()=>{"use strict";xk();Pk()});var Ok=je(()=>{"use strict";Ik()});var L2,Nk=je(()=>{"use strict";jr();ci();Ok();L2=gt("hookWritePolicy",async e=>(await rp(e))?.hook??{allow_paths:[]})});import{promises as aN}from"node:fs";import cN from"node:path";function Rp(e){return cN.join(e,".comet","current-change.json")}function lN(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Tk(e){return e===null||typeof e=="string"}function uN(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!lN(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Tk(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:pl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==pl)throw new Error(`current change selection schema must be ${pl}`);if(t.workflow!=="native"&&t.workflow!=="classic"&&t.workflow!=="application")throw new Error("current change selection workflow must be native, classic or application");if(t.workflow==="application"&&(typeof t.applicationId!="string"||!t.applicationId.trim()||t.branch!==null))throw new Error("application selection requires applicationId and a null branch");if(t.workflow!=="application"&&t.applicationId!==void 0)throw new Error("built-in selection cannot retain another application identity");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Tk(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function ml(e){let t;try{let n=Rp(e),{bytes:i}=await si(n,$k,{label:"current change selection"});t=i.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...uN(t)}}async function jk(e){await aN.rm(Rp(e),{force:!0})}async function Sp(e,t,r){let n=await ml(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==r?!1:(await jk(e),!0)}var pl,$k,dN,hl=je(()=>{"use strict";jr();ai();pl="comet.selection.v2",$k=Number.MAX_SAFE_INTEGER;dN=gt("readCometCurrentSelection",e=>ml(e))});var Dk=je(()=>{"use strict";fl();Lt();Ck();Ek();Yt();_k();ye();ci();pp();Ak();Nk();hl();dp();bp()});import{TextDecoder as pN}from"util";function qk(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function mN(e,t){try{return new pN("utf-8",{fatal:!0}).decode(e.bytes)}catch(r){throw new Error(`${t} is not valid UTF-8`,{cause:r})}}async function Cp(e,t,r,n,i={}){try{let o=await ae(e,t,r,{label:n,hooks:i.hooks});return{result:o,text:mN(o,n)}}catch(o){let s=o.code;if(s==="ENOENT"||s==="ENOTDIR")return null;throw o}}async function pi(e,t,r,n,i={}){return(await Cp(e,t,r,n,i))?.text??null}async function mi(e,t,r,n,i,o={}){if(Buffer.byteLength(r,"utf8")>n)throw new Error(`${i} exceeds ${n} bytes`);let s=await Cp(e,t,n,i),c=await U(e,t,{label:i,expected:"file"});await $e(c.target,r,{containedRoot:c.projectRoot,beforeCommit:async()=>{await o.beforeCommit?.();let u=await Cp(e,t,n,i);if(!(!s&&!u)){if(!s||!u)throw new Error(`${i} changed before commit`);if(s.result.realPath!==u.result.realPath||!rr(qk(s.result.stat),qk(u.result.stat))||s.text!==u.text)throw new Error(`${i} changed before commit`)}}})}async function Lk(e,t,r,n,i,o={}){let s=await pi(e,t,n,i);await mi(e,t,`${s??""}${r}`,n,i,o)}async function gl(e,t,r,n={}){let i=await U(e,t,{label:r,expected:"file"});return i.exists?Dr(i.target,{containedRoot:i.projectRoot,beforeRemove:n.beforeRemove}):!1}var Ep=je(()=>{"use strict";Dk();Ts()});var Fk={};yA(Fk,{RUN_STATE_FILE:()=>wl,applyRunStateToDocument:()=>_p,readRunState:()=>Fs,removeRunState:()=>Hs,runStateFromDocument:()=>hi,writeRunState:()=>gi});import hN from"path";function Ws(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Ms(e,t){let r=Ws(e,t);if(hN.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function gN(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(r))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function hi(e){if(!e.run_id)return null;let t=Ws(e,"run_id"),r=Ws(e,"skill"),n=Ws(e,"skill_version"),i=Ws(e,"skill_hash"),o=Ms(e,"pending_ref"),s=Ms(e,"trajectory_ref"),c=Ms(e,"context_ref"),u=Ms(e,"artifacts_ref"),f=Ms(e,"checkpoint_ref"),a=Number(e.iteration);if(!Number.isInteger(a)||a<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:n,skillHash:i,orchestration:e.orchestration,currentStep:Mk(e,"current_step"),iteration:a,pending:Mk(e,"pending"),pendingRef:o,trajectoryRef:s,contextRef:c,artifactsRef:u,checkpointRef:f,status:e.run_status,retries:gN(e)}}function _p(e,t){t?e.run_id=t.runId:delete e.run_id}function wN(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,currentStep:e.currentStep,iteration:e.iteration,pending:e.pending,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,status:e.status,retries:e.retries}}function yN(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)};return hi(t)}async function Fs(e,t={}){let r=await pi(e,wl,Wk,"Run state",t);if(r===null)return null;let n=JSON.parse(r);return yN(n)}async function gi(e,t,r={}){await mi(e,wl,JSON.stringify(wN(t),null,2),Wk,"Run state",r)}async function Hs(e,t={}){await gl(e,wl,"Run state",t)}var Mk,wl,Wk,yl=je(()=>{"use strict";Ep();Mk=(e,t)=>{let r=e[t];return r==null?null:String(r)};wl=".comet/run-state.json",Wk=Number.MAX_SAFE_INTEGER});var la=A(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.regexpCode=Ce.getEsmExportName=Ce.getProperty=Ce.safeStringify=Ce.stringify=Ce.strConcat=Ce.addCodeArg=Ce.str=Ce._=Ce.nil=Ce._Code=Ce.Name=Ce.IDENTIFIER=Ce._CodeOrName=void 0;var aa=class{};Ce._CodeOrName=aa;Ce.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ei=class extends aa{constructor(t){if(super(),!Ce.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Ce.Name=Ei;var cr=class extends aa{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Ei&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Ce._Code=cr;Ce.nil=new cr("");function IR(e,...t){let r=[e[0]],n=0;for(;n<t.length;)sm(r,t[n]),r.push(e[++n]);return new cr(r)}Ce._=IR;var om=new cr("+");function OR(e,...t){let r=[ca(e[0])],n=0;for(;n<t.length;)r.push(om),sm(r,t[n]),r.push(om,ca(e[++n]));return x$(r),new cr(r)}Ce.str=OR;function sm(e,t){t instanceof cr?e.push(...t._items):t instanceof Ei?e.push(t):e.push(O$(t))}Ce.addCodeArg=sm;function x$(e){let t=1;for(;t<e.length-1;){if(e[t]===om){let r=P$(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function P$(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Ei||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Ei))return`"${e}${t.slice(1)}`}function I$(e,t){return t.emptyStr()?e:e.emptyStr()?t:OR`${e}${t}`}Ce.strConcat=I$;function O$(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:ca(Array.isArray(e)?e.join(","):e)}function N$(e){return new cr(ca(e))}Ce.stringify=N$;function ca(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Ce.safeStringify=ca;function T$(e){return typeof e=="string"&&Ce.IDENTIFIER.test(e)?new cr(`.${e}`):IR`[${e}]`}Ce.getProperty=T$;function $$(e){if(typeof e=="string"&&Ce.IDENTIFIER.test(e))return new cr(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Ce.getEsmExportName=$$;function j$(e){return new cr(e.toString())}Ce.regexpCode=j$});var lm=A(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.ValueScope=Bt.ValueScopeName=Bt.Scope=Bt.varKinds=Bt.UsedValueState=void 0;var Vt=la(),am=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},nu;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(nu||(Bt.UsedValueState=nu={}));Bt.varKinds={const:new Vt.Name("const"),let:new Vt.Name("let"),var:new Vt.Name("var")};var iu=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Vt.Name?t:this.name(t)}name(t){return new Vt.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Bt.Scope=iu;var ou=class extends Vt.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Vt._)`.${new Vt.Name(r)}[${n}]`}};Bt.ValueScopeName=ou;var D$=(0,Vt._)`\n`,cm=class extends iu{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?D$:Vt.nil}}get(){return this._scope}name(t){return new ou(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[o];if(c){let a=c.get(s);if(a)return a}else c=this._values[o]=new Map;c.set(s,i);let u=this._scope[o]||(this._scope[o]=[]),f=u.length;return u[f]=r.ref,i.setValue(r,{property:o,itemIndex:f}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Vt._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let o=Vt.nil;for(let s in t){let c=t[s];if(!c)continue;let u=n[s]=n[s]||new Map;c.forEach(f=>{if(u.has(f))return;u.set(f,nu.Started);let a=r(f);if(a){let d=this.opts.es5?Bt.varKinds.var:Bt.varKinds.const;o=(0,Vt._)`${o}${d} ${f} = ${a};${this.opts._n}`}else if(a=i?.(f))o=(0,Vt._)`${o}${a}${this.opts._n}`;else throw new am(f);u.set(f,nu.Completed)})}return o}};Bt.ValueScope=cm});var de=A(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.or=ue.and=ue.not=ue.CodeGen=ue.operators=ue.varKinds=ue.ValueScopeName=ue.ValueScope=ue.Scope=ue.Name=ue.regexpCode=ue.stringify=ue.getProperty=ue.nil=ue.strConcat=ue.str=ue._=void 0;var ge=la(),Er=lm(),qn=la();Object.defineProperty(ue,"_",{enumerable:!0,get:function(){return qn._}});Object.defineProperty(ue,"str",{enumerable:!0,get:function(){return qn.str}});Object.defineProperty(ue,"strConcat",{enumerable:!0,get:function(){return qn.strConcat}});Object.defineProperty(ue,"nil",{enumerable:!0,get:function(){return qn.nil}});Object.defineProperty(ue,"getProperty",{enumerable:!0,get:function(){return qn.getProperty}});Object.defineProperty(ue,"stringify",{enumerable:!0,get:function(){return qn.stringify}});Object.defineProperty(ue,"regexpCode",{enumerable:!0,get:function(){return qn.regexpCode}});Object.defineProperty(ue,"Name",{enumerable:!0,get:function(){return qn.Name}});var lu=lm();Object.defineProperty(ue,"Scope",{enumerable:!0,get:function(){return lu.Scope}});Object.defineProperty(ue,"ValueScope",{enumerable:!0,get:function(){return lu.ValueScope}});Object.defineProperty(ue,"ValueScopeName",{enumerable:!0,get:function(){return lu.ValueScopeName}});Object.defineProperty(ue,"varKinds",{enumerable:!0,get:function(){return lu.varKinds}});ue.operators={GT:new ge._Code(">"),GTE:new ge._Code(">="),LT:new ge._Code("<"),LTE:new ge._Code("<="),EQ:new ge._Code("==="),NEQ:new ge._Code("!=="),NOT:new ge._Code("!"),OR:new ge._Code("||"),AND:new ge._Code("&&"),ADD:new ge._Code("+")};var nn=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},um=class extends nn{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?Er.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Io(this.rhs,t,r)),this}get names(){return this.rhs instanceof ge._CodeOrName?this.rhs.names:{}}},su=class extends nn{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof ge.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Io(this.rhs,t,r),this}get names(){let t=this.lhs instanceof ge.Name?{}:{...this.lhs.names};return cu(t,this.rhs)}},dm=class extends su{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},fm=class extends nn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},pm=class extends nn{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},mm=class extends nn{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},hm=class extends nn{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Io(this.code,t,r),this}get names(){return this.code instanceof ge._CodeOrName?this.code.names:{}}},ua=class extends nn{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(t,r)||(q$(t,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>xi(t,r.names),{})}},on=class extends ua{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},gm=class extends ua{},Po=class extends on{};Po.kind="else";var _i=class e extends on{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Po(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(NR(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Io(this.condition,t,r),this}get names(){let t=super.names;return cu(t,this.condition),this.else&&xi(t,this.else.names),t}};_i.kind="if";var Ai=class extends on{};Ai.kind="for";var wm=class extends Ai{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Io(this.iteration,t,r),this}get names(){return xi(super.names,this.iteration.names)}},ym=class extends Ai{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?Er.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(t)}get names(){let t=cu(super.names,this.from);return cu(t,this.to)}},au=class extends Ai{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Io(this.iterable,t,r),this}get names(){return xi(super.names,this.iterable.names)}},da=class extends on{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};da.kind="func";var fa=class extends ua{render(t){return"return "+super.render(t)}};fa.kind="return";var vm=class extends on{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&xi(t,this.catch.names),this.finally&&xi(t,this.finally.names),t}},pa=class extends on{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};pa.kind="catch";var ma=class extends on{render(t){return"finally"+super.render(t)}};ma.kind="finally";var km=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
143
+ `:""},this._extScope=t,this._scope=new Er.Scope({parent:t}),this._nodes=[new gm]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new um(t,o,n)),o}const(t,r,n){return this._def(Er.varKinds.const,t,r,n)}let(t,r,n){return this._def(Er.varKinds.let,t,r,n)}var(t,r,n){return this._def(Er.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new su(t,r,n))}add(t,r){return this._leafNode(new dm(t,ue.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==ge.nil&&this._leafNode(new hm(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,ge.addCodeArg)(r,i));return r.push("}"),new ge._Code(r)}if(t,r,n){if(this._blockNode(new _i(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new _i(t))}else(){return this._elseNode(new Po)}endIf(){return this._endBlockNode(_i,Po)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new wm(t),r)}forRange(t,r,n,i,o=this.opts.es5?Er.varKinds.var:Er.varKinds.let){let s=this._scope.toName(t);return this._for(new ym(o,s,r,n),()=>i(s))}forOf(t,r,n,i=Er.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let s=r instanceof ge.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ge._)`${s}.length`,c=>{this.var(o,(0,ge._)`${s}[${c}]`),n(o)})}return this._for(new au("of",i,o,r),()=>n(o))}forIn(t,r,n,i=this.opts.es5?Er.varKinds.var:Er.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,ge._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new au("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Ai)}label(t){return this._leafNode(new fm(t))}break(t){return this._leafNode(new pm(t))}return(t){let r=new fa;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fa)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new vm;if(this._blockNode(i),this.code(t),r){let o=this.name("e");this._currNode=i.catch=new pa(o),r(o)}return n&&(this._currNode=i.finally=new ma,this.code(n)),this._endBlockNode(pa,ma)}throw(t){return this._leafNode(new mm(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=ge.nil,n,i){return this._blockNode(new da(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(da)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof _i))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};ue.CodeGen=km;function xi(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function cu(e,t){return t instanceof ge._CodeOrName?xi(e,t.names):e}function Io(e,t,r){if(e instanceof ge.Name)return n(e);if(!i(e))return e;return new ge._Code(e._items.reduce((o,s)=>(s instanceof ge.Name&&(s=n(s)),s instanceof ge._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||t[o.str]!==1?o:(delete t[o.str],s)}function i(o){return o instanceof ge._Code&&o._items.some(s=>s instanceof ge.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function q$(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function NR(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,ge._)`!${bm(e)}`}ue.not=NR;var L$=TR(ue.operators.AND);function M$(...e){return e.reduce(L$)}ue.and=M$;var W$=TR(ue.operators.OR);function F$(...e){return e.reduce(W$)}ue.or=F$;function TR(e){return(t,r)=>t===ge.nil?r:r===ge.nil?t:(0,ge._)`${bm(t)} ${e} ${bm(r)}`}function bm(e){return e instanceof ge.Name?e:(0,ge._)`(${e})`}});var ve=A(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.checkStrictMode=fe.getErrorPath=fe.Type=fe.useFunc=fe.setEvaluated=fe.evaluatedPropsToName=fe.mergeEvaluated=fe.eachItem=fe.unescapeJsonPointer=fe.escapeJsonPointer=fe.escapeFragment=fe.unescapeFragment=fe.schemaRefOrVal=fe.schemaHasRulesButRef=fe.schemaHasRules=fe.checkUnknownRules=fe.alwaysValidSchema=fe.toHash=void 0;var Ne=de(),H$=la();function V$(e){let t={};for(let r of e)t[r]=!0;return t}fe.toHash=V$;function B$(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(DR(e,t),!qR(t,e.self.RULES.all))}fe.alwaysValidSchema=B$;function DR(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let o in t)i[o]||WR(e,`unknown keyword: "${o}"`)}fe.checkUnknownRules=DR;function qR(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}fe.schemaHasRules=qR;function U$(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}fe.schemaHasRulesButRef=U$;function K$({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ne._)`${r}`}return(0,Ne._)`${e}${t}${(0,Ne.getProperty)(n)}`}fe.schemaRefOrVal=K$;function J$(e){return LR(decodeURIComponent(e))}fe.unescapeFragment=J$;function z$(e){return encodeURIComponent(Sm(e))}fe.escapeFragment=z$;function Sm(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}fe.escapeJsonPointer=Sm;function LR(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}fe.unescapeJsonPointer=LR;function G$(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}fe.eachItem=G$;function $R({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,o,s,c)=>{let u=s===void 0?o:s instanceof Ne.Name?(o instanceof Ne.Name?e(i,o,s):t(i,o,s),s):o instanceof Ne.Name?(t(i,s,o),o):r(o,s);return c===Ne.Name&&!(u instanceof Ne.Name)?n(i,u):u}}fe.mergeEvaluated={props:$R({mergeNames:(e,t,r)=>e.if((0,Ne._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,Ne._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,Ne._)`${r} || {}`).code((0,Ne._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,Ne._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,Ne._)`${r} || {}`),Cm(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:MR}),items:$R({mergeNames:(e,t,r)=>e.if((0,Ne._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,Ne._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,Ne._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,Ne._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function MR(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,Ne._)`{}`);return t!==void 0&&Cm(e,r,t),r}fe.evaluatedPropsToName=MR;function Cm(e,t,r){Object.keys(r).forEach(n=>e.assign((0,Ne._)`${t}${(0,Ne.getProperty)(n)}`,!0))}fe.setEvaluated=Cm;var jR={};function Y$(e,t){return e.scopeValue("func",{ref:t,code:jR[t.code]||(jR[t.code]=new H$._Code(t.code))})}fe.useFunc=Y$;var Rm;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Rm||(fe.Type=Rm={}));function X$(e,t,r){if(e instanceof Ne.Name){let n=t===Rm.Num;return r?n?(0,Ne._)`"[" + ${e} + "]"`:(0,Ne._)`"['" + ${e} + "']"`:n?(0,Ne._)`"/" + ${e}`:(0,Ne._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ne.getProperty)(e).toString():"/"+Sm(e)}fe.getErrorPath=X$;function WR(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}fe.checkStrictMode=WR});var sn=A(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var vt=de(),Q$={data:new vt.Name("data"),valCxt:new vt.Name("valCxt"),instancePath:new vt.Name("instancePath"),parentData:new vt.Name("parentData"),parentDataProperty:new vt.Name("parentDataProperty"),rootData:new vt.Name("rootData"),dynamicAnchors:new vt.Name("dynamicAnchors"),vErrors:new vt.Name("vErrors"),errors:new vt.Name("errors"),this:new vt.Name("this"),self:new vt.Name("self"),scope:new vt.Name("scope"),json:new vt.Name("json"),jsonPos:new vt.Name("jsonPos"),jsonLen:new vt.Name("jsonLen"),jsonPart:new vt.Name("jsonPart")};Em.default=Q$});var ha=A(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.extendErrors=kt.resetErrorsCount=kt.reportExtraError=kt.reportError=kt.keyword$DataError=kt.keywordError=void 0;var ke=de(),uu=ve(),It=sn();kt.keywordError={message:({keyword:e})=>(0,ke.str)`must pass "${e}" keyword validation`};kt.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,ke.str)`"${e}" keyword must be ${t} ($data)`:(0,ke.str)`"${e}" keyword is invalid ($data)`};function Z$(e,t=kt.keywordError,r,n){let{it:i}=e,{gen:o,compositeRule:s,allErrors:c}=i,u=VR(e,t,r);n??(s||c)?FR(o,u):HR(i,(0,ke._)`[${u}]`)}kt.reportError=Z$;function ej(e,t=kt.keywordError,r){let{it:n}=e,{gen:i,compositeRule:o,allErrors:s}=n,c=VR(e,t,r);FR(i,c),o||s||HR(n,It.default.vErrors)}kt.reportExtraError=ej;function tj(e,t){e.assign(It.default.errors,t),e.if((0,ke._)`${It.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,ke._)`${It.default.vErrors}.length`,t),()=>e.assign(It.default.vErrors,null)))}kt.resetErrorsCount=tj;function rj({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",i,It.default.errors,c=>{e.const(s,(0,ke._)`${It.default.vErrors}[${c}]`),e.if((0,ke._)`${s}.instancePath === undefined`,()=>e.assign((0,ke._)`${s}.instancePath`,(0,ke.strConcat)(It.default.instancePath,o.errorPath))),e.assign((0,ke._)`${s}.schemaPath`,(0,ke.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0,ke._)`${s}.schema`,r),e.assign((0,ke._)`${s}.data`,n))})}kt.extendErrors=rj;function FR(e,t){let r=e.const("err",t);e.if((0,ke._)`${It.default.vErrors} === null`,()=>e.assign(It.default.vErrors,(0,ke._)`[${r}]`),(0,ke._)`${It.default.vErrors}.push(${r})`),e.code((0,ke._)`${It.default.errors}++`)}function HR(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,ke._)`new ${e.ValidationError}(${t})`):(r.assign((0,ke._)`${n}.errors`,t),r.return(!1))}var Pi={keyword:new ke.Name("keyword"),schemaPath:new ke.Name("schemaPath"),params:new ke.Name("params"),propertyName:new ke.Name("propertyName"),message:new ke.Name("message"),schema:new ke.Name("schema"),parentSchema:new ke.Name("parentSchema")};function VR(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,ke._)`{}`:nj(e,t,r)}function nj(e,t,r={}){let{gen:n,it:i}=e,o=[ij(i,r),oj(e,r)];return sj(e,t,o),n.object(...o)}function ij({errorPath:e},{instancePath:t}){let r=t?(0,ke.str)`${e}${(0,uu.getErrorPath)(t,uu.Type.Str)}`:e;return[It.default.instancePath,(0,ke.strConcat)(It.default.instancePath,r)]}function oj({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,ke.str)`${t}/${e}`;return r&&(i=(0,ke.str)`${i}${(0,uu.getErrorPath)(r,uu.Type.Str)}`),[Pi.schemaPath,i]}function sj(e,{params:t,message:r},n){let{keyword:i,data:o,schemaValue:s,it:c}=e,{opts:u,propertyName:f,topSchemaRef:a,schemaPath:d}=c;n.push([Pi.keyword,i],[Pi.params,typeof t=="function"?t(e):t||(0,ke._)`{}`]),u.messages&&n.push([Pi.message,typeof r=="function"?r(e):r]),u.verbose&&n.push([Pi.schema,s],[Pi.parentSchema,(0,ke._)`${a}${d}`],[It.default.data,o]),f&&n.push([Pi.propertyName,f])}});var UR=A(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.boolOrEmptySchema=Oo.topBoolOrEmptySchema=void 0;var aj=ha(),cj=de(),lj=sn(),uj={message:"boolean schema is false"};function dj(e){let{gen:t,schema:r,validateName:n}=e;r===!1?BR(e,!1):typeof r=="object"&&r.$async===!0?t.return(lj.default.data):(t.assign((0,cj._)`${n}.errors`,null),t.return(!0))}Oo.topBoolOrEmptySchema=dj;function fj(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),BR(e)):r.var(t,!0)}Oo.boolOrEmptySchema=fj;function BR(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,aj.reportError)(i,uj,void 0,t)}});var _m=A(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.getRules=No.isJSONType=void 0;var pj=["string","number","integer","boolean","null","object","array"],mj=new Set(pj);function hj(e){return typeof e=="string"&&mj.has(e)}No.isJSONType=hj;function gj(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}No.getRules=gj});var Am=A(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.shouldUseRule=Ln.shouldUseGroup=Ln.schemaHasRulesForType=void 0;function wj({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&KR(e,n)}Ln.schemaHasRulesForType=wj;function KR(e,t){return t.rules.some(r=>JR(e,r))}Ln.shouldUseGroup=KR;function JR(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Ln.shouldUseRule=JR});var ga=A(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.reportTypeError=bt.checkDataTypes=bt.checkDataType=bt.coerceAndCheckDataType=bt.getJSONTypes=bt.getSchemaTypes=bt.DataType=void 0;var yj=_m(),vj=Am(),kj=ha(),se=de(),zR=ve(),To;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(To||(bt.DataType=To={}));function bj(e){let t=GR(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}bt.getSchemaTypes=bj;function GR(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(yj.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}bt.getJSONTypes=GR;function Rj(e,t){let{gen:r,data:n,opts:i}=e,o=Sj(t,i.coerceTypes),s=t.length>0&&!(o.length===0&&t.length===1&&(0,vj.schemaHasRulesForType)(e,t[0]));if(s){let c=Pm(t,n,i.strictNumbers,To.Wrong);r.if(c,()=>{o.length?Cj(e,t,o):Im(e)})}return s}bt.coerceAndCheckDataType=Rj;var YR=new Set(["string","number","integer","boolean","null"]);function Sj(e,t){return t?e.filter(r=>YR.has(r)||t==="array"&&r==="array"):[]}function Cj(e,t,r){let{gen:n,data:i,opts:o}=e,s=n.let("dataType",(0,se._)`typeof ${i}`),c=n.let("coerced",(0,se._)`undefined`);o.coerceTypes==="array"&&n.if((0,se._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,se._)`${i}[0]`).assign(s,(0,se._)`typeof ${i}`).if(Pm(t,i,o.strictNumbers),()=>n.assign(c,i))),n.if((0,se._)`${c} !== undefined`);for(let f of r)(YR.has(f)||f==="array"&&o.coerceTypes==="array")&&u(f);n.else(),Im(e),n.endIf(),n.if((0,se._)`${c} !== undefined`,()=>{n.assign(i,c),Ej(e,c)});function u(f){switch(f){case"string":n.elseIf((0,se._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,se._)`"" + ${i}`).elseIf((0,se._)`${i} === null`).assign(c,(0,se._)`""`);return;case"number":n.elseIf((0,se._)`${s} == "boolean" || ${i} === null
144
+ || (${s} == "string" && ${i} && ${i} == +${i})`).assign(c,(0,se._)`+${i}`);return;case"integer":n.elseIf((0,se._)`${s} === "boolean" || ${i} === null
145
+ || (${s} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(c,(0,se._)`+${i}`);return;case"boolean":n.elseIf((0,se._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(c,!1).elseIf((0,se._)`${i} === "true" || ${i} === 1`).assign(c,!0);return;case"null":n.elseIf((0,se._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(c,null);return;case"array":n.elseIf((0,se._)`${s} === "string" || ${s} === "number"
146
+ || ${s} === "boolean" || ${i} === null`).assign(c,(0,se._)`[${i}]`)}}}function Ej({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,se._)`${t} !== undefined`,()=>e.assign((0,se._)`${t}[${r}]`,n))}function xm(e,t,r,n=To.Correct){let i=n===To.Correct?se.operators.EQ:se.operators.NEQ,o;switch(e){case"null":return(0,se._)`${t} ${i} null`;case"array":o=(0,se._)`Array.isArray(${t})`;break;case"object":o=(0,se._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=s((0,se._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=s();break;default:return(0,se._)`typeof ${t} ${i} ${e}`}return n===To.Correct?o:(0,se.not)(o);function s(c=se.nil){return(0,se.and)((0,se._)`typeof ${t} == "number"`,c,r?(0,se._)`isFinite(${t})`:se.nil)}}bt.checkDataType=xm;function Pm(e,t,r,n){if(e.length===1)return xm(e[0],t,r,n);let i,o=(0,zR.toHash)(e);if(o.array&&o.object){let s=(0,se._)`typeof ${t} != "object"`;i=o.null?s:(0,se._)`!${t} || ${s}`,delete o.null,delete o.array,delete o.object}else i=se.nil;o.number&&delete o.integer;for(let s in o)i=(0,se.and)(i,xm(s,t,r,n));return i}bt.checkDataTypes=Pm;var _j={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,se._)`{type: ${e}}`:(0,se._)`{type: ${t}}`};function Im(e){let t=Aj(e);(0,kj.reportError)(t,_j)}bt.reportTypeError=Im;function Aj(e){let{gen:t,data:r,schema:n}=e,i=(0,zR.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var QR=A(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});du.assignDefaults=void 0;var $o=de(),xj=ve();function Pj(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)XR(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,o)=>XR(e,o,i.default))}du.assignDefaults=Pj;function XR(e,t,r){let{gen:n,compositeRule:i,data:o,opts:s}=e;if(r===void 0)return;let c=(0,$o._)`${o}${(0,$o.getProperty)(t)}`;if(i){(0,xj.checkStrictMode)(e,`default is ignored for: ${c}`);return}let u=(0,$o._)`${c} === undefined`;s.useDefaults==="empty"&&(u=(0,$o._)`${u} || ${c} === null || ${c} === ""`),n.if(u,(0,$o._)`${c} = ${(0,$o.stringify)(r)}`)}});var lr=A(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.validateUnion=Oe.validateArray=Oe.usePattern=Oe.callValidateCode=Oe.schemaProperties=Oe.allSchemaProperties=Oe.noPropertyInData=Oe.propertyInData=Oe.isOwnProperty=Oe.hasPropFunc=Oe.reportMissingProp=Oe.checkMissingProp=Oe.checkReportMissingProp=void 0;var De=de(),Om=ve(),Mn=sn(),Ij=ve();function Oj(e,t){let{gen:r,data:n,it:i}=e;r.if(Tm(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,De._)`${t}`},!0),e.error()})}Oe.checkReportMissingProp=Oj;function Nj({gen:e,data:t,it:{opts:r}},n,i){return(0,De.or)(...n.map(o=>(0,De.and)(Tm(e,t,o,r.ownProperties),(0,De._)`${i} = ${o}`)))}Oe.checkMissingProp=Nj;function Tj(e,t){e.setParams({missingProperty:t},!0),e.error()}Oe.reportMissingProp=Tj;function ZR(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,De._)`Object.prototype.hasOwnProperty`})}Oe.hasPropFunc=ZR;function Nm(e,t,r){return(0,De._)`${ZR(e)}.call(${t}, ${r})`}Oe.isOwnProperty=Nm;function $j(e,t,r,n){let i=(0,De._)`${t}${(0,De.getProperty)(r)} !== undefined`;return n?(0,De._)`${i} && ${Nm(e,t,r)}`:i}Oe.propertyInData=$j;function Tm(e,t,r,n){let i=(0,De._)`${t}${(0,De.getProperty)(r)} === undefined`;return n?(0,De.or)(i,(0,De.not)(Nm(e,t,r))):i}Oe.noPropertyInData=Tm;function eS(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Oe.allSchemaProperties=eS;function jj(e,t){return eS(t).filter(r=>!(0,Om.alwaysValidSchema)(e,t[r]))}Oe.schemaProperties=jj;function Dj({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:o},it:s},c,u,f){let a=f?(0,De._)`${e}, ${t}, ${n}${i}`:t,d=[[Mn.default.instancePath,(0,De.strConcat)(Mn.default.instancePath,o)],[Mn.default.parentData,s.parentData],[Mn.default.parentDataProperty,s.parentDataProperty],[Mn.default.rootData,Mn.default.rootData]];s.opts.dynamicRef&&d.push([Mn.default.dynamicAnchors,Mn.default.dynamicAnchors]);let p=(0,De._)`${a}, ${r.object(...d)}`;return u!==De.nil?(0,De._)`${c}.call(${u}, ${p})`:(0,De._)`${c}(${p})`}Oe.callValidateCode=Dj;var qj=(0,De._)`new RegExp`;function Lj({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,o=i(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,De._)`${i.code==="new RegExp"?qj:(0,Ij.useFunc)(e,i)}(${r}, ${n})`})}Oe.usePattern=Lj;function Mj(e){let{gen:t,data:r,keyword:n,it:i}=e,o=t.name("valid");if(i.allErrors){let c=t.let("valid",!0);return s(()=>t.assign(c,!1)),c}return t.var(o,!0),s(()=>t.break()),o;function s(c){let u=t.const("len",(0,De._)`${r}.length`);t.forRange("i",0,u,f=>{e.subschema({keyword:n,dataProp:f,dataPropType:Om.Type.Num},o),t.if((0,De.not)(o),c)})}}Oe.validateArray=Mj;function Wj(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(u=>(0,Om.alwaysValidSchema)(i,u))&&!i.opts.unevaluated)return;let s=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((u,f)=>{let a=e.subschema({keyword:n,schemaProp:f,compositeRule:!0},c);t.assign(s,(0,De._)`${s} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,De.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}Oe.validateUnion=Wj});var nS=A(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.validateKeywordUsage=Vr.validSchemaType=Vr.funcKeywordCode=Vr.macroKeywordCode=void 0;var Ot=de(),Ii=sn(),Fj=lr(),Hj=ha();function Vj(e,t){let{gen:r,keyword:n,schema:i,parentSchema:o,it:s}=e,c=t.macro.call(s.self,i,o,s),u=rS(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let f=r.name("valid");e.subschema({schema:c,schemaPath:Ot.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:u,compositeRule:!0},f),e.pass(f,()=>e.error(!0))}Vr.macroKeywordCode=Vj;function Bj(e,t){var r;let{gen:n,keyword:i,schema:o,parentSchema:s,$data:c,it:u}=e;Kj(u,t);let f=!c&&t.compile?t.compile.call(u.self,o,s,u):t.validate,a=rS(n,i,f),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1)h(),t.modifying&&tS(e),g(()=>e.error());else{let w=t.async?l():m();t.modifying&&tS(e),g(()=>Uj(e,w))}}function l(){let w=n.let("ruleErrs",null);return n.try(()=>h((0,Ot._)`await `),k=>n.assign(d,!1).if((0,Ot._)`${k} instanceof ${u.ValidationError}`,()=>n.assign(w,(0,Ot._)`${k}.errors`),()=>n.throw(k))),w}function m(){let w=(0,Ot._)`${a}.errors`;return n.assign(w,null),h(Ot.nil),w}function h(w=t.async?(0,Ot._)`await `:Ot.nil){let k=u.opts.passContext?Ii.default.this:Ii.default.self,b=!("compile"in t&&!c||t.schema===!1);n.assign(d,(0,Ot._)`${w}${(0,Fj.callValidateCode)(e,a,k,b)}`,t.modifying)}function g(w){var k;n.if((0,Ot.not)((k=t.valid)!==null&&k!==void 0?k:d),w)}}Vr.funcKeywordCode=Bj;function tS(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ot._)`${n.parentData}[${n.parentDataProperty}]`))}function Uj(e,t){let{gen:r}=e;r.if((0,Ot._)`Array.isArray(${t})`,()=>{r.assign(Ii.default.vErrors,(0,Ot._)`${Ii.default.vErrors} === null ? ${t} : ${Ii.default.vErrors}.concat(${t})`).assign(Ii.default.errors,(0,Ot._)`${Ii.default.vErrors}.length`),(0,Hj.extendErrors)(e)},()=>e.error())}function Kj({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function rS(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ot.stringify)(r)})}function Jj(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Vr.validSchemaType=Jj;function zj({schema:e,opts:t,self:r,errSchemaPath:n},i,o){if(Array.isArray(i.keyword)?!i.keyword.includes(o):i.keyword!==o)throw new Error("ajv implementation error");let s=i.dependencies;if(s?.some(c=>!Object.prototype.hasOwnProperty.call(e,c)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[o])){let u=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(u);else throw new Error(u)}}Vr.validateKeywordUsage=zj});var oS=A(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.extendSubschemaMode=Wn.extendSubschemaData=Wn.getSubschema=void 0;var Br=de(),iS=ve();function Gj(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:o,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let c=e.schema[t];return r===void 0?{schema:c,schemaPath:(0,Br._)`${e.schemaPath}${(0,Br.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,Br._)`${e.schemaPath}${(0,Br.getProperty)(t)}${(0,Br.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,iS.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Wn.getSubschema=Gj;function Yj(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:o,propertyName:s}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(r!==void 0){let{errorPath:f,dataPathArr:a,opts:d}=t,p=c.let("data",(0,Br._)`${t.data}${(0,Br.getProperty)(r)}`,!0);u(p),e.errorPath=(0,Br.str)`${f}${(0,iS.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0,Br._)`${r}`,e.dataPathArr=[...a,e.parentDataProperty]}if(i!==void 0){let f=i instanceof Br.Name?i:c.let("data",i,!0);u(f),s!==void 0&&(e.propertyName=s)}o&&(e.dataTypes=o);function u(f){e.data=f,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,f]}}Wn.extendSubschemaData=Yj;function Xj(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:o}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),o!==void 0&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r}Wn.extendSubschemaMode=Xj});var $m=A((_G,sS)=>{"use strict";sS.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var cS=A((AG,aS)=>{"use strict";var Fn=aS.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};fu(t,n,i,e,"",e)};Fn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Fn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Fn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Fn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function fu(e,t,r,n,i,o,s,c,u,f){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,o,s,c,u,f);for(var a in n){var d=n[a];if(Array.isArray(d)){if(a in Fn.arrayKeywords)for(var p=0;p<d.length;p++)fu(e,t,r,d[p],i+"/"+a+"/"+p,o,i,a,n,p)}else if(a in Fn.propsKeywords){if(d&&typeof d=="object")for(var l in d)fu(e,t,r,d[l],i+"/"+a+"/"+Qj(l),o,i,a,n,l)}else(a in Fn.keywords||e.allKeys&&!(a in Fn.skipKeywords))&&fu(e,t,r,d,i+"/"+a,o,i,a,n)}r(n,i,o,s,c,u,f)}}function Qj(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var wa=A(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.getSchemaRefs=Ut.resolveUrl=Ut.normalizeId=Ut._getFullPath=Ut.getFullPath=Ut.inlineRef=void 0;var Zj=ve(),eD=$m(),tD=cS(),rD=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function nD(e,t=!0){return typeof e=="boolean"?!0:t===!0?!jm(e):t?lS(e)<=t:!1}Ut.inlineRef=nD;var iD=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function jm(e){for(let t in e){if(iD.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(jm)||typeof r=="object"&&jm(r))return!0}return!1}function lS(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!rD.has(r)&&(typeof e[r]=="object"&&(0,Zj.eachItem)(e[r],n=>t+=lS(n)),t===1/0))return 1/0}return t}function uS(e,t="",r){r!==!1&&(t=jo(t));let n=e.parse(t);return dS(e,n)}Ut.getFullPath=uS;function dS(e,t){return e.serialize(t).split("#")[0]+"#"}Ut._getFullPath=dS;var oD=/#\/?$/;function jo(e){return e?e.replace(oD,""):""}Ut.normalizeId=jo;function sD(e,t,r){return r=jo(r),e.resolve(t,r)}Ut.resolveUrl=sD;var aD=/^[a-z_][-a-z0-9._]*$/i;function cD(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=jo(e[r]||t),o={"":i},s=uS(n,i,!1),c={},u=new Set;return tD(e,{allKeys:!0},(d,p,l,m)=>{if(m===void 0)return;let h=s+p,g=o[m];typeof d[r]=="string"&&(g=w.call(this,d[r])),k.call(this,d.$anchor),k.call(this,d.$dynamicAnchor),o[p]=g;function w(b){let S=this.opts.uriResolver.resolve;if(b=jo(g?S(g,b):b),u.has(b))throw a(b);u.add(b);let E=this.refs[b];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?f(d,E.schema,b):b!==jo(h)&&(b[0]==="#"?(f(d,c[b],b),c[b]=d):this.refs[b]=h),b}function k(b){if(typeof b=="string"){if(!aD.test(b))throw new Error(`invalid anchor "${b}"`);w.call(this,`#${b}`)}}}),c;function f(d,p,l){if(p!==void 0&&!eD(d,p))throw a(l)}function a(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Ut.getSchemaRefs=cD});var ka=A(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.getData=Hn.KeywordCxt=Hn.validateFunctionCode=void 0;var gS=UR(),fS=ga(),qm=Am(),pu=ga(),lD=QR(),va=nS(),Dm=oS(),X=de(),re=sn(),uD=wa(),an=ve(),ya=ha();function dD(e){if(vS(e)&&(kS(e),yS(e))){mD(e);return}wS(e,()=>(0,gS.topBoolOrEmptySchema)(e))}Hn.validateFunctionCode=dD;function wS({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},o){i.code.es5?e.func(t,(0,X._)`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{e.code((0,X._)`"use strict"; ${pS(r,i)}`),pD(e,i),e.code(o)}):e.func(t,(0,X._)`${re.default.data}, ${fD(i)}`,n.$async,()=>e.code(pS(r,i)).code(o))}function fD(e){return(0,X._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${e.dynamicRef?(0,X._)`, ${re.default.dynamicAnchors}={}`:X.nil}}={}`}function pD(e,t){e.if(re.default.valCxt,()=>{e.var(re.default.instancePath,(0,X._)`${re.default.valCxt}.${re.default.instancePath}`),e.var(re.default.parentData,(0,X._)`${re.default.valCxt}.${re.default.parentData}`),e.var(re.default.parentDataProperty,(0,X._)`${re.default.valCxt}.${re.default.parentDataProperty}`),e.var(re.default.rootData,(0,X._)`${re.default.valCxt}.${re.default.rootData}`),t.dynamicRef&&e.var(re.default.dynamicAnchors,(0,X._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{e.var(re.default.instancePath,(0,X._)`""`),e.var(re.default.parentData,(0,X._)`undefined`),e.var(re.default.parentDataProperty,(0,X._)`undefined`),e.var(re.default.rootData,re.default.data),t.dynamicRef&&e.var(re.default.dynamicAnchors,(0,X._)`{}`)})}function mD(e){let{schema:t,opts:r,gen:n}=e;wS(e,()=>{r.$comment&&t.$comment&&RS(e),vD(e),n.let(re.default.vErrors,null),n.let(re.default.errors,0),r.unevaluated&&hD(e),bS(e),RD(e)})}function hD(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,X._)`${r}.evaluated`),t.if((0,X._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,X._)`${e.evaluated}.props`,(0,X._)`undefined`)),t.if((0,X._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,X._)`${e.evaluated}.items`,(0,X._)`undefined`))}function pS(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,X._)`/*# sourceURL=${r} */`:X.nil}function gD(e,t){if(vS(e)&&(kS(e),yS(e))){wD(e,t);return}(0,gS.boolOrEmptySchema)(e,t)}function yS({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function vS(e){return typeof e.schema!="boolean"}function wD(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&RS(e),kD(e),bD(e);let o=n.const("_errs",re.default.errors);bS(e,o),n.var(t,(0,X._)`${o} === ${re.default.errors}`)}function kS(e){(0,an.checkUnknownRules)(e),yD(e)}function bS(e,t){if(e.opts.jtd)return mS(e,[],!1,t);let r=(0,fS.getSchemaTypes)(e.schema),n=(0,fS.coerceAndCheckDataType)(e,r);mS(e,r,!n,t)}function yD(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,an.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function vD(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,an.checkStrictMode)(e,"default is ignored in the schema root")}function kD(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,uD.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function bD(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function RS({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let o=r.$comment;if(i.$comment===!0)e.code((0,X._)`${re.default.self}.logger.log(${o})`);else if(typeof i.$comment=="function"){let s=(0,X.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,X._)`${re.default.self}.opts.$comment(${o}, ${s}, ${c}.schema)`)}}function RD(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:o}=e;r.$async?t.if((0,X._)`${re.default.errors} === 0`,()=>t.return(re.default.data),()=>t.throw((0,X._)`new ${i}(${re.default.vErrors})`)):(t.assign((0,X._)`${n}.errors`,re.default.vErrors),o.unevaluated&&SD(e),t.return((0,X._)`${re.default.errors} === 0`))}function SD({gen:e,evaluated:t,props:r,items:n}){r instanceof X.Name&&e.assign((0,X._)`${t}.props`,r),n instanceof X.Name&&e.assign((0,X._)`${t}.items`,n)}function mS(e,t,r,n){let{gen:i,schema:o,data:s,allErrors:c,opts:u,self:f}=e,{RULES:a}=f;if(o.$ref&&(u.ignoreKeywordsWithRef||!(0,an.schemaHasRulesButRef)(o,a))){i.block(()=>CS(e,"$ref",a.all.$ref.definition));return}u.jtd||CD(e,t),i.block(()=>{for(let p of a.rules)d(p);d(a.post)});function d(p){(0,qm.shouldUseGroup)(o,p)&&(p.type?(i.if((0,pu.checkDataType)(p.type,s,u.strictNumbers)),hS(e,p),t.length===1&&t[0]===p.type&&r&&(i.else(),(0,pu.reportTypeError)(e)),i.endIf()):hS(e,p),c||i.if((0,X._)`${re.default.errors} === ${n||0}`))}}function hS(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,lD.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0,qm.shouldUseRule)(n,o)&&CS(e,o.keyword,o.definition,t.type)})}function CD(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(ED(e,t),e.opts.allowUnionTypes||_D(e,t),AD(e,e.dataTypes))}function ED(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{SS(e.dataTypes,r)||Lm(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),PD(e,t)}}function _D(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Lm(e,"use allowUnionTypes to allow union type keyword")}function AD(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,qm.shouldUseRule)(e.schema,i)){let{type:o}=i.definition;o.length&&!o.some(s=>xD(t,s))&&Lm(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function xD(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function SS(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function PD(e,t){let r=[];for(let n of e.dataTypes)SS(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Lm(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,an.checkStrictMode)(e,t,e.opts.strictTypes)}var mu=class{constructor(t,r,n){if((0,va.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,an.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",ES(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,va.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",re.default.errors))}result(t,r,n){this.failResult((0,X.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,X.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,X._)`${r} !== undefined && (${(0,X.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?ya.reportExtraError:ya.reportError)(this,this.def.error,r)}$dataError(){(0,ya.reportError)(this,this.def.$dataError||ya.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ya.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=X.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=X.nil,r=X.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:o,def:s}=this;n.if((0,X.or)((0,X._)`${i} === undefined`,r)),t!==X.nil&&n.assign(t,!0),(o.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==X.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:o}=this;return(0,X.or)(s(),c());function s(){if(n.length){if(!(r instanceof X.Name))throw new Error("ajv implementation error");let u=Array.isArray(n)?n:[n];return(0,X._)`${(0,pu.checkDataTypes)(u,r,o.opts.strictNumbers,pu.DataType.Wrong)}`}return X.nil}function c(){if(i.validateSchema){let u=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,X._)`!${u}(${r})`}return X.nil}}subschema(t,r){let n=(0,Dm.getSubschema)(this.it,t);(0,Dm.extendSubschemaData)(n,this.it,t),(0,Dm.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return gD(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=an.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=an.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,X.Name)),!0}};Hn.KeywordCxt=mu;function CS(e,t,r,n){let i=new mu(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,va.funcKeywordCode)(i,r):"macro"in r?(0,va.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,va.funcKeywordCode)(i,r)}var ID=/^\/(?:[^~]|~0|~1)*$/,OD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ES(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,o;if(e==="")return re.default.rootData;if(e[0]==="/"){if(!ID.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,o=re.default.rootData}else{let f=OD.exec(e);if(!f)throw new Error(`Invalid JSON-pointer: ${e}`);let a=+f[1];if(i=f[2],i==="#"){if(a>=t)throw new Error(u("property/index",a));return n[t-a]}if(a>t)throw new Error(u("data",a));if(o=r[t-a],!i)return o}let s=o,c=i.split("/");for(let f of c)f&&(o=(0,X._)`${o}${(0,X.getProperty)((0,an.unescapeJsonPointer)(f))}`,s=(0,X._)`${s} && ${o}`);return s;function u(f,a){return`Cannot access ${f} ${a} levels up, current level is ${t}`}}Hn.getData=ES});var hu=A(Wm=>{"use strict";Object.defineProperty(Wm,"__esModule",{value:!0});var Mm=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Wm.default=Mm});var ba=A(Vm=>{"use strict";Object.defineProperty(Vm,"__esModule",{value:!0});var Fm=wa(),Hm=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Fm.resolveUrl)(t,r,n),this.missingSchema=(0,Fm.normalizeId)((0,Fm.getFullPath)(t,this.missingRef))}};Vm.default=Hm});var wu=A(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;var _r=de(),ND=hu(),Oi=sn(),Ar=wa(),_S=ve(),TD=ka(),Do=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,Ar.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};ur.SchemaEnv=Do;function Um(e){let t=AS.call(this,e);if(t)return t;let r=(0,Ar.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:o}=this.opts,s=new _r.CodeGen(this.scope,{es5:n,lines:i,ownProperties:o}),c;e.$async&&(c=s.scopeValue("Error",{ref:ND.default,code:(0,_r._)`require("ajv/dist/runtime/validation_error").default`}));let u=s.scopeName("validate");e.validateName=u;let f={gen:s,allErrors:this.opts.allErrors,data:Oi.default.data,parentData:Oi.default.parentData,parentDataProperty:Oi.default.parentDataProperty,dataNames:[Oi.default.data],dataPathArr:[_r.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,_r.stringify)(e.schema)}:{ref:e.schema}),validateName:u,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:_r.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,_r._)`""`,opts:this.opts,self:this},a;try{this._compilations.add(e),(0,TD.validateFunctionCode)(f),s.optimize(this.opts.code.optimize);let d=s.toString();a=`${s.scopeRefs(Oi.default.scope)}return ${d}`,this.opts.code.process&&(a=this.opts.code.process(a,e));let l=new Function(`${Oi.default.self}`,`${Oi.default.scope}`,a)(this,this.scope.get());if(this.scope.value(u,{ref:l}),l.errors=null,l.schema=e.schema,l.schemaEnv=e,e.$async&&(l.$async=!0),this.opts.code.source===!0&&(l.source={validateName:u,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=f;l.evaluated={props:m instanceof _r.Name?void 0:m,items:h instanceof _r.Name?void 0:h,dynamicProps:m instanceof _r.Name,dynamicItems:h instanceof _r.Name},l.source&&(l.source.evaluated=(0,_r.stringify)(l.evaluated))}return e.validate=l,e}catch(d){throw delete e.validate,delete e.validateName,a&&this.logger.error("Error compiling schema, function code:",a),d}finally{this._compilations.delete(e)}}ur.compileSchema=Um;function $D(e,t,r){var n;r=(0,Ar.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let o=qD.call(this,e,r);if(o===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;s&&(o=new Do({schema:s,schemaId:c,root:e,baseId:t}))}if(o!==void 0)return e.refs[r]=jD.call(this,o)}ur.resolveRef=$D;function jD(e){return(0,Ar.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Um.call(this,e)}function AS(e){for(let t of this._compilations)if(DD(t,e))return t}ur.getCompilingSchema=AS;function DD(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function qD(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||gu.call(this,e,t)}function gu(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ar._getFullPath)(this.opts.uriResolver,r),i=(0,Ar.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Bm.call(this,r,e);let o=(0,Ar.normalizeId)(n),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let c=gu.call(this,e,s);return typeof c?.schema!="object"?void 0:Bm.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||Um.call(this,s),o===(0,Ar.normalizeId)(t)){let{schema:c}=s,{schemaId:u}=this.opts,f=c[u];return f&&(i=(0,Ar.resolveUrl)(this.opts.uriResolver,i,f)),new Do({schema:c,schemaId:u,root:e,baseId:i})}return Bm.call(this,r,s)}}ur.resolveSchema=gu;var LD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Bm(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let c of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let u=r[(0,_S.unescapeFragment)(c)];if(u===void 0)return;r=u;let f=typeof r=="object"&&r[this.opts.schemaId];!LD.has(c)&&f&&(t=(0,Ar.resolveUrl)(this.opts.uriResolver,t,f))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,_S.schemaHasRulesButRef)(r,this.RULES)){let c=(0,Ar.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=gu.call(this,n,c)}let{schemaId:s}=this.opts;if(o=o||new Do({schema:r,schemaId:s,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var xS=A((TG,MD)=>{MD.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Xm=A(($G,DS)=>{"use strict";var WD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Jm=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),FD=RegExp.prototype.test.bind(/^\d*$/u),Ni=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),zm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),IS=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Gm=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),HD=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Kt=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)Kt[t]="%"+e[t>>4]+e[t&15]}function Rt(e){return e<2048?Kt[192|e>>6]+Kt[128|e&63]:e<65536?Kt[224|e>>12]+Kt[128|e>>6&63]+Kt[128|e&63]:Kt[240|e>>18]+Kt[128|e>>12&63]+Kt[128|e>>6&63]+Kt[128|e&63]}function VD(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var BD=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),UD=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),KD=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),JD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function zD(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!KD(e[t])){if(e[t]==="%"&&t+2<e.length&&Ni(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function PS(e){let t=-1,r=0,n=-1,i=0;for(let c=0;c<e.length;c++)e[c]==="0"?(n===-1&&(n=c),i++,i>r&&(r=i,t=n)):(n=-1,i=0);if(r<2)return e.join(":");let o=e.slice(0,t).join(":"),s=e.slice(t+r).join(":");return o+"::"+s}function GD(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=r.concat(n),o=0;for(let c=0;c<i.length;c++){let u=i[c];if(u==="")return;if(u.indexOf(".")!==-1){if(c!==i.length-1||t!==-1&&n.length===0||!Jm(u))return;o+=2;continue}if(!BD(u))return;i[c]=parseInt(u,16).toString(16),o++}if(t===-1)return o!==8?void 0:PS(i);if(o>=8)return;let s=i.slice(0,r.length);for(let c=o;c<8;c++)s.push("0");for(let c=r.length;c<i.length;c++)s.push(i[c]);return PS(s)}function Km(e){let t=e[0]==="["&&e[e.length-1]==="]";if((e[0]==="["||e[e.length-1]==="]")&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&UD(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(YD(n,":")<2)return{host:e,isIPV6:!1,error:t};let i="",o=n.indexOf("%");if(o!==-1){let c=n.slice(o,o+3).toLowerCase()==="%25"?3:1;if(i=n.slice(o+c),!zD(i))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,o)}let s=GD(n);return s===void 0?{host:e,isIPV6:!1,error:!0}:{host:s+(i?"%"+i:""),escapedHost:s+(i?"%25"+i:""),isIPV6:!0}}function YD(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function OS(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function XD(e){if(e===""||e[0]==="/")return OS(e);let t=e.split("/"),r=t.length-1,n=[],i=!1;for(let o=0;o<=r;o++){let s=t[o];s==="."||s===".."?(s===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),i=o===r):n.push(s)}return i&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var QD={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ZD=/[@/?#:]/g,e1=/[@/?#]/g;function NS(e,t){let r=t?e1:ZD;return r.lastIndex=0,e.replace(r,n=>QD[n])}function TS(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(Ni(i)){let o=i.toUpperCase(),s=String.fromCharCode(parseInt(o,16));t&&zm(s)?r+=s:r+="%"+o,n+=2;continue}}r+=e[n]}return r}function t1(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(Ni(i)){let o=i.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&zm(s)?t+=s:t+="%"+o,r+=2;continue}}if(IS(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=jS(i)?n:Kt[i];else if(i<55296||i>57343)t+=Rt(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=Rt(65536+(i-55296<<10)+(o-56320)),r++):t+=Rt(65533)}else t+=Rt(65533)}}return t}function r1(e,t=!1){let r="",n=t&&e[0]!=="/";for(let i=0;i<e.length;i++){let o=e[i];if(o==="%"&&i+2<e.length){let s=e.slice(i+1,i+3);if(Ni(s)){r+="%"+s.toUpperCase(),i+=2;continue}}if(o==="/"&&(n=!1),IS(o)&&(o!==":"||!n))r+=o;else{let s=e.charCodeAt(i);if(s<128)r+=Kt[s];else if(s<55296||s>57343)r+=Rt(s);else if(s<=56319&&i+1<e.length){let c=e.charCodeAt(i+1);c>=56320&&c<=57343?(r+=Rt(65536+(s-55296<<10)+(c-56320)),i++):r+=Rt(65533)}else r+=Rt(65533)}}return r}function Ym(e,t){let r="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Ni(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(t(i))r+=i;else{let o=e.charCodeAt(n);if(o<128)r+=Kt[o];else if(o<55296||o>57343)r+=Rt(o);else if(o<=56319&&n+1<e.length){let s=e.charCodeAt(n+1);s>=56320&&s<=57343?(r+=Rt(65536+(o-55296<<10)+(s-56320)),n++):r+=Rt(65533)}else r+=Rt(65533)}}return r}function $S(e){return Ym(e,HD)}function n1(e){return Ym(e,Gm)}function i1(e){return Ym(e,Gm)}function jS(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function o1(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(Ni(i)){let o=i.toUpperCase(),s=String.fromCharCode(parseInt(o,16));zm(s)?t+=s:t+="%"+o,r+=2;continue}}if(Gm(n))t+=n;else{let i=e.charCodeAt(r);if(i<128)t+=jS(i)?n:Kt[i];else if(i<55296||i>57343)t+=Rt(i);else if(i<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(t+=Rt(65536+(i-55296<<10)+(o-56320)),r++):t+=Rt(65533)}else t+=Rt(65533)}}return t}function s1(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Ni(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function a1(e){let t=[];if(e.userinfo!==void 0&&(t.push($S(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!Jm(r)){let n=Km(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=TS(r,!0),n=Km(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=NS(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!FD(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}DS.exports={nonSimpleDomain:JD,recomposeAuthority:a1,reescapeHostDelimiters:NS,normalizePercentEncoding:TS,normalizePathEncoding:t1,serializePathEncoding:r1,normalizeQueryFragmentEncoding:o1,encodeUserinfo:$S,encodeQuery:n1,encodeFragment:i1,escapePreservingEscapes:s1,removeDotSegments:OS,removeDotSegmentsRelative:XD,isIPv4:Jm,isUUID:WD,normalizeIPv6:Km,stringArrayToHexStripped:VD}});var FS=A((jG,WS)=>{"use strict";var{isUUID:c1}=Xm(),l1=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,u1=["http","https","ws","wss","urn","urn:uuid"];function d1(e){return u1.indexOf(e)!==-1}function Qm(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function qS(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function LS(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function f1(e){return e.secure=Qm(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function p1(e){if((e.port===(Qm(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function m1(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(l1);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,o=Zm(i);e.path=void 0,o&&(e=o.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function h1(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,o=Zm(i);o&&(e=o.serialize(e,t));let s=e,c=e.nss;return s.path=`${n||t.nid}:${c}`,t.skipEscape=!0,s}function g1(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!c1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function w1(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var MS={scheme:"http",domainHost:!0,parse:qS,serialize:LS},y1={scheme:"https",domainHost:MS.domainHost,parse:qS,serialize:LS},yu={scheme:"ws",domainHost:!0,parse:f1,serialize:p1},v1={scheme:"wss",domainHost:yu.domainHost,parse:yu.parse,serialize:yu.serialize},k1={scheme:"urn",parse:m1,serialize:h1,skipNormalize:!0},b1={scheme:"urn:uuid",parse:g1,serialize:w1,skipNormalize:!0},vu={http:MS,https:y1,ws:yu,wss:v1,urn:k1,"urn:uuid":b1};Object.setPrototypeOf(vu,null);function Zm(e){return e&&(vu[e]||vu[e.toLowerCase()])||void 0}WS.exports={wsIsSecure:Qm,SCHEMES:vu,isValidSchemeName:d1,getSchemeHandler:Zm}});var rC=A((DG,Cu)=>{"use strict";var{normalizeIPv6:KS,removeDotSegments:Sa,removeDotSegmentsRelative:JS,recomposeAuthority:R1,normalizePercentEncoding:eh,normalizePathEncoding:S1,serializePathEncoding:HS,normalizeQueryFragmentEncoding:VS,encodeQuery:C1,encodeFragment:E1,reescapeHostDelimiters:_1,isIPv4:zS,nonSimpleDomain:A1}=Xm(),{SCHEMES:GS,getSchemeHandler:th}=FS(),YS=/^[A-Za-z][A-Za-z0-9+.-]*$/u,XS="URI scheme is malformed.",ku="URI host is malformed.",x1=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function BS(e){let t=String(e);if(!YS.test(t))throw new TypeError(XS);return t}function P1(e,t){return typeof e=="string"?e=L1(e,t):typeof e=="object"&&(e=Ru(Ti(e,t),t)),e}function I1(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:u,malformedScheme:f}=bu(e,n),{parsed:a,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:l,malformedHost:m,malformedScheme:h}=bu(t,n);if(o||d||s||p||c||l||u||m||f||h)throw new Error(i.error||a.error||"URI is malformed.");let g=QS(i,a,n,!0),w=th(r&&r.scheme||g.scheme),k=g.host,b=k!==void 0&&k!==""&&(zS(k)||KS(k).isIPV6);if(eC(g,r||{},w,b))throw new Error(ku);ZS(g,r||{},w,b);let S=k&&k.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(k);if(g.error&&!S)throw new Error(g.error);return n.skipEscape=!0,Ti(g,n)}function QS(e,t,r,n){let i={};if(n||(e=Ru(Ti(e,r),r),t=Ru(Ti(t,r),r)),r=r||{},!r.tolerant&&t.scheme)i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=Sa(t.path||""),i.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=Sa(t.path||""),i.query=t.query;else{if(!t.path)i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query;else{if(t.path[0]==="/")i.path=Sa(t.path);else{let o=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;o&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=e.scheme===void 0&&!o&&i.path[0]!=="/"?JS(i.path):Sa(i.path)}i.query=t.query}i.userinfo=e.userinfo,i.host=e.host,i.port=e.port}i.scheme=e.scheme}return i.fragment=t.fragment,i}function O1(e,t,r){let n=US(e,r),i=US(t,r);return n!==void 0&&i!==void 0&&n===i}function Ti(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[];r.scheme&&(r.scheme=BS(r.scheme));let o=th(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n);let s=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,c=(r.scheme===void 0||n.reference==="suffix")&&!s,u=!n.skipEscape&&c;r.path!==void 0&&(n.skipEscape?r.path=eh(r.path):r.path=HS(r.path,u)),n.reference!=="suffix"&&r.scheme&&(r.scheme=BS(r.scheme),i.push(r.scheme,":"));let f=R1(r);if(f!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(f),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=c&&a[0]!=="/"?JS(a):Sa(a)),c&&(a=HS(a,!0)),f===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",C1(r.query)),r.fragment!==void 0&&i.push("#",E1(r.fragment)),i.join("")}var N1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,T1=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,$1=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function j1(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Ra(e){if(e===void 0)return!1;let t=e.indexOf("%");for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function Su(e){return e[0]==="["&&e[e.length-1]==="]"}function D1(e){let t=e[4];return Ra(e[3])||t!==void 0&&!Su(t)&&Ra(t)||Ra(e[6])||Ra(e[7])||Ra(e[8])}function ZS(e,t,r,n){if(eC(e,t,r,n))return e.error=e.error||ku,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!Su(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&A1(e.host)){let i;try{i=new URL("http://"+e.host)}catch(o){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+o,!0}if(!q1(i))return e.error=e.error||ku,!0;e.host=i.hostname}return!1}function eC(e,t,r,n){return!!(e.host&&n===!1&&!Su(e.host)&&(t.domainHost||r&&r.domainHost)&&x1.test(e.host))}function q1(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function bu(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,o=!1,s=!1,c=!1,u=!1,f=!1,a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let d=e.match(T1);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let p=e.match($1);if(p!==null){let m=p[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):m.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let l=e.match(N1);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],n.scheme!==void 0&&(YS.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||XS,f=!0)),o=D1(l),o&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=l[5]);let m=j1(n,l);if(m!==void 0&&(n.error=n.error||m,i=!0),n.host)if(zS(n.host)===!1){let w=Su(n.host),k=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,b=KS(n.host);a=b.isIPV6||b.isIPVFuture===!0,u=k&&(!w||b.error===!0),n.host=a?b.host:b.host.toLowerCase(),u&&(n.error=n.error||ku,i=!0)}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=th(r.scheme||n.scheme);if(u||(c=ZS(n,r,h,a)),e.indexOf("%")!==-1&&n.host!==void 0&&!u){let g=a?n.host:eh(n.host,!0);a||(g=eh(g.toLowerCase())),n.host=a||r.scheme!=="null"?_1(g,a):g}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=S1(n.path)),n.query&&(n.query=VS(n.query)),n.fragment&&(n.fragment=VS(n.fragment))),h&&h.parse&&(h.parse(n,r),h===GS.urn&&n.nid===void 0&&(s=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:c,malformedScheme:f}}function Ru(e,t){return bu(e,t).parsed}function L1(e,t){return tC(e,t).normalized}function tC(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=bu(e,t);return{normalized:n||i||o||s||c?e:Ti(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}}function US(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Ti(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:c,malformedScheme:u}=tC(r,t);return i||o||s||c||u?void 0:n}var rh={SCHEMES:GS,normalize:P1,resolve:I1,resolveComponent:QS,equal:O1,serialize:Ti,parse:Ru};Cu.exports=rh;Cu.exports.default=rh;Cu.exports.fastUri=rh});var iC=A(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var nC=rC();nC.code='require("ajv/dist/runtime/uri").default';nh.default=nC});var fC=A(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.CodeGen=pt.Name=pt.nil=pt.stringify=pt.str=pt._=pt.KeywordCxt=void 0;var M1=ka();Object.defineProperty(pt,"KeywordCxt",{enumerable:!0,get:function(){return M1.KeywordCxt}});var qo=de();Object.defineProperty(pt,"_",{enumerable:!0,get:function(){return qo._}});Object.defineProperty(pt,"str",{enumerable:!0,get:function(){return qo.str}});Object.defineProperty(pt,"stringify",{enumerable:!0,get:function(){return qo.stringify}});Object.defineProperty(pt,"nil",{enumerable:!0,get:function(){return qo.nil}});Object.defineProperty(pt,"Name",{enumerable:!0,get:function(){return qo.Name}});Object.defineProperty(pt,"CodeGen",{enumerable:!0,get:function(){return qo.CodeGen}});var W1=hu(),lC=ba(),F1=_m(),Ca=wu(),H1=de(),Ea=wa(),Eu=ga(),oh=ve(),oC=xS(),V1=iC(),uC=(e,t)=>new RegExp(e,t);uC.code="new RegExp";var B1=["removeAdditional","useDefaults","coerceTypes"],U1=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),K1={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},J1={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},sC=200;function z1(e){var t,r,n,i,o,s,c,u,f,a,d,p,l,m,h,g,w,k,b,S,E,O,K,D,Y;let Q=e.strict,te=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=te===!0||te===void 0?1:te||0,Pe=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:uC,ee=(i=e.uriResolver)!==null&&i!==void 0?i:V1.default;return{strictSchema:(s=(o=e.strictSchema)!==null&&o!==void 0?o:Q)!==null&&s!==void 0?s:!0,strictNumbers:(u=(c=e.strictNumbers)!==null&&c!==void 0?c:Q)!==null&&u!==void 0?u:!0,strictTypes:(a=(f=e.strictTypes)!==null&&f!==void 0?f:Q)!==null&&a!==void 0?a:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:Q)!==null&&p!==void 0?p:"log",strictRequired:(m=(l=e.strictRequired)!==null&&l!==void 0?l:Q)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Z,regExp:Pe}:{optimize:Z,regExp:Pe},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:sC,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:sC,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(k=e.messages)!==null&&k!==void 0?k:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(S=e.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(E=e.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(O=e.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(K=e.validateFormats)!==null&&K!==void 0?K:!0,unicodeRegExp:(D=e.unicodeRegExp)!==null&&D!==void 0?D:!0,int32range:(Y=e.int32range)!==null&&Y!==void 0?Y:!0,uriResolver:ee}}var _a=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...z1(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new H1.ValueScope({scope:{},prefixes:U1,es5:r,lines:n}),this.logger=eq(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,F1.getRules)(),aC.call(this,K1,t,"NOT SUPPORTED"),aC.call(this,J1,t,"DEPRECATED","warn"),this._metaOpts=Q1.call(this),t.formats&&Y1.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&X1.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),G1.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=oC;n==="id"&&(i={...oC},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(a,d){await o.call(this,a.$schema);let p=this._addSchema(a,d);return p.validate||s.call(this,p)}async function o(a){a&&!this.getSchema(a)&&await i.call(this,{$ref:a},!0)}async function s(a){try{return this._compileSchemaEnv(a)}catch(d){if(!(d instanceof lC.default))throw d;return c.call(this,d),await u.call(this,d.missingSchema),s.call(this,a)}}function c({missingSchema:a,missingRef:d}){if(this.refs[a])throw new Error(`AnySchema ${a} is loaded but ${d} cannot be resolved`)}async function u(a){let d=await f.call(this,a);this.refs[a]||await o.call(this,d.$schema),this.refs[a]||this.addSchema(d,a,r)}async function f(a){let d=this._loading[a];if(d)return d;try{return await(this._loading[a]=n(a))}finally{delete this._loading[a]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,i);return this}let o;if(typeof t=="object"){let{schemaId:s}=this.opts;if(o=t[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Ea.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return i}getSchema(t){let r;for(;typeof(r=cC.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Ca.SchemaEnv({schema:{},schemaId:n});if(r=Ca.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=cC.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Ea.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(rq.call(this,n,r),!r)return(0,oh.eachItem)(n,o=>ih.call(this,o)),this;iq.call(this,r);let i={...r,type:(0,Eu.getJSONTypes)(r.type),schemaType:(0,Eu.getJSONTypes)(r.schemaType)};return(0,oh.eachItem)(n,i.type.length===0?o=>ih.call(this,o,i):o=>i.type.forEach(s=>ih.call(this,o,i,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(o=>o.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,o)=>i+r+o)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let o=i.split("/").slice(1),s=t;for(let c of o)s=s[c];for(let c in n){let u=n[c];if(typeof u!="object")continue;let{$data:f}=u.definition,a=s[c];f&&a&&(s[c]=dC(a))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,o=this.opts.addUsedSchema){let s,{schemaId:c}=this.opts;if(typeof t=="object")s=t[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let u=this._cache.get(t);if(u!==void 0)return u;n=(0,Ea.normalizeId)(s||n);let f=Ea.getSchemaRefs.call(this,t,n);return u=new Ca.SchemaEnv({schema:t,schemaId:c,meta:r,baseId:n,localRefs:f}),this._cache.set(u.schema,u),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=u),i&&this.validateSchema(t,!0),u}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Ca.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Ca.compileSchema.call(this,t)}finally{this.opts=r}}};_a.ValidationError=W1.default;_a.MissingRefError=lC.default;pt.default=_a;function aC(e,t,r,n="error"){for(let i in e){let o=i;o in t&&this.logger[n](`${r}: option ${i}. ${e[o]}`)}}function cC(e){return e=(0,Ea.normalizeId)(e),this.schemas[e]||this.refs[e]}function G1(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function Y1(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function X1(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function Q1(){let e={...this.opts};for(let t of B1)delete e[t];return e}var Z1={log(){},warn(){},error(){}};function eq(e){if(e===!1)return Z1;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var tq=/^[a-z_$][a-z0-9_$:-]*$/i;function rq(e,t){let{RULES:r}=this;if((0,oh.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!tq.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function ih(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=i?o.post:o.rules.find(({type:u})=>u===r);if(s||(s={type:r,rules:[]},o.rules.push(s)),o.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,Eu.getJSONTypes)(t.type),schemaType:(0,Eu.getJSONTypes)(t.schemaType)}};t.before?nq.call(this,s,c,t.before):s.rules.push(c),o.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(u=>this.addKeyword(u))}function nq(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function iq(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=dC(t)),e.validateSchema=this.compile(t,!0))}var oq={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function dC(e){return{anyOf:[e,oq]}}});var pC=A(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var sq={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sh.default=sq});var wC=A($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.callRef=$i.getValidate=void 0;var aq=ba(),mC=lr(),Jt=de(),Lo=sn(),hC=wu(),_u=ve(),cq={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:o,validateName:s,opts:c,self:u}=n,{root:f}=o;if((r==="#"||r==="#/")&&i===f.baseId)return d();let a=hC.resolveRef.call(u,f,i,r);if(a===void 0)throw new aq.default(n.opts.uriResolver,i,r);if(a instanceof hC.SchemaEnv)return p(a);return l(a);function d(){if(o===f)return Au(e,s,o,o.$async);let m=t.scopeValue("root",{ref:f});return Au(e,(0,Jt._)`${m}.validate`,f,f.$async)}function p(m){let h=gC(e,m);Au(e,h,m,m.$async)}function l(m){let h=t.scopeValue("schema",c.code.source===!0?{ref:m,code:(0,Jt.stringify)(m)}:{ref:m}),g=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Jt.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(w),e.ok(g)}}};function gC(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Jt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}$i.getValidate=gC;function Au(e,t,r,n){let{gen:i,it:o}=e,{allErrors:s,schemaEnv:c,opts:u}=o,f=u.passContext?Lo.default.this:Jt.nil;n?a():d();function a(){if(!c.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,Jt._)`await ${(0,mC.callValidateCode)(e,t,f)}`),l(t),s||i.assign(m,!0)},h=>{i.if((0,Jt._)`!(${h} instanceof ${o.ValidationError})`,()=>i.throw(h)),p(h),s||i.assign(m,!1)}),e.ok(m)}function d(){e.result((0,mC.callValidateCode)(e,t,f),()=>l(t),()=>p(t))}function p(m){let h=(0,Jt._)`${m}.errors`;i.assign(Lo.default.vErrors,(0,Jt._)`${Lo.default.vErrors} === null ? ${h} : ${Lo.default.vErrors}.concat(${h})`),i.assign(Lo.default.errors,(0,Jt._)`${Lo.default.vErrors}.length`)}function l(m){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=_u.mergeEvaluated.props(i,g.props,o.props));else{let w=i.var("props",(0,Jt._)`${m}.evaluated.props`);o.props=_u.mergeEvaluated.props(i,w,o.props,Jt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=_u.mergeEvaluated.items(i,g.items,o.items));else{let w=i.var("items",(0,Jt._)`${m}.evaluated.items`);o.items=_u.mergeEvaluated.items(i,w,o.items,Jt.Name)}}}$i.callRef=Au;$i.default=cq});var yC=A(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var lq=pC(),uq=wC(),dq=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",lq.default,uq.default];ah.default=dq});var vC=A(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var xu=de(),Vn=xu.operators,Pu={maximum:{okStr:"<=",ok:Vn.LTE,fail:Vn.GT},minimum:{okStr:">=",ok:Vn.GTE,fail:Vn.LT},exclusiveMaximum:{okStr:"<",ok:Vn.LT,fail:Vn.GTE},exclusiveMinimum:{okStr:">",ok:Vn.GT,fail:Vn.LTE}},fq={message:({keyword:e,schemaCode:t})=>(0,xu.str)`must be ${Pu[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,xu._)`{comparison: ${Pu[e].okStr}, limit: ${t}}`},pq={keyword:Object.keys(Pu),type:"number",schemaType:"number",$data:!0,error:fq,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,xu._)`${r} ${Pu[t].fail} ${n} || isNaN(${r})`)}};ch.default=pq});var kC=A(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var Aa=de(),mq={message:({schemaCode:e})=>(0,Aa.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Aa._)`{multipleOf: ${e}}`},hq={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:mq,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,o=i.opts.multipleOfPrecision,s=t.let("res"),c=o?(0,Aa._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,Aa._)`${s} !== parseInt(${s})`;e.fail$data((0,Aa._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};lh.default=hq});var dh=A(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});function bC(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}uh.default=bC;bC.code='require("ajv/dist/runtime/ucs2length").default'});var RC=A(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var ji=de(),gq=ve(),wq=dh(),yq={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,ji.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,ji._)`{limit: ${e}}`},vq={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:yq,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,o=t==="maxLength"?ji.operators.GT:ji.operators.LT,s=i.opts.unicode===!1?(0,ji._)`${r}.length`:(0,ji._)`${(0,gq.useFunc)(e.gen,wq.default)}(${r})`;e.fail$data((0,ji._)`${s} ${o} ${n}`)}};fh.default=vq});var SC=A(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var kq=lr(),bq=ve(),Mo=de(),Rq={message:({schemaCode:e})=>(0,Mo.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Mo._)`{pattern: ${e}}`},Sq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Rq,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:s}=e,c=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:u}=s.opts.code,f=u.code==="new RegExp"?(0,Mo._)`new RegExp`:(0,bq.useFunc)(t,u),a=t.let("valid");t.try(()=>t.assign(a,(0,Mo._)`${f}(${o}, ${c}).test(${r})`),()=>t.assign(a,!1)),e.fail$data((0,Mo._)`!${a}`)}else{let u=(0,kq.usePattern)(e,i);e.fail$data((0,Mo._)`!${u}.test(${r})`)}}};ph.default=Sq});var CC=A(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var xa=de(),Cq={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,xa.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,xa._)`{limit: ${e}}`},Eq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Cq,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?xa.operators.GT:xa.operators.LT;e.fail$data((0,xa._)`Object.keys(${r}).length ${i} ${n}`)}};mh.default=Eq});var EC=A(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var Pa=lr(),Ia=de(),_q=ve(),Aq={message:({params:{missingProperty:e}})=>(0,Ia.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Ia._)`{missingProperty: ${e}}`},xq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Aq,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:o,it:s}=e,{opts:c}=s;if(!o&&r.length===0)return;let u=r.length>=c.loopRequired;if(s.allErrors?f():a(),c.strictRequired){let l=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(l?.[h]===void 0&&!m.has(h)){let g=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,_q.checkStrictMode)(s,w,s.opts.strictRequired)}}function f(){if(u||o)e.block$data(Ia.nil,d);else for(let l of r)(0,Pa.checkReportMissingProp)(e,l)}function a(){let l=t.let("missing");if(u||o){let m=t.let("valid",!0);e.block$data(m,()=>p(l,m)),e.ok(m)}else t.if((0,Pa.checkMissingProp)(e,r,l)),(0,Pa.reportMissingProp)(e,l),t.else()}function d(){t.forOf("prop",n,l=>{e.setParams({missingProperty:l}),t.if((0,Pa.noPropertyInData)(t,i,l,c.ownProperties),()=>e.error())})}function p(l,m){e.setParams({missingProperty:l}),t.forOf(l,n,()=>{t.assign(m,(0,Pa.propertyInData)(t,i,l,c.ownProperties)),t.if((0,Ia.not)(m),()=>{e.error(),t.break()})},Ia.nil)}}};hh.default=xq});var _C=A(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var Oa=de(),Pq={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Oa.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Oa._)`{limit: ${e}}`},Iq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Pq,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?Oa.operators.GT:Oa.operators.LT;e.fail$data((0,Oa._)`${r}.length ${i} ${n}`)}};gh.default=Iq});var Iu=A(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var AC=$m();AC.code='require("ajv/dist/runtime/equal").default';wh.default=AC});var xC=A(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var yh=ga(),mt=de(),Oq=ve(),Nq=Iu(),Tq={message:({params:{i:e,j:t}})=>(0,mt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,mt._)`{i: ${e}, j: ${t}}`},$q={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Tq,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:o,schemaCode:s,it:c}=e;if(!n&&!i)return;let u=t.let("valid"),f=o.items?(0,yh.getSchemaTypes)(o.items):[];e.block$data(u,a,(0,mt._)`${s} === false`),e.ok(u);function a(){let m=t.let("i",(0,mt._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(u,!0),t.if((0,mt._)`${m} > 1`,()=>(d()?p:l)(m,h))}function d(){return f.length>0&&!f.some(m=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),w=(0,yh.checkDataTypes)(f,g,c.opts.strictNumbers,yh.DataType.Wrong),k=t.const("indices",(0,mt._)`{}`);t.for((0,mt._)`;${m}--;`,()=>{t.let(g,(0,mt._)`${r}[${m}]`),t.if(w,(0,mt._)`continue`),f.length>1&&t.if((0,mt._)`typeof ${g} == "string"`,(0,mt._)`${g} += "_"`),t.if((0,mt._)`typeof ${k}[${g}] == "number"`,()=>{t.assign(h,(0,mt._)`${k}[${g}]`),e.error(),t.assign(u,!1).break()}).code((0,mt._)`${k}[${g}] = ${m}`)})}function l(m,h){let g=(0,Oq.useFunc)(t,Nq.default),w=t.name("outer");t.label(w).for((0,mt._)`;${m}--;`,()=>t.for((0,mt._)`${h} = ${m}; ${h}--;`,()=>t.if((0,mt._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(u,!1).break(w)})))}}};vh.default=$q});var PC=A(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var kh=de(),jq=ve(),Dq=Iu(),qq={message:"must be equal to constant",params:({schemaCode:e})=>(0,kh._)`{allowedValue: ${e}}`},Lq={keyword:"const",$data:!0,error:qq,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0,kh._)`!${(0,jq.useFunc)(t,Dq.default)}(${r}, ${i})`):e.fail((0,kh._)`${o} !== ${r}`)}};bh.default=Lq});var IC=A(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var Na=de(),Mq=ve(),Wq=Iu(),Fq={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Na._)`{allowedValues: ${e}}`},Hq={keyword:"enum",schemaType:"array",$data:!0,error:Fq,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:o,it:s}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let c=i.length>=s.opts.loopEnum,u,f=()=>u??(u=(0,Mq.useFunc)(t,Wq.default)),a;if(c||n)a=t.let("valid"),e.block$data(a,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let l=t.const("vSchema",o);a=(0,Na.or)(...i.map((m,h)=>p(l,h)))}e.pass(a);function d(){t.assign(a,!1),t.forOf("v",o,l=>t.if((0,Na._)`${f()}(${r}, ${l})`,()=>t.assign(a,!0).break()))}function p(l,m){let h=i[m];return typeof h=="object"&&h!==null?(0,Na._)`${f()}(${r}, ${l}[${m}])`:(0,Na._)`${r} === ${h}`}}};Rh.default=Hq});var OC=A(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var Vq=vC(),Bq=kC(),Uq=RC(),Kq=SC(),Jq=CC(),zq=EC(),Gq=_C(),Yq=xC(),Xq=PC(),Qq=IC(),Zq=[Vq.default,Bq.default,Uq.default,Kq.default,Jq.default,zq.default,Gq.default,Yq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Xq.default,Qq.default];Sh.default=Zq});var Eh=A(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.validateAdditionalItems=void 0;var Di=de(),Ch=ve(),eL={message:({params:{len:e}})=>(0,Di.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Di._)`{limit: ${e}}`},tL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:eL,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Ch.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}NC(e,n)}};function NC(e,t){let{gen:r,schema:n,data:i,keyword:o,it:s}=e;s.items=!0;let c=r.const("len",(0,Di._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Di._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Ch.alwaysValidSchema)(s,n)){let f=r.var("valid",(0,Di._)`${c} <= ${t.length}`);r.if((0,Di.not)(f),()=>u(f)),e.ok(f)}function u(f){r.forRange("i",t.length,c,a=>{e.subschema({keyword:o,dataProp:a,dataPropType:Ch.Type.Num},f),s.allErrors||r.if((0,Di.not)(f),()=>r.break())})}}Ta.validateAdditionalItems=NC;Ta.default=tL});var _h=A($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.validateTuple=void 0;var TC=de(),Ou=ve(),rL=lr(),nL={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return $C(e,"additionalItems",t);r.items=!0,!(0,Ou.alwaysValidSchema)(r,t)&&e.ok((0,rL.validateArray)(e))}};function $C(e,t,r=e.schema){let{gen:n,parentSchema:i,data:o,keyword:s,it:c}=e;a(i),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=Ou.mergeEvaluated.items(n,r.length,c.items));let u=n.name("valid"),f=n.const("len",(0,TC._)`${o}.length`);r.forEach((d,p)=>{(0,Ou.alwaysValidSchema)(c,d)||(n.if((0,TC._)`${f} > ${p}`,()=>e.subschema({keyword:s,schemaProp:p,dataProp:p},u)),e.ok(u))});function a(d){let{opts:p,errSchemaPath:l}=c,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${s}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${l}"`;(0,Ou.checkStrictMode)(c,g,p.strictTuples)}}}$a.validateTuple=$C;$a.default=nL});var jC=A(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var iL=_h(),oL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,iL.validateTuple)(e,"items")};Ah.default=oL});var qC=A(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var DC=de(),sL=ve(),aL=lr(),cL=Eh(),lL={message:({params:{len:e}})=>(0,DC.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,DC._)`{limit: ${e}}`},uL={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:lL,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,sL.alwaysValidSchema)(n,t)&&(i?(0,cL.validateAdditionalItems)(e,i):e.ok((0,aL.validateArray)(e)))}};xh.default=uL});var LC=A(Ph=>{"use strict";Object.defineProperty(Ph,"__esModule",{value:!0});var dr=de(),Nu=ve(),dL={message:({params:{min:e,max:t}})=>t===void 0?(0,dr.str)`must contain at least ${e} valid item(s)`:(0,dr.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,dr._)`{minContains: ${e}}`:(0,dr._)`{minContains: ${e}, maxContains: ${t}}`},fL={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:dL,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e,s,c,{minContains:u,maxContains:f}=n;o.opts.next?(s=u===void 0?1:u,c=f):s=1;let a=t.const("len",(0,dr._)`${i}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,Nu.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,Nu.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Nu.alwaysValidSchema)(o,r)){let h=(0,dr._)`${a} >= ${s}`;c!==void 0&&(h=(0,dr._)`${h} && ${a} <= ${c}`),e.pass(h);return}o.items=!0;let d=t.name("valid");c===void 0&&s===1?l(d,()=>t.if(d,()=>t.break())):s===0?(t.let(d,!0),c!==void 0&&t.if((0,dr._)`${i}.length > 0`,p)):(t.let(d,!1),p()),e.result(d,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);l(h,()=>t.if(h,()=>m(g)))}function l(h,g){t.forRange("i",0,a,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Nu.Type.Num,compositeRule:!0},h),g()})}function m(h){t.code((0,dr._)`${h}++`),c===void 0?t.if((0,dr._)`${h} >= ${s}`,()=>t.assign(d,!0).break()):(t.if((0,dr._)`${h} > ${c}`,()=>t.assign(d,!1).break()),s===1?t.assign(d,!0):t.if((0,dr._)`${h} >= ${s}`,()=>t.assign(d,!0)))}}};Ph.default=fL});var FC=A(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.validateSchemaDeps=Ur.validatePropertyDeps=Ur.error=void 0;var Ih=de(),pL=ve(),ja=lr();Ur.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Ih.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Ih._)`{property: ${e},
147
+ missingProperty: ${n},
148
+ depsCount: ${t},
149
+ deps: ${r}}`};var mL={keyword:"dependencies",type:"object",schemaType:"object",error:Ur.error,code(e){let[t,r]=hL(e);MC(e,t),WC(e,r)}};function hL({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function MC(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let s in t){let c=t[s];if(c.length===0)continue;let u=(0,ja.propertyInData)(r,n,s,i.opts.ownProperties);e.setParams({property:s,depsCount:c.length,deps:c.join(", ")}),i.allErrors?r.if(u,()=>{for(let f of c)(0,ja.checkReportMissingProp)(e,f)}):(r.if((0,Ih._)`${u} && (${(0,ja.checkMissingProp)(e,c,o)})`),(0,ja.reportMissingProp)(e,o),r.else())}}Ur.validatePropertyDeps=MC;function WC(e,t=e.schema){let{gen:r,data:n,keyword:i,it:o}=e,s=r.name("valid");for(let c in t)(0,pL.alwaysValidSchema)(o,t[c])||(r.if((0,ja.propertyInData)(r,n,c,o.opts.ownProperties),()=>{let u=e.subschema({keyword:i,schemaProp:c},s);e.mergeValidEvaluated(u,s)},()=>r.var(s,!0)),e.ok(s))}Ur.validateSchemaDeps=WC;Ur.default=mL});var VC=A(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var HC=de(),gL=ve(),wL={message:"property name must be valid",params:({params:e})=>(0,HC._)`{propertyName: ${e.propertyName}}`},yL={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:wL,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,gL.alwaysValidSchema)(i,r))return;let o=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),t.if((0,HC.not)(o),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(o)}};Oh.default=yL});var Th=A(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var Tu=lr(),xr=de(),vL=sn(),$u=ve(),kL={message:"must NOT have additional properties",params:({params:e})=>(0,xr._)`{additionalProperty: ${e.additionalProperty}}`},bL={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:kL,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:o,it:s}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:c,opts:u}=s;if(s.props=!0,u.removeAdditional!=="all"&&(0,$u.alwaysValidSchema)(s,r))return;let f=(0,Tu.allSchemaProperties)(n.properties),a=(0,Tu.allSchemaProperties)(n.patternProperties);d(),e.ok((0,xr._)`${o} === ${vL.default.errors}`);function d(){t.forIn("key",i,g=>{!f.length&&!a.length?m(g):t.if(p(g),()=>m(g))})}function p(g){let w;if(f.length>8){let k=(0,$u.schemaRefOrVal)(s,n.properties,"properties");w=(0,Tu.isOwnProperty)(t,k,g)}else f.length?w=(0,xr.or)(...f.map(k=>(0,xr._)`${g} === ${k}`)):w=xr.nil;return a.length&&(w=(0,xr.or)(w,...a.map(k=>(0,xr._)`${(0,Tu.usePattern)(e,k)}.test(${g})`))),(0,xr.not)(w)}function l(g){t.code((0,xr._)`delete ${i}[${g}]`)}function m(g){if(u.removeAdditional==="all"||u.removeAdditional&&r===!1){l(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,$u.alwaysValidSchema)(s,r)){let w=t.name("valid");u.removeAdditional==="failing"?(h(g,w,!1),t.if((0,xr.not)(w),()=>{e.reset(),l(g)})):(h(g,w),c||t.if((0,xr.not)(w),()=>t.break()))}}function h(g,w,k){let b={keyword:"additionalProperties",dataProp:g,dataPropType:$u.Type.Str};k===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,w)}}};Nh.default=bL});var KC=A(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var RL=ka(),BC=lr(),$h=ve(),UC=Th(),SL={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:o}=e;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&UC.default.code(new RL.KeywordCxt(o,UC.default,"additionalProperties"));let s=(0,BC.allSchemaProperties)(r);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=$h.mergeEvaluated.props(t,(0,$h.toHash)(s),o.props));let c=s.filter(d=>!(0,$h.alwaysValidSchema)(o,r[d]));if(c.length===0)return;let u=t.name("valid");for(let d of c)f(d)?a(d):(t.if((0,BC.propertyInData)(t,i,d,o.opts.ownProperties)),a(d),o.allErrors||t.else().var(u,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(u);function f(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function a(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},u)}}};jh.default=SL});var YC=A(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var JC=lr(),ju=de(),zC=ve(),GC=ve(),CL={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:o}=e,{opts:s}=o,c=(0,JC.allSchemaProperties)(r),u=c.filter(h=>(0,zC.alwaysValidSchema)(o,r[h]));if(c.length===0||u.length===c.length&&(!o.opts.unevaluated||o.props===!0))return;let f=s.strictSchema&&!s.allowMatchingProperties&&i.properties,a=t.name("valid");o.props!==!0&&!(o.props instanceof ju.Name)&&(o.props=(0,GC.evaluatedPropsToName)(t,o.props));let{props:d}=o;p();function p(){for(let h of c)f&&l(h),o.allErrors?m(h):(t.var(a,!0),m(h),t.if(a))}function l(h){for(let g in f)new RegExp(h).test(g)&&(0,zC.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,g=>{t.if((0,ju._)`${(0,JC.usePattern)(e,h)}.test(${g})`,()=>{let w=u.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:GC.Type.Str},a),o.opts.unevaluated&&d!==!0?t.assign((0,ju._)`${d}[${g}]`,!0):!w&&!o.allErrors&&t.if((0,ju.not)(a),()=>t.break())})})}}};Dh.default=CL});var XC=A(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var EL=ve(),_L={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,EL.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};qh.default=_L});var QC=A(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});var AL=lr(),xL={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:AL.validateUnion,error:{message:"must match a schema in anyOf"}};Lh.default=xL});var ZC=A(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var Du=de(),PL=ve(),IL={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Du._)`{passingSchemas: ${e.passing}}`},OL={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:IL,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let o=r,s=t.let("valid",!1),c=t.let("passing",null),u=t.name("_valid");e.setParams({passing:c}),t.block(f),e.result(s,()=>e.reset(),()=>e.error(!0));function f(){o.forEach((a,d)=>{let p;(0,PL.alwaysValidSchema)(i,a)?t.var(u,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},u),d>0&&t.if((0,Du._)`${u} && ${s}`).assign(s,!1).assign(c,(0,Du._)`[${c}, ${d}]`).else(),t.if(u,()=>{t.assign(s,!0),t.assign(c,d),p&&e.mergeEvaluated(p,Du.Name)})})}}};Mh.default=OL});var eE=A(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var NL=ve(),TL={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((o,s)=>{if((0,NL.alwaysValidSchema)(n,o))return;let c=e.subschema({keyword:"allOf",schemaProp:s},i);e.ok(i),e.mergeEvaluated(c)})}};Wh.default=TL});var nE=A(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var qu=de(),rE=ve(),$L={message:({params:e})=>(0,qu.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,qu._)`{failingKeyword: ${e.ifClause}}`},jL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$L,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,rE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=tE(n,"then"),o=tE(n,"else");if(!i&&!o)return;let s=t.let("valid",!0),c=t.name("_valid");if(u(),e.reset(),i&&o){let a=t.let("ifClause");e.setParams({ifClause:a}),t.if(c,f("then",a),f("else",a))}else i?t.if(c,f("then")):t.if((0,qu.not)(c),f("else"));e.pass(s,()=>e.error(!0));function u(){let a=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);e.mergeEvaluated(a)}function f(a,d){return()=>{let p=e.subschema({keyword:a},c);t.assign(s,c),e.mergeValidEvaluated(p,s),d?t.assign(d,(0,qu._)`${a}`):e.setParams({ifClause:a})}}}};function tE(e,t){let r=e.schema[t];return r!==void 0&&!(0,rE.alwaysValidSchema)(e,r)}Fh.default=jL});var iE=A(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var DL=ve(),qL={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,DL.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hh.default=qL});var oE=A(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var LL=Eh(),ML=jC(),WL=_h(),FL=qC(),HL=LC(),VL=FC(),BL=VC(),UL=Th(),KL=KC(),JL=YC(),zL=XC(),GL=QC(),YL=ZC(),XL=eE(),QL=nE(),ZL=iE();function eM(e=!1){let t=[zL.default,GL.default,YL.default,XL.default,QL.default,ZL.default,BL.default,UL.default,VL.default,KL.default,JL.default];return e?t.push(ML.default,FL.default):t.push(LL.default,WL.default),t.push(HL.default),t}Vh.default=eM});var sE=A(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var Ge=de(),tM={message:({schemaCode:e})=>(0,Ge.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Ge._)`{format: ${e}}`},rM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:tM,code(e,t){let{gen:r,data:n,$data:i,schema:o,schemaCode:s,it:c}=e,{opts:u,errSchemaPath:f,schemaEnv:a,self:d}=c;if(!u.validateFormats)return;i?p():l();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:u.code.formats}),h=r.const("fDef",(0,Ge._)`${m}[${s}]`),g=r.let("fType"),w=r.let("format");r.if((0,Ge._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Ge._)`${h}.type || "string"`).assign(w,(0,Ge._)`${h}.validate`),()=>r.assign(g,(0,Ge._)`"string"`).assign(w,h)),e.fail$data((0,Ge.or)(k(),b()));function k(){return u.strictSchema===!1?Ge.nil:(0,Ge._)`${s} && !${w}`}function b(){let S=a.$async?(0,Ge._)`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,Ge._)`${w}(${n})`,E=(0,Ge._)`(typeof ${w} == "function" ? ${S} : ${w}.test(${n}))`;return(0,Ge._)`${w} && ${w} !== true && ${g} === ${t} && !${E}`}}function l(){let m=d.formats[o];if(!m){k();return}if(m===!0)return;let[h,g,w]=b(m);h===t&&e.pass(S());function k(){if(u.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${o}" ignored in schema at path "${f}"`}}function b(E){let O=E instanceof RegExp?(0,Ge.regexpCode)(E):u.code.formats?(0,Ge._)`${u.code.formats}${(0,Ge.getProperty)(o)}`:void 0,K=r.scopeValue("formats",{key:o,ref:E,code:O});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Ge._)`${K}.validate`]:["string",E,K]}function S(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!a.$async)throw new Error("async format in sync schema");return(0,Ge._)`await ${w}(${n})`}return typeof g=="function"?(0,Ge._)`${w}(${n})`:(0,Ge._)`${w}.test(${n})`}}}};Bh.default=rM});var aE=A(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var nM=sE(),iM=[nM.default];Uh.default=iM});var cE=A(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.contentVocabulary=Wo.metadataVocabulary=void 0;Wo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Wo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var uE=A(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var oM=yC(),sM=OC(),aM=oE(),cM=aE(),lE=cE(),lM=[oM.default,sM.default,(0,aM.default)(),cM.default,lE.metadataVocabulary,lE.contentVocabulary];Kh.default=lM});var fE=A(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});Lu.DiscrError=void 0;var dE;(function(e){e.Tag="tag",e.Mapping="mapping"})(dE||(Lu.DiscrError=dE={}))});var mE=A(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var Fo=de(),Jh=fE(),pE=wu(),uM=ba(),dM=ve(),fM={message:({params:{discrError:e,tagName:t}})=>e===Jh.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Fo._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},pM={keyword:"discriminator",type:"object",schemaType:"object",error:fM,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:o}=e,{oneOf:s}=i;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let u=t.let("valid",!1),f=t.const("tag",(0,Fo._)`${r}${(0,Fo.getProperty)(c)}`);t.if((0,Fo._)`typeof ${f} == "string"`,()=>a(),()=>e.error(!1,{discrError:Jh.DiscrError.Tag,tag:f,tagName:c})),e.ok(u);function a(){let l=p();t.if(!1);for(let m in l)t.elseIf((0,Fo._)`${f} === ${m}`),t.assign(u,d(l[m]));t.else(),e.error(!1,{discrError:Jh.DiscrError.Mapping,tag:f,tagName:c}),t.endIf()}function d(l){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:l},m);return e.mergeEvaluated(h,Fo.Name),m}function p(){var l;let m={},h=w(i),g=!0;for(let S=0;S<s.length;S++){let E=s[S];if(E?.$ref&&!(0,dM.schemaHasRulesButRef)(E,o.self.RULES)){let K=E.$ref;if(E=pE.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,K),E instanceof pE.SchemaEnv&&(E=E.schema),E===void 0)throw new uM.default(o.opts.uriResolver,o.baseId,K)}let O=(l=E?.properties)===null||l===void 0?void 0:l[c];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);g=g&&(h||w(E)),k(O,S)}if(!g)throw new Error(`discriminator: "${c}" must be required`);return m;function w({required:S}){return Array.isArray(S)&&S.includes(c)}function k(S,E){if(S.const)b(S.const,E);else if(S.enum)for(let O of S.enum)b(O,E);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function b(S,E){if(typeof S!="string"||S in m)throw new Error(`discriminator: "${c}" values must be unique strings`);m[S]=E}}}};zh.default=pM});var hE=A((C4,mM)=>{mM.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var wE=A((qe,Gh)=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.MissingRefError=qe.ValidationError=qe.CodeGen=qe.Name=qe.nil=qe.stringify=qe.str=qe._=qe.KeywordCxt=qe.Ajv=void 0;var hM=fC(),gM=uE(),wM=mE(),gE=hE(),yM=["/properties"],Mu="http://json-schema.org/draft-07/schema",Ho=class extends hM.default{_addVocabularies(){super._addVocabularies(),gM.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(wM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(gE,yM):gE;this.addMetaSchema(t,Mu,!1),this.refs["http://json-schema.org/schema"]=Mu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Mu)?Mu:void 0)}};qe.Ajv=Ho;Gh.exports=qe=Ho;Gh.exports.Ajv=Ho;Object.defineProperty(qe,"__esModule",{value:!0});qe.default=Ho;var vM=ka();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return vM.KeywordCxt}});var Vo=de();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var kM=hu();Object.defineProperty(qe,"ValidationError",{enumerable:!0,get:function(){return kM.default}});var bM=ba();Object.defineProperty(qe,"MissingRefError",{enumerable:!0,get:function(){return bM.default}})});import{AsyncLocalStorage as F0}from"async_hooks";import{promises as pk}from"fs";import qs from"path";import{promises as fk}from"fs";import Ke from"path";import D0 from"os";import{promises as kA}from"fs";async function Za(e){try{return await kA.access(e),!0}catch(t){if(bA(t))return!1;throw t}}function bA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}Yt();ci();pp();ye();var Ds=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},di=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="ClassicProjectConfigError"}},dk=".comet/config.yaml";function mp(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function sl(e,t){let r=Ke.resolve(e),n=t==="docs"?Ke.join(r,"docs"):r,i=Ke.join(n,"openspec"),o=Ke.join(r,"docs","superpowers");return{projectRoot:r,artifactLayout:t,openSpecBase:n,openSpecRoot:i,changesDir:Ke.join(i,"changes"),archiveDir:Ke.join(i,"changes","archive"),specsDir:Ke.join(i,"specs"),superpowersRoot:o,superpowersSpecsDir:Ke.join(o,"specs"),superpowersPlansDir:Ke.join(o,"plans"),superpowersReportsDir:Ke.join(o,"reports")}}async function q0(e){let t=await co(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new Ds;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new Ds("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function Xr(e,t){return sl(e,t??await q0(e))}async function L0(e){try{return await fk.lstat(e),!0}catch(t){if(mp(t))return!1;throw t}}async function M0(e,t){let r=await Xr(e,t),n=r.artifactLayout==="legacy"?"docs":"legacy",i=sl(e,n).openSpecRoot,[o,s]=await Promise.all([U(r.projectRoot,tt(r.projectRoot,r.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),L0(i)]),c=o.exists;return{paths:r,configuredRootExists:c,alternateRoot:i,alternateRootExists:s,dualRoots:c&&s}}async function W0(e){let t=[e.openSpecRoot,e.changesDir,e.archiveDir,e.specsDir,e.superpowersRoot,e.superpowersSpecsDir,e.superpowersPlansDir,e.superpowersReportsDir];for(let r of t){let n=tt(e.projectRoot,r);await U(e.projectRoot,n,{label:`Classic managed physical path ${n}`,expected:"directory"})}}async function Xt(e,t){let r=await M0(e,t);if(await W0(r.paths),!r.configuredRootExists){let n=tt(r.paths.projectRoot,r.paths.openSpecRoot),i=tt(r.paths.projectRoot,r.alternateRoot);throw new Ds(`Configured Classic OpenSpec root is missing: ${n} (alternate ${i} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function fi(e,t){let r=Ke.join(Ke.resolve(e),".comet","classic-root-move.json");if(await Za(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let n=await Xt(e,t);if(!await Za(n.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${tt(n.projectRoot,n.openSpecRoot)}`);return n}async function at(e){let t=Ke.resolve(e),r=null;try{(await fk.lstat(t)).isDirectory()||(t=Ke.dirname(t))}catch(o){if(!mp(o))throw o}let n=t,i=Ke.resolve(D0.homedir());for(;;){Ke.basename(t)==="openspec"&&(r=Ke.dirname(t));let o=!1,s=t===i&&t!==n,c=null;if(!s)try{let{bytes:f}=await ae(t,dk,ii,{label:dk});c=f.toString("utf8")}catch(f){if(!mp(f))throw f}if(c!==null)try{let f=oi(c,{allowPartialProject:!0,allowMissingNativeFields:!0}).value;o=!!f&&typeof f=="object"&&!Array.isArray(f)&&(f.schema==="comet.project.v1"||f.default_workflow!==void 0||f.native!==void 0)}catch(f){if(t===n)throw new di(f);if(Kv(c))throw new di(f)}if(o||await Za(Ke.join(t,".git")))return t;let u=Ke.dirname(t);if(u===t)return r??Ke.resolve(e);t=u}}function tt(e,t){return Ke.relative(Ke.resolve(e),t).replaceAll("\\","/")}var lo=new F0;function H0(e,t){let r=qs.relative(e,t);return r===""||!qs.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${qs.sep}`)}async function V0(e){let t=qs.resolve(e.invocationCwd??process.cwd()),r=qs.resolve(e.projectRoot??await at(t)),[n,i]=await Promise.all([pk.realpath(t),pk.realpath(r)]);if(!H0(i,n))throw new Error(`Classic command invocation cwd is outside the discovered project: ${t}`);return{invocationCwd:t,projectRoot:r,observations:new Map}}async function B0(e,t){let r=lo.getStore();if(r)return t(r);let n=await V0(e);return lo.run(n,()=>t(n))}function al(){let e=lo.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}async function mk(e,t){let r=lo.getStore();if(!r?.observations)return t();let n=r.observations.get(e);if(n)return n;let i=t();r.observations.set(e,i);try{return await i}catch(o){throw r.observations.delete(e),o}}async function Ls(e){let t=lo.getStore();if(!t)return e();t.observations?.clear();try{return await lo.run({...t,observations:null},e)}finally{t.observations?.clear()}}function cl(e){return(t,r)=>B0(r,()=>e(t,r))}import{randomUUID as a$}from"node:crypto";var Zk=Tt(Gt(),1);import Wr from"node:path";import{spawnSync as Y0}from"child_process";import{accessSync as wk,constants as gp,statSync as yk,existsSync as BB,readFileSync as UB}from"node:fs";import uo from"node:path";import{existsSync as hp,readFileSync as U0}from"node:fs";import nr from"node:path";var FB=["$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 hk(e,t){let r=t.toLowerCase();return Object.entries(e).find(([n,i])=>n.toLowerCase()===r&&i!==void 0)?.[1]}function K0(e){let t=(hk(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function J0(e,t,r){let i=nr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(hk(t,"PATH")??"").split(nr.delimiter).map(c=>c.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),s=nr.win32.extname(e)?[e]:K0(t).map(c=>`${e}${c}`);return i.flatMap(c=>s.map(u=>c?nr.join(c,u):nr.resolve(r,u)))}function ll(e,t,r){return J0(e,t,r).find(n=>hp(n))??e}function z0(e){let t=e.replaceAll(`\r
150
+ `,`
151
+ `).trim(),r=/^@"([^"%\r\n]+)" "%~dp0([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(t);if(r&&nr.win32.isAbsolute(r[1])&&nr.win32.basename(r[1]).toLowerCase()==="node.exe")return{target:r[2],nodeCommand:r[1]};let n=/^@ECHO off\nGOTO start\n:find_dp0\nSET dp0=%~dp0\nEXIT \/b\n:start\nSETLOCAL\nCALL :find_dp0\n\nIF EXIST "%dp0%\\node\.exe" \(\n {2}SET "_prog=%dp0%\\node\.exe"\n\) ELSE \(\n {2}SET "_prog=node"\n {2}SET PATHEXT=%PATHEXT:;\.JS;=;%\n\)\n\nendLocal & goto #_undefined_# 2>NUL \|\| title %COMSPEC% & "%_prog%" {2}"%dp0%\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(t);if(n)return{target:n[1]};let i=/^@SETLOCAL\n(?:@IF NOT DEFINED NODE_PATH \(\n {2}@SET "NODE_PATH=([^"\r\n]+)"\n\) ELSE \(\n {2}@SET "NODE_PATH=\1;%NODE_PATH%"\n\)\n)?@IF EXIST "%~dp0\\node\.exe" \(\n {2}"%~dp0\\node\.exe" {2}"%~dp0\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*\n\) ELSE \(\n {2}@SET PATHEXT=%PATHEXT:;\.JS;=;%\n {2}node {2}"%~dp0\\\2" %\*\n\)$/u.exec(t);return i?{target:i[2],...i[1]?{nodePath:i[1]}:{}}:null}function gk(e,t,r,n=process.execPath){let i=z0(U0(e,"utf8"));if(!i)return null;let o=i.target.replace(/^[/\\]+/u,"");if(nr.win32.parse(o).root)return null;let s=nr.resolve(nr.dirname(e),o);if(!hp(s))throw new Error("Node CLI entry is missing: "+s);let c=nr.join(nr.dirname(e),"node.exe"),u={...r},f=Object.keys(u).find(d=>d.toUpperCase()==="NODE_PATH"),a=f?u[f]:void 0;return i.nodePath&&(f&&delete u[f],u.NODE_PATH=i.nodePath+(a?";"+a:"")),{command:i.nodeCommand??(hp(c)?c:n),args:[s,...t],...i.nodePath?{env:u}:{}}}function wp(e,t,r){if((r.platform??process.platform)!=="win32")return{command:e,args:[...t]};let n=ll(e,r.env??process.env,r.cwd),i=uo.extname(n).toLowerCase();if([".mjs",".cjs",".js"].includes(i))return{command:process.execPath,args:[uo.resolve(r.cwd,n),...t]};if(i===".cmd"){let o=gk(n,t,r.env??process.env);if(o)return o}if([".cmd",".bat",".ps1"].includes(i))throw new Error(`Unsupported Node CLI shim: ${n}. Use a standard npm/pnpm .cmd launcher or the Node CLI .js/.mjs/.cjs entry; no shell fallback is allowed.`);return{command:n,args:[...t]}}function vk(e,t,r){let n=wp(e,t,r),i=r.platform??process.platform,o=n.env??r.env??process.env,s=n.command;if(!(i==="win32"?[ll(s,o,r.cwd)]:s.includes("/")?[uo.resolve(r.cwd,s)]:(o.PATH??"/usr/bin:/bin").split(uo.delimiter).map(f=>uo.resolve(r.cwd,f,s))).some(f=>{try{let a=uo.resolve(r.cwd,f);return yk(a).isFile()?(wk(a,i==="win32"?gp.F_OK:gp.X_OK),!0):!1}catch{return!1}}))throw new Error(`Executable not found or not executable: ${e}`);if(n.command!==e&&n.args.length>t.length){let f=n.args[0];if(!yk(f).isFile())throw new Error(`Node CLI entry is not a file: ${f}`);wk(f,gp.R_OK)}}var kk=Tt(Gt(),1);ye();import G0 from"path";async function bk(e,t){let r=t??await Xt(e),n=G0.join(r.openSpecRoot,"config.yaml"),i=tt(r.projectRoot,n),o;try{o=(await ae(r.projectRoot,i,Number.MAX_SAFE_INTEGER,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(f){throw f.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${i} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:f}):new Error(`Classic OpenSpec root is unhealthy: ${f instanceof Error?f.message:String(f)}`,{cause:f})}let s=(0,kk.parseDocument)(o,{uniqueKeys:!0});if(s.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${i} is invalid YAML (${s.errors[0].message})`);let c=s.toJS();if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`Classic OpenSpec root is unhealthy: ${i} must contain a mapping`);let u=c.schema;if(typeof u!="string"||u.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${i} must declare a non-empty schema`);return{layout:r,configPath:i,schema:u}}async function Rk(e,t=process.cwd()){let r=e[0]==="--"?e.slice(1):[...e];if(r.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- <openspec-args...>"};let n=await at(t),i=await fi(n);await bk(n,i);let o=process.env.COMET_OPENSPEC||"openspec",s;try{vk(o,r,{cwd:i.openSpecBase}),s=wp(o,r,{cwd:i.openSpecBase})}catch(u){return{exitCode:u.code==="ENOENT"?127:70,executionStarted:!1,stderr:u instanceof Error?u.message:String(u)}}let c=Y0(s.command,s.args,{cwd:i.openSpecBase,encoding:"utf8",shell:!1,windowsHide:!0,timeout:12e4,...s.env?{env:s.env}:{}});if(c.error){let u=c.error.code;return{exitCode:u==="ENOENT"?127:70,...c.pid===0&&["ENOENT","EACCES","ENOTDIR","ENOEXEC"].includes(u??"")?{executionStarted:!1}:{},stdout:c.stdout||void 0,stderr:c.stderr||(u==="ENOENT"?`OpenSpec CLI not found: ${o}`:c.error.message)}}return{exitCode:c.status??1,executionCompleted:c.status!==null&&c.signal===null,stdout:c.stdout||void 0,stderr:c.stderr||void 0}}jr();import{promises as X0}from"node:fs";import yp from"node:path";var Sk="comet-state.yaml",ul=".comet.yaml",vp=[Sk,ul],kp=class extends Error{};function dl(e){return vp.some(t=>t===e)}async function Q0(e,t={}){let r=[],n=[];for(let i of vp)try{let o=await X0.lstat(yp.join(e,i));r.push(i),(!o.isFile()||o.isSymbolicLink())&&n.push(i)}catch(o){if(o.code!=="ENOENT")throw o}if(r.length>1)throw new kp(`Classic state files are ambiguous in ${e}: ${vp.join(" and ")} both exist; preserve both files and resolve the conflict before continuing`);if(n.length)throw new Error(`Classic state must be a regular file, not a symlink or directory: ${yp.join(e,n[0])}`);return yp.join(e,r[0]??t.defaultFileName??Sk)}var Z0=gt("classicStateFile",(e,t)=>Q0(e,t));async function Re(e,t={}){return Z0(e,t)}ye();import{promises as _l}from"fs";import Mr from"path";import po from"path";import{AsyncLocalStorage as GN}from"node:async_hooks";yl();var Hk=["full","hotfix","tweak"],wi=1,Pp=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u,Ip=`# comet-execution: managed-run
152
+ `;function At(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}var vN=["open","design","build","verify","archive"],kN=["en","zh-CN"],bN=["off","beta"],RN=["subagent-driven-development","executing-plans","direct","autonomous"],SN=["plan-ready"],CN=["confirmed"],EN=["tdd","direct"],_N=["off","standard","thorough"],AN=["current","branch","worktree"],xN=["light","full"],PN=["pending","pass","fail"],IN=["pending","handled"],ON=["pending","confirmed"],xn=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","check_epoch","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Vs=["change_id","run_id","run_checkpoint","application_checkpoint"],NN=new Set([...xn,...Vs]),TN=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Ap(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function fo(e,t){let r=e[t];if(r==null||r==="")return null;if(typeof r!="string")throw new Error(`Invalid Classic state: ${t} must be a string or null`);return r}function _t(e,t,r,n=!0){let i=e[t];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof i!="string"||!r.includes(i))throw new Error(`Invalid Classic state: ${t} must be one of ${r.join(", ")}${n?" or null":""}`);return i}function xp(e,t,r=!0){let n=e[t];if(n==null||n===""){if(r)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof n!="boolean")throw new Error(`Invalid Classic state: ${t} must be true or false`);return n}function Vk(e,t,r=0){let n=e[t];if(n==null||n==="")return r;if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error(`Invalid Classic state: ${t} must be a non-negative integer`);return n}function vl(e,t){let r=fo(e,t);if(r===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${t} must be a relative repository path`);return r}function $N(e,t){let r=fo(e,t);if(r!==null&&!/^[a-f0-9]{64}$/u.test(r))throw new Error(`Invalid Classic state: ${t} must be a sha256 hex digest`);return r}function jN(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==wi)throw new Error(`Invalid Classic state: classic_migration must be ${wi}`);return t}function DN(e){if(!xn.some(r=>Ap(e,r)))return null;for(let r of TN)if(!Ap(e,r))return null;return{workflow:_t(e,"workflow",Hk,!1),language:_t(e,"language",kN),phase:_t(e,"phase",vN,!1),contextCompression:_t(e,"context_compression",bN),buildMode:_t(e,"build_mode",RN),buildPause:_t(e,"build_pause",SN),subagentDispatch:_t(e,"subagent_dispatch",CN),tddMode:_t(e,"tdd_mode",EN),reviewMode:_t(e,"review_mode",_N),isolation:_t(e,"isolation",AN),boundBranch:fo(e,"bound_branch"),verifyMode:_t(e,"verify_mode",xN),autoTransition:xp(e,"auto_transition"),baseRef:fo(e,"base_ref"),designDoc:vl(e,"design_doc"),plan:vl(e,"plan"),verifyResult:_t(e,"verify_result",PN,!1),verifyFailures:Vk(e,"verify_failures"),...Ap(e,"check_epoch")?{checkEpoch:Vk(e,"check_epoch")}:{},verificationReport:vl(e,"verification_report"),branchStatus:_t(e,"branch_status",IN),createdAt:fo(e,"created_at"),verifiedAt:fo(e,"verified_at"),archiveConfirmation:_t(e,"archive_confirmation",ON),archived:xp(e,"archived",!1),directOverride:xp(e,"direct_override"),handoffContext:vl(e,"handoff_context"),handoffHash:$N(e,"handoff_hash"),classicProfile:_t(e,"classic_profile",Hk),classicMigration:jN(e)}}function Mt(e,t){if(e.change_id!==void 0&&(typeof e.change_id!="string"||!Pp.test(e.change_id)))throw new Error("Invalid Classic state: change_id must be an immutable UUID");let r=t??null;if(r===null&&t===void 0&&e.run_id&&e.skill)try{r=hi(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:n})}return{classic:DN(e),run:r,unknownKeys:Object.keys(e).filter(n=>!NN.has(n))}}function kl(e){return{workflow:e.workflow,language:e.language,phase:e.phase,context_compression:e.contextCompression,build_mode:e.buildMode,build_pause:e.buildPause,subagent_dispatch:e.subagentDispatch,tdd_mode:e.tddMode,review_mode:e.reviewMode,isolation:e.isolation,bound_branch:e.boundBranch,verify_mode:e.verifyMode,auto_transition:e.autoTransition,base_ref:e.baseRef,design_doc:e.designDoc,plan:e.plan,verify_result:e.verifyResult,verify_failures:e.verifyFailures,...e.checkEpoch===void 0?{}:{check_epoch:e.checkEpoch},verification_report:e.verificationReport,branch_status:e.branchStatus,created_at:e.createdAt,verified_at:e.verifiedAt,archive_confirmation:e.archiveConfirmation,archived:e.archived,direct_override:e.directOverride,handoff_context:e.handoffContext,handoff_hash:e.handoffHash,classic_profile:e.classicProfile,classic_migration:e.classicMigration}}ye();var Gk=Tt(Gt(),1);Lt();ye();import{createHash as BN,randomUUID as UN}from"node:crypto";import Ee from"node:path";import{promises as Us}from"node:fs";import Kk from"node:path";jr();import{createHash as qN}from"node:crypto";import{lstatSync as Bs,readFileSync as LN,realpathSync as Bk}from"node:fs";import MN from"node:os";import xt from"node:path";function Op(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function bl(e){return process.platform==="win32"?Bk.native(e):Bk(e)}var WN=$r("workspaceIdentity",HN);function FN(e){return WN(e)}function HN(e){let t=bl(xt.resolve(e)),r=Bs(t,{bigint:!0});if(!r.isDirectory())throw new Error(`工作区必须是目录:${e}`);let n=Op(r),i=(u,f)=>({projectRoot:t,workspaceId:qN("sha256").update(JSON.stringify(["comet.workspace.v2",t,n,u,f])).digest("hex")}),o=xt.join(t,".git"),s,c;try{let u=Bs(o);if(u.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${o}`);if(u.isDirectory())s=bl(o),c=Op(Bs(s,{bigint:!0}));else if(u.isFile()){let f=/^gitdir: (.+)\r?\n?$/u.exec(LN(o,"utf8"));if(!f)throw new Error(`工作区 .git 文件格式无效:${o}`);s=bl(xt.resolve(t,f[1].trim()));let a=Bs(s,{bigint:!0});if(!a.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${s}`);c=Op(a)}else throw new Error(`工作区 .git 类型无效:${o}`)}catch(u){if(u.code!=="ENOENT")throw u;try{Bs(o)}catch(f){if(f.code==="ENOENT")return i(o,null);throw f}throw u}return i(s,c)}function Uk(e){let t=xt.dirname(e);if(t===e)return e;try{return xt.join(bl(t),xt.basename(e))}catch(r){if(r.code!=="ENOENT")throw r;return xt.join(Uk(t),xt.basename(e))}}var VN=$r("workspaceRuntimeParent",Uk);function Np(e){let t=FN(e),r=process.env.COMET_DATA_DIR;if(r!==void 0&&(!r.trim()||!xt.isAbsolute(r)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let n=VN(r??xt.join(MN.homedir(),".comet")),i=xt.relative(t.projectRoot,n);if(i===""||!xt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${xt.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${n};工作区:${t.projectRoot}`);let o=xt.join(n,"workspaces",t.workspaceId);return{...t,dataRoot:n,workspaceRoot:o,runtimeRoot:xt.join(o,"runtime")}}function Wt(e){return Np(e).runtimeRoot}ai();async function Qr(e){return Wt(e)}async function Tp(e){return[Wt(e)]}async function Jk(e){let t=Kk.dirname(e);if(t!==e){await Jk(t);try{await Us.mkdir(e,{mode:448})}catch(n){if(n.code!=="EEXIST")throw n}}let r=await Us.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function qr(e){let t=Wt(e);return await Jk(t),t}async function zk(e,t,r){try{let n=await Us.lstat(e);if(n.isSymbolicLink())throw new Error("旧 Runtime 路径不能是符号链接:"+e);let i=n.isDirectory()?Kk.join(e,".comet-runtime-migration.json"):e,o=await Us.lstat(i);if(!o.isFile()||o.isSymbolicLink())return!1;let s;try{s=JSON.parse((await si(i,Number.MAX_SAFE_INTEGER,{label:"旧 Runtime 标记"})).bytes.toString("utf8"))}catch(c){if(c instanceof SyntaxError)return!1;throw c}return s?.schema!=="comet.workspace-runtime-migration.v1"||typeof s.workspaceId!="string"||typeof s.source!="string"||typeof s.target!="string"||!["file","directory"].includes(s.kind)?!1:!n.isDirectory()||(await Us.readdir(e)).every(c=>c===".comet-runtime-migration.json")}catch(n){if(n.code==="ENOENT")return!1;throw n}}var KN=new Set(["run-state.json","pending-action.json","trajectory.jsonl","context.md","artifacts.json","checkpoint.json","coordination.json","subagent-progress.md"]);function Rl(e){let t=BN("sha256").update(e).digest("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`}async function Yk(e,t){let r=await Re(t),n=Ee.relative(e,r).replaceAll("\\","/"),i=null;try{i=(await ae(e,n,Number.MAX_SAFE_INTEGER,{label:"Classic change identity"})).bytes.toString("utf8")}catch(c){if(c.code!=="ENOENT")throw c}if(i===null)throw Object.assign(new Error("Classic state file does not exist"),{code:"ENOENT"});let o=(0,Gk.parseDocument)(i,{uniqueKeys:!0});if(o.errors.length)throw new Error(`Invalid Classic state document: ${o.errors[0].message}`);let s=o.get("change_id");if(s!==void 0&&(typeof s!="string"||!Pp.test(s)))throw new Error("Invalid Classic change_id: expected an immutable UUID");return{source:i,document:o,id:s}}async function JN(e,t){let r=await Re(t),n=Ee.relative(e,r).replaceAll("\\","/"),i=()=>Yk(e,t),o=await i();if(o.id)return o.id;let{source:s,document:c}=o,u=c.get("run_id"),f=typeof u=="string"&&u?Rl(`classic-run:${u}`):UN();return c.get("archived")===!0||Ee.basename(Ee.dirname(t))==="archive"?typeof u=="string"&&u?f:Rl(`classic-archive:${n}`):(c.set("change_id",f),await $e(r,c.toString(),{containedRoot:e,exclusive:s===null,beforeCommit:async()=>{if((await i()).source!==s)throw new Error("Classic state changed while assigning its instance identity")}}),f)}async function $p(e,t,r={}){let n=t??await at(e),i;try{i=await Yk(n,e)}catch(m){if(m.code==="ENOENT")return null;throw m}let{document:o,id:s}=i,c=Ee.relative(n,e).replaceAll("\\","/"),u=o.get("run_id"),f=o.get("archived")===!0||Ee.basename(Ee.dirname(e))==="archive",a=s??(typeof u=="string"&&u?Rl(`classic-run:${u}`):f?Rl(`classic-archive:${c}`):null);if(!a)return e;let d=Wt(n),p=Ee.parse(d).root;if(!(await U(p,Ee.relative(p,d).replaceAll("\\","/"),{label:"Classic read-only Runtime root",expected:"directory"})).exists)return r.includeMissing?Ee.join(d,"classic-changes",a):e;let l=await U(d,`classic-changes/${a}`,{label:"Classic read-only Run directory",expected:"directory"});return l.exists||r.includeMissing?l.target:e}async function Se(e,t){return zN(e,t)}async function zN(e,t){let r=t??await at(e),n=Ee.relative(r,e).replaceAll("\\","/");if(n&&!(await U(r,n,{label:"Classic change directory",expected:"directory"})).exists)throw Object.assign(new Error("Classic change directory does not exist"),{code:"ENOENT"});await Re(e);let i=await qr(r),o=await JN(r,e),s=Ee.join(i,"classic-changes",o);return await ft(i,Ee.relative(i,s),{label:"Classic local Run directory"}),s}async function Sl(e,t,r={}){let n=Wt(e),i=Ee.relative(n,t);if(i===""||!i.startsWith(`..${Ee.sep}`)&&i!==".."&&!Ee.isAbsolute(i))return r.readOnly?{root:Ee.dirname(n),target:t}:(await qr(e),{root:n,target:t});let o=Ee.relative(Ee.resolve(e),t).replaceAll("\\","/");if(o.startsWith(".comet/runtime/"))return{root:n,target:Ee.join(n,o.slice(15))};let s=/^(?:(.*)\/)?\.comet\/([^/]+)(\/.*)?$/u.exec(o);if(!s||!KN.has(s[2]))return null;if(r.readOnly){let p=Ee.parse(n).root;if(!(await U(p,Ee.relative(p,Ee.join(n,"classic-changes")),{label:"Classic local records",expected:"directory"})).exists)return null}let c=s[1]??"";if(!(await U(e,Ee.relative(e,await Re(Ee.join(e,c))),{label:"Classic local change identity",expected:"file"})).exists)return null;let f=Ee.join(e,c),a=r.readOnly?await $p(f,e,{includeMissing:!0}):await Se(f,e);if(!a||r.readOnly&&a===f)return null;let d=Ee.relative(n,a);if(Ee.isAbsolute(d)||d===".."||d.startsWith(`..${Ee.sep}`))throw new Error("Classic Runtime workspace changed while resolving a change-local target");return{root:r.readOnly?Ee.dirname(n):n,target:Ee.join(a,".comet",s[2],s[3]??"")}}Lt();Yt();ye();var Cl=Number.MAX_SAFE_INTEGER,YN=new GN;async function XN(e,t){let r=YN.getStore();if(!r||r.root!==po.resolve(e))return null;let n=et(t,"Classic proposal source"),i=r.files.get(n);return i||(i=r.session.read(n,Cl),r.files.set(n,i)),i}async function El(e,t,r,n=!1){let i=po.resolve(e),o=po.isAbsolute(t)?po.resolve(t):po.resolve(i,t),s=await Sl(i,o,{readOnly:!n});s&&(i=s.root,o=s.target);let c=po.relative(i,o).replaceAll("\\","/");return{root:i,relative:et(c,r),target:o}}async function mo(e,t,r){let n=await El(e,t,r.label,r.migrate);return U(n.root,n.relative,r)}async function Lr(e,t,r){try{return(await mo(e,t,{label:r.label,expected:r.expected??"any"})).exists}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ho(e,t,r,n){return await Lr(e,t,{label:r,expected:"file"})?(await Xk(e,t,{label:r,hooks:n})).byteLength>0:!1}async function Fe(e,t,r){return(await Xk(e,t,r)).toString("utf8")}async function Xk(e,t,r){let n=await El(e,t,r.label);if(!r.hooks){let i=await XN(n.root,n.relative);if(i){if(i.bytes.length>(r.maxBytes??Cl))throw new Error(`${r.label} exceeds the read limit`);return i.bytes}}return(await ae(n.root,n.relative,r.maxBytes??Cl,{label:r.label,hooks:r.hooks})).bytes}async function jp(e,t,r){let n=await El(e,t,r,!0);return ft(n.root,n.relative,{label:r})}async function go(e,t,r,n){let i=await El(e,t,n.label,!0);await U(i.root,i.relative,{label:n.label,expected:"file"}),await $e(i.target,r,{containedRoot:i.root,beforeTemporaryOpen:n.beforeTemporaryOpen,beforeCommit:n.beforeCommit,exclusive:n.exclusive})}async function wo(e,t){let r=[],n=new Set;async function i(o,s){let c=await mo(e,o,{label:"Classic capability directory",expected:"directory"});if(!c.exists)return;let u=await _l.realpath(c.target);if(n.has(u))throw new Error(`Classic capability directory cycle: ${o}`);if(n.add(u),s){let a=`${o}/spec.md`;(await mo(e,a,{label:"Classic capability spec",expected:"file"})).exists&&r.push(a)}let f=(await _l.readdir(c.target,{withFileTypes:!0})).sort((a,d)=>a.name.localeCompare(d.name));for(let a of f)if(a.isDirectory()||a.isSymbolicLink()){if(a.name==="spec.md")continue;await i(`${o}/${a.name}`,!0)}n.delete(u)}return await i(t.replaceAll("\\","/"),!1),r}function Ks(e){return e?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e)?e.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${e}'
153
+ Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function yo(e){let t=Ks(e);if(t)throw new Error(t)}async function kr(e,t){yo(t);let r=[],n=async i=>(await U(e,Mr.relative(e,i),{label:"Classic change directory",expected:"directory"}),Re(i));for(let i of["openspec/changes","docs/openspec/changes"]){r.push(await n(Mr.join(e,i,t)));let o=Mr.join(e,i,"archive"),s=await xl(e,o,t);for(let c of s??[])c===t?await n(Mr.join(o,c)):Qk(c,t)&&r.push(await n(Mr.join(o,c)))}return r}function QN(e,t){return{label:tt(e,t),directory:t}}async function Al(e,t,r){let n=QN(e,t);if(!(await mo(e,t,{label:r,expected:"directory"})).exists)return{change:n,exists:!1,stateExists:!1};let o=await mo(e,await Re(t),{label:`${r} state`,expected:"file"});return{change:n,exists:!0,stateExists:o.exists}}var ZN=/^\d{4}-\d{2}-\d{2}-/u;function Qk(e,t){return e.slice(11)===t&&ZN.test(e)}async function xl(e,t,r){yo(r);let n=()=>U(e,Mr.relative(e,t),{label:"Classic Archive directory",expected:"directory"}),i=await n();if(!i.exists)return null;let o=async()=>{let u=await _l.lstat(i.target,{bigint:!0});if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Classic Archive directory must be a real directory");return[u.dev,u.ino,u.mode,u.size,u.mtimeNs,u.ctimeNs].join(":")},s=await o(),c=await mk(`classic-archive:${JSON.stringify([i.target,r,s])}`,async()=>{let u=await _l.readdir(i.target);if(await o()!==s)throw new Error("Classic Archive directory changed while inspecting state files");return u.filter(f=>f===r||Qk(f,r))});if(!(await n()).exists||await o()!==s)throw new Error("Classic Archive directory changed while inspecting state files");return c}async function eT(e,t,r,n={}){if(!n.skipExactCompatibility){let s=await Al(e,Mr.join(t,r),`Classic archived change ${r}`);if(s.exists)return s.change}let i=await xl(e,t,r),o=[];for(let s of i??[]){if(s===r)continue;let c=await Al(e,Mr.join(t,s),`Classic archived change ${s}`);c.exists&&c.stateExists&&o.push(c.change)}return o.sort((s,c)=>c.directory.localeCompare(s.directory))[0]??null}async function Pl(e,t=process.cwd()){yo(e);let r=await Xt(t),n=await Al(r.projectRoot,Mr.join(r.changesDir,e),`Classic active change ${e}`);return{...n.change,exists:n.exists,stateExists:n.stateExists}}async function Il(e,t=process.cwd()){yo(e);let r=await Xt(t),n=await Al(r.projectRoot,Mr.join(r.changesDir,e),`Classic active change ${e}`);if(n.exists)return n.change;let i=await eT(r.projectRoot,r.archiveDir,e);return i||n.change}var tT=".comet/archive-requirements.json";async function eb(e,t){let r=Wr.join(t,tT),n=["proposal.md","design.md","tasks.md"];if(await Lr(e,r,{label:"Classic archive requirements",expected:"file"})){let o=JSON.parse(await Fe(e,r,{label:"Classic archive requirements"}));if(o?.schema!=="comet.classic.archive-requirements.v1")throw new Error("Unsupported Classic archive requirements");n=o.files}if(!Array.isArray(n)||!n.includes("proposal.md")||!n.includes("tasks.md")||n.some(o=>typeof o!="string"||!(["proposal.md","design.md","tasks.md"].includes(o)||/^specs\/(?:[^/\\:]+\/)+spec\.md$/u.test(o))||o.split("/").some(s=>s==="."||s==="..")))throw new Error("Invalid Classic archive required files");let i=[];for(let o of n)await ho(e,Wr.join(t,o),"Classic archived required file")||i.push(`Required archived artifact is missing or empty: ${o}`);return i}function rT(e){if(!e||typeof e!="object")throw new Error("Unsupported OpenSpec status: expected an object");let t=e;if(!Array.isArray(t.artifacts)||!Array.isArray(t.applyRequires))throw new Error("OpenSpec must expose artifacts and applyRequires; upgrade to a supported version");let r=new Map;for(let c of t.artifacts){if(!c||typeof c!="object"||typeof c.id!="string"||typeof c.outputPath!="string"||!["done","skipped","ready","blocked"].includes(c.status)||!Array.isArray(c.requires)||c.requires.some(u=>typeof u!="string"))throw new Error("OpenSpec must expose dependency edges for every artifact; upgrade to a supported version");if(r.has(c.id))throw new Error(`Duplicate OpenSpec artifact: ${c.id}`);r.set(c.id,c)}let n=[],i=new Set,o=new Set,s=c=>{if(typeof c!="string"||!r.has(c))throw new Error(`Missing OpenSpec dependency: ${String(c)}`);if(o.has(c))throw new Error(`Cyclic OpenSpec dependency: ${c}`);if(i.has(c))return;o.add(c);let u=r.get(c);for(let f of u.requires)s(f);o.delete(c),i.add(c),n.push(u)};for(let c of[...t.applyRequires,"proposal","tasks"])s(c);return n}async function Ol(e,t,r){let n=Wr.join(t,".openspec.yaml");if(!await Lr(e,n,{label:"OpenSpec change metadata",expected:"file"})){if(r!==void 0)throw new Error("OpenSpec change metadata is missing; cannot validate its status");return{source:"legacy",required:["proposal","design","tasks"],skipped:[],designRequired:!0,files:["proposal.md","design.md","tasks.md"].map(d=>Wr.join(t,d)),problems:[]}}let i=(0,Zk.parseDocument)(await Fe(e,n,{label:"OpenSpec change metadata"}));if(i.errors.length)throw new Error(`Invalid OpenSpec metadata: ${i.errors[0].message}`);let o=await wo(e,Wr.join(t,"specs")),s=r===void 0?await Rk(["status","--change",Wr.basename(t),"--json"],e):void 0;if(s&&s.exitCode!==0)throw new Error(`Cannot inspect OpenSpec artifact requirements: ${s.stderr??s.exitCode}`);let c;try{c=s?JSON.parse(s.stdout??""):r}catch{throw new Error("Unsupported OpenSpec status: expected JSON")}if(!c||typeof c.changeRoot!="string"||Wr.resolve(c.changeRoot)!==Wr.resolve(t))throw new Error("OpenSpec status resolves outside the selected Classic change");let u=rT(c),f=o,a={source:"openspec",required:u.map(d=>d.id),skipped:[],designRequired:u.some(d=>d.id==="design"),files:[],problems:[]};for(let d of u){if(!["proposal","specs","design","tasks"].includes(d.id))throw new Error(`Unsupported Classic artifact: ${d.id}; use a schema with supported artifact roles`);if(d.id!=="specs"&&d.outputPath!==`${d.id}.md`)throw new Error(`Unsupported Classic artifact output: ${d.outputPath}`);if(d.status==="skipped"){if(d.id!=="specs"||i.get("skip_specs")!==!0||f.length)throw new Error("OpenSpec skipped specs require explicit skip_specs: true and no conflicting spec files");a.skipped.push(d.id);continue}let p=d.outputPath.replaceAll("\\","/");if(Wr.posix.isAbsolute(p)||/^[A-Za-z]:/u.test(p)||p.split("/").includes(".."))throw new Error(`Unsafe OpenSpec artifact path: ${p}`);let l;if(d.id==="specs"&&["specs/**/*.md","specs/**/spec.md","specs/*/spec.md"].includes(p))l=f;else{if(["?","*","[","]","{","}"].some(m=>p.includes(m)))throw new Error(`Unsupported OpenSpec artifact pattern: ${p}`);l=[Wr.join(t,p)]}(d.status!=="done"||!l.length)&&a.problems.push(`Required OpenSpec artifact is not complete: ${d.id}`);for(let m of l)await ho(e,m,`OpenSpec required artifact ${d.id}`)||a.problems.push(`Required OpenSpec file is missing or empty: ${m}`),a.files.push(m)}return a}function Nl(e){return e==="zh-CN"?"zh-CN":"en"}function nT(e,t,r){return e==="zh-CN"?r:t}function Tl(e){let{name:t,locale:r}=e;return{summary:nT(r,`Handoff context for ${t} was written and recorded; the Build phase can resume from it.`,`需求 ${t} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}Ep();import $l from"path";var yi={trajectory:Number.MAX_SAFE_INTEGER,artifacts:Number.MAX_SAFE_INTEGER,context:Number.MAX_SAFE_INTEGER,pendingAction:Number.MAX_SAFE_INTEGER,checkpoint:Number.MAX_SAFE_INTEGER};function Pn(e,t){if($l.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let r=$l.resolve(e),n=$l.resolve(r,t);if(n!==r&&!n.startsWith(r+$l.sep))throw new Error("Run path must stay inside the change directory")}async function tb(e,t,r,n={}){Pn(e,t),await Lk(e,t,`${JSON.stringify(r)}
154
+ `,yi.trajectory,"Run trajectory",n)}async function rb(e,t,r={}){Pn(e,t);let n=await pi(e,t,yi.trajectory,"Run trajectory",r);return n===null?[]:n.split(/\r?\n/).map((i,o)=>({line:i,number:o+1})).filter(({line:i})=>i.length>0).map(({line:i,number:o})=>{try{return JSON.parse(i)}catch(s){throw new Error(`Invalid Trajectory event at line ${o}`,{cause:s})}})}async function nb(e,t,r={}){Pn(e,t);let n=await pi(e,t,yi.artifacts,"Run artifacts",r);return n===null?{}:JSON.parse(n)}async function ib(e,t,r,n={}){Pn(e,t),await mi(e,t,JSON.stringify(r,null,2)+`
155
+ `,yi.artifacts,"Run artifacts",n)}async function ob(e,t,r,n={}){Pn(e,t),await mi(e,t,r,yi.context,"Run context",n)}async function sb(e,t,r={}){Pn(e,t);let n=await pi(e,t,yi.pendingAction,"Run pending action",r);return n===null?null:JSON.parse(n)}async function ab(e,t,r={}){Pn(e,t),await gl(e,t,"Run pending action",r)}async function cb(e,t,r,n={}){Pn(e,t),await mi(e,t,JSON.stringify(r,null,2)+`
156
+ `,yi.checkpoint,"Run checkpoint",n)}import In from"node:path";async function Dp(e,t){let r=In.resolve(e,t),n=In.relative(In.resolve(e),r);if(In.isAbsolute(t)||In.isAbsolute(n)||n===".."||n.startsWith(`..${In.sep}`))throw new Error("Run path must stay inside the change directory");let i=await at(e),o=await Sl(i,r,{readOnly:!0}),s=o?.root??e,c=o?.target??r,u=s===In.parse(c).root?Wt(i):s;return{root:u,ref:In.relative(u,c).replaceAll("\\","/"),inspectionRoot:s,target:c}}async function vo(...e){return e[0]=await Se(e[0]),tb(...e)}async function jl(...e){let t=await Dp(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,rb(...e)}async function lb(...e){let t=await Dp(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,nb(...e)}async function Dl(...e){return e[0]=await Se(e[0]),ib(...e)}async function ql(...e){return e[0]=await Se(e[0]),ob(...e)}async function ub(...e){let t=await Dp(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,sb(...e)}async function db(...e){return e[0]=await Se(e[0]),ab(...e)}async function fb(...e){return e[0]=await Se(e[0]),cb(...e)}import{promises as Bb}from"fs";import Qt from"path";import{fileURLToPath as Ub}from"url";ye();import On from"path";ye();Yt();import Js from"path";function oT(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function pb(e,t,r,n){let i=et(r,"Classic handoff artifact pointer");if((await U(e,i,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let s=await Xt(e),c=`${tt(e,s.changesDir)}/`,f=(s.artifactLayout==="docs"?[c,"openspec/changes/"]:[c]).find(k=>i.startsWith(k));if(!f)return null;let a=i.slice(f.length).split("/");if(a.length<4||a[1]!==".comet"||a.slice(2).some(k=>k.length===0))return null;let d=a[0];yo(d);let p=a.slice(2),l=Js.resolve(t);if(Js.dirname(l)!==Js.resolve(s.archiveDir))return null;let m=Js.basename(l),h=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(m);if(m!==d&&h?.[1]!==d)return null;await U(e,tt(e,l),{label:"Classic archived change directory",expected:"directory"});let g=Js.join(l,".comet",...p),w=tt(e,g);try{return await ae(e,w,n,{label:"Historical Classic archived handoff artifact"}),w}catch(k){if(oT(k))return null;throw k}}import vi from"node:path";function zs(e){if(e.workflow!=="full")return{missingFields:[],invalidFields:[]};let t=[],r=[];return e.buildMode||t.push("build_mode"),e.tddMode||t.push("tdd_mode"),e.reviewMode||t.push("review_mode"),e.buildMode==="subagent-driven-development"&&e.subagentDispatch!=="confirmed"&&t.push("subagent_dispatch"),e.buildMode!=="subagent-driven-development"&&e.subagentDispatch==="confirmed"&&r.push({field:"subagent_dispatch",reason:"subagent_dispatch=confirmed 仅适用于 build_mode=subagent-driven-development"}),e.buildMode!=="direct"&&e.directOverride===!0&&r.push({field:"direct_override",reason:"direct_override=true 仅适用于 build_mode=direct"}),e.buildMode==="autonomous"&&e.reviewMode==="off"&&r.push({field:"review_mode",reason:"autonomous full build requires review_mode=standard or thorough"}),e.buildMode==="direct"&&e.directOverride!==!0&&r.push({field:"direct_override",reason:"full workflow direct execution requires direct_override=true"}),{missingFields:t,invalidFields:r}}function mb(e){let t=zs(e);return t.missingFields.length===0&&t.invalidFields.length===0}async function Ll(e,t,r={}){if(!t||t==="null")return{status:"missing",recordedPath:null};let n=await Xt(e),i=vi.resolve(e,t),o=vi.relative(n.superpowersPlansDir,i);return vi.isAbsolute(t)||!o||o.startsWith(`..${vi.sep}`)||vi.isAbsolute(o)||o.includes(vi.sep)||vi.extname(o).toLowerCase()!==".md"?{status:"broken",recordedPath:t}:await Lr(e,t,{label:`Classic build plan ${t}`,expected:"file"})&&(!r.requireNonempty||(await Fe(e,t,{label:`Classic build plan ${t}`})).trim().length>0)?{status:"ready",recordedPath:t}:{status:"broken",recordedPath:t}}var sT=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,aT=/\s*<!-- comet-task:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->\s*$/u;function Gs(e){let t=[],r=new Set,n=null;for(let[i,o]of e.split(/\r?\n/u).entries()){let s=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(o);if(s){n?s[1][0]===n.marker&&s[1].length>=n.length&&!s[2].trim()&&(n=null):n={marker:s[1][0],length:s[1].length};continue}if(n)continue;let c=sT.exec(o);if(!c)continue;let u=aT.exec(c[4]),f=u?.[1]??null;if(c[4].includes("<!-- comet-task:")&&(!u||c[4].slice(0,u.index).includes("<!-- comet-task:")))throw new Error(`Malformed Classic task ID at line ${i+1}`);if(f&&r.has(f))throw new Error(`Duplicate Classic task ID: ${f}`);f&&r.add(f);let a=c[4].slice(0,u?.index).trim();if(!a)throw new Error(`Empty Classic task at line ${i+1}`);t.push({id:f,text:a,completed:c[2].toLowerCase()==="x",line:i+1})}return t}function Ml(e,t){return On.relative(e,t).split(On.sep).join("/")}async function Ys(e,t,r,n,i){if(!r)return{code:t,satisfied:!1};let o=r.replaceAll("\\","/");if(i)return{code:t,satisfied:!1,source:o,detail:`Classic layout is unsafe or unavailable: ${i instanceof Error?i.message:String(i)}`};try{if(n){let c=n.artifactLayout==="legacy"?"docs":"legacy",u=tt(e,sl(e,c).openSpecRoot);if((o===u||o.startsWith(`${u}/`))&&(await U(e,o,{label:`${t} artifact`,expected:"file"})).exists)return{code:t,satisfied:!1,source:o,detail:"standalone OpenSpec root is not a Comet artifact root"}}let s=await tp(e,o,{label:`${t} artifact`});return{code:t,satisfied:s,source:o,...s?{resolvedSource:o}:{}}}catch(s){return{code:t,satisfied:!1,source:o,detail:`unsafe artifact pointer outside the project or through a special path: ${s instanceof Error?s.message:String(s)}`}}}async function cT(e,t,r,n){try{n??=await Xt(e)}catch(o){return{code:"design.handoff",satisfied:!1,...r?{source:r.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${o instanceof Error?o.message:String(o)}`}}let i=await Ys(e,"design.handoff",r,n);if(!r||i.satisfied||i.detail)return i;try{let o=await pb(e,t,r,Number.MAX_SAFE_INTEGER);return o?{...i,satisfied:!0,resolvedSource:o,detail:`resolved historical legacy pointer from archived change: ${o}`}:i}catch(o){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${o instanceof Error?o.message:String(o)}`}}}async function qp(e,t,r){return Ys(e,t,Ml(e,r))}async function lT(e,t){let r=On.join(t,"specs"),n;try{n=await wo(e,r)}catch(i){return i.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${i instanceof Error?i.message:String(i)}`}}return{code:"openspec.delta-spec",satisfied:n.length>0,source:n[0]?Ml(e,n[0]):void 0,detail:`${n.length} delta spec${n.length===1?"":"s"}`}}async function uT(e,t){let r,n=Ml(e,t);try{r=(await ae(e,n,Number.MAX_SAFE_INTEGER,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(s){return s.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:n,detail:`unsafe tasks artifact: ${s instanceof Error?s.message:String(s)}`}}let i;try{i=Gs(r)}catch(s){return{code:"build.tasks-complete",satisfied:!1,source:n,detail:`malformed tasks.md: ${s instanceof Error?s.message:String(s)}`}}let o=i.filter(s=>s.completed).length;return{code:"build.tasks-complete",satisfied:i.length>0&&o===i.length,source:n,detail:`${o} of ${i.length} tasks complete`}}function ko(e,t){return e.some(r=>r.code===t&&r.satisfied)}async function bo(e,t){let r=await at(e),n=t.classic,i=On.join(e,"proposal.md"),o=On.join(e,"design.md"),s=On.join(e,"tasks.md"),c=t.run?On.resolve(e,t.run.checkpointRef):On.join(e,".comet","checkpoint.json"),u,f;try{u=await Xt(r)}catch(d){f=d}let a=await Promise.all([qp(r,"openspec.proposal",i),qp(r,"openspec.design",o),qp(r,"openspec.tasks",s),lT(r,e),Ys(r,"design.document",n?.designDoc??null,u,f),(async()=>{let d=await Ys(r,"build.plan",n?.plan??null,u,f);if(!d.satisfied)return d;try{let p=await Ll(r,n?.plan??null,{requireNonempty:n?.buildMode==="autonomous"});return p.status==="ready"?d:{code:d.code,source:d.source,satisfied:!1,detail:`Implementation plan is ${p.status}`}}catch(p){return{code:d.code,source:d.source,satisfied:!1,detail:p instanceof Error?p.message:String(p)}}})(),uT(r,s),Ys(r,"verification.report",n?.verificationReport??null,u,f),cT(r,e,n?.handoffContext??null,u),(async()=>{try{return{code:"run.checkpoint",source:Ml(r,c),satisfied:await ho(r,c,"Classic Run checkpoint")}}catch(d){return{code:"run.checkpoint",satisfied:!1,detail:d instanceof Error?d.message:String(d)}}})()]);return a.push({code:"archive.confirmed",satisfied:n?.archiveConfirmation==="confirmed"}),a}import{createHash as JT,randomUUID as zT}from"crypto";import{promises as Vp}from"fs";import en from"path";function dT(e){return e.classicProfile??e.workflow}function fT(e){return e.isolation!==null&&mb(e)}function pT(e){return(e.buildMode==="direct"||e.buildMode==="autonomous")&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function mT(e,t,r){if(e!=="full"&&t.verifyResult==="fail")return`${e}.build.execute`;if(e==="full"){if(ko(r,"build.plan")&&t.buildPause==="plan-ready")return"full.build.plan-ready";if(!fT(t))return"full.build.configure";if(!ko(r,"build.plan"))return"full.build.plan";if(t.verifyResult==="fail")return"full.build.fix"}else if(!pT(t))throw new Error(`${e} build configuration is incomplete`);return ko(r,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function hT(e,t,r){return t.verifyResult!=="pass"||!ko(r,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function gT(e,t){if(t.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return t.archiveConfirmation==="confirmed"?`${e}.archive.execute`:`${e}.archive.confirm`}function Wl(e,t){let r=dT(e);if(e.archived&&e.phase!=="archive")throw new Error("archived=true requires phase=archive");if(e.archived)return"completed";if(r!=="full"&&e.phase==="design")throw new Error(`${r} workflow cannot enter design`);switch(e.phase){case"open":return`${r}.open`;case"design":return ko(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return mT(r,e,t);case"verify":return hT(r,e,t);case"archive":return gT(r,e)}}jr();import{randomUUID as wT}from"node:crypto";ye();ye();var Zs=Tt(Gt(),1);Lt();ye();import Fr from"path";import{AsyncLocalStorage as yT}from"node:async_hooks";yl();var hb=new yT,Xs=".comet-state-transaction.json";async function Zr(e,t){let r=await Se(e);return hb.getStore()===r?t():hb.run(r,async()=>(await wb(e),t()))}async function Qs(e,t){let r=t===Xs?await Se(e):e;try{return(await ae(r,t,Number.MAX_SAFE_INTEGER,{label:"Classic state transaction"})).bytes.toString("utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}}function vT(e){if(e===null)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic transaction Run");let t=e,r=hi({run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:t.retries});if(!r)throw new Error("Invalid Classic transaction Run identity");return r}async function wb(e){let t=await Qs(e,Xs);if(t===null)return;let r=JSON.parse(t);if(!r||r.schema!=="comet.classic.state-transaction.v1"||r.beforeYaml!==null&&typeof r.beforeYaml!="string"||typeof r.afterYaml!="string")throw new Error("Invalid Classic state transaction");let n=await Re(e),i=r.stateFile??ul;if(typeof i!="string"||!dl(i)||Fr.basename(n)!==i)throw new Error("Classic state transaction belongs to a different state filename; preserve files for recovery");let o=await Qs(e,i);if(o!==r.beforeYaml&&o!==r.afterYaml)throw new Error("Classic state transaction conflicts with current YAML; preserve files for recovery");let s=vT(o===r.afterYaml?r.afterRun:r.beforeRun);if(await Re(e)!==n)throw new Error("Classic state filename changed during transaction recovery");s?await gi(await Se(e),s):await Hs(await Se(e));let c=await Se(e);await Dr(Fr.join(c,Xs),{containedRoot:c})}function yb(e,t){if(t&&e.run_id!==t.runId)throw new Error("Classic local Run identity differs from .comet.yaml; preserve both records and restore the matching Runtime history");if(!t&&e.run_id&&!e.skill&&e.run_checkpoint===void 0)throw new Error("Classic local Run history is missing; restore the matching workspace Runtime backup before continuing")}function ki(e){let t=e.toJS();if(t===null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic state document: root must be a mapping");return t}function gb(e,t,r){e.get(t)!==r&&e.set(t,r)}function vb(e,t){if(t.classic)for(let[r,n]of Object.entries(kl(t.classic)))r==="auto_transition"&&n===null&&!e.has(r)||gb(e,r,n);else for(let r of xn)e.delete(r);_p(e.toJS(),t.run),t.run?gb(e,"run_id",t.run.runId):e.delete("run_id")}function kT(e){let t=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let r of t)e.delete(r)}function kb(e){let t=!1;for(let r of["build_command","verify_command"])e.has(r)&&(e.delete(r),t=!0);return t}async function Lp(e){let t;try{t=(await ae(Fr.dirname(e),Fr.basename(e),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(n){if(n.code!=="ENOENT")throw n;return new Zs.Document({})}let r=(0,Zs.parseDocument)(t);if(r.errors.length>0)throw new Error(`Invalid Classic state document: ${r.errors[0].message}`);return ki(r),r}var bT=gt("classicStateProjection",e=>RT(e));async function Ro(e,t={}){return t.migrate===!1?bT(e):Zr(e,()=>ST(e,t))}async function RT(e){let t=await $p(e);if(t===null)return Mt({});if((await U(t,Xs,{label:"Classic state transaction",expected:"file"})).exists)throw new Error("Classic state transaction is incomplete; use an explicit state operation to recover it");let r=await Lp(await Re(e));kb(r);let n=ki(r),i=await Fs(t);return!i&&n.run_id&&n.skill&&(i=hi(n)),yb(n,i),Mt(n,i)}async function ST(e,t){let r=t.migrate!==!1,n=await Re(e),i=await Lp(n),o=ki(i),s=kb(i);s&&(o=ki(i));let c=await Fs(await Se(e));if(yb(o,c),!c&&o.run_id&&o.skill){let{runStateFromDocument:u}=await Promise.resolve().then(()=>(yl(),Fk));c=u(o),c&&r&&(await gi(await Se(e),c),kT(i),s=!0)}return s&&r&&await $e(n,i.toString(),{containedRoot:e}),Mt(ki(i),c)}async function So(e,t,r={}){let n=await Re(e,{defaultFileName:ul});if(await Qs(e,Fr.basename(n))===null){let i=new Zs.Document({change_id:wT()});vb(i,{...t,unknownKeys:t.unknownKeys??[]}),Mt(ki(i),t.run??null);let o=await at(e),s=await qr(o),c=await ft(s,`classic-changes/${i.get("change_id")}`,{label:"Classic initial Run"});t.run&&await gi(c,t.run),await $e(n,i.toString(),{containedRoot:e,exclusive:!0,beforeCommit:r.beforeCommit});return}return Zr(e,()=>CT(e,t,r))}async function CT(e,t,r){let n=await Re(e),i=await Qs(e,Fr.basename(n));if(i!==null&&At(i))throw new Error("Classic managed Run state is owned by the SDK; compat writes are not allowed");let o=await Lp(n);o.has("change_id")||o.set("change_id",Fr.basename(await Se(e)));let s=o.get("check_epoch")??0;if(typeof s=="number"&&s>(t.classic?.checkEpoch??0))throw new Error("Classic state changed during this operation; reload before retrying");vb(o,{...t,unknownKeys:t.unknownKeys??[]}),Mt(ki(o),t.run??null);let c=await Qs(e,Fr.basename(n)),u=o.toString();if(c===u){await r.beforeCommit?.(),t.run?await gi(await Se(e),t.run):await Hs(await Se(e));return}let f=await Se(e),a=Fr.join(f,Xs);await $e(a,JSON.stringify({schema:"comet.classic.state-transaction.v1",stateFile:Fr.basename(n),beforeYaml:c,afterYaml:u,beforeRun:await Fs(await Se(e)),afterRun:t.run}),{containedRoot:f});try{t.run?await gi(await Se(e),t.run):await Hs(await Se(e)),await $e(n,u,{containedRoot:e,beforeCommit:r.beforeCommit})}catch(d){throw await wb(e).catch(()=>{}),d}await Dr(a,{containedRoot:f}).catch(()=>{})}function bb(e,t,r){return{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:r,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}import{createHash as jb,randomUUID as HT}from"crypto";import{promises as ct}from"fs";import rt from"path";var Cb=Tt(Gt(),1);import{promises as Mp}from"fs";import ir from"path";var ET=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],_T=["deterministic","adaptive"],AT=["function","mcp","script","agent"],xT=["none","read","write","external"],PT=["progress","step","completion"],IT=["artifact_exists","state_equals"];function bi(e,t,r){return new Error(`${e}: ${t} ${r}`)}function Ft(e,t,r="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw bi(t,r,"must be an object")}function Nn(e,t,r){if(!Array.isArray(e))throw bi(t,r,"must be an array")}function Pt(e,t,r){if(typeof e!="string")throw bi(t,r,"must be a string")}function br(e,t,r,n){t in e&&Pt(e[t],r,`${n}.${t}`)}function Eb(e,t,r,n){if(t in e&&typeof e[t]!="boolean")throw bi(r,`${n}.${t}`,"must be a boolean")}function Tn(e,t,r,n){if(typeof e!="string"||!t.includes(e))throw bi(r,n,`must be one of ${t.join(", ")}`)}function Fl(e,t,r){Nn(e,t,r),e.forEach((n,i)=>{Pt(n,t,`${r}[${i}]`)})}function Rb(e,t,r){Ft(e,t,r),Pt(e.name,t,`${r}.name`),Pt(e.description,t,`${r}.description`),Eb(e,"required",t,r)}function OT(e,t,r){Ft(e,t,r),Pt(e.id,t,`${r}.id`),br(e,"source",t,r),br(e,"version",t,r)}function NT(e,t,r){Ft(e,t,r),Pt(e.id,t,`${r}.id`),Pt(e.role,t,`${r}.role`),br(e,"instructions",t,r)}function TT(e,t,r){Ft(e,t,r),Pt(e.id,t,`${r}.id`),Tn(e.kind,AT,t,`${r}.kind`),Pt(e.source,t,`${r}.source`),Tn(e.sideEffect,xT,t,`${r}.sideEffect`),Eb(e,"requiresConfirmation",t,r)}function $T(e,t,r){Ft(e,t,r),Tn(e.type,ET,t,`${r}.type`),br(e,"ref",t,r),br(e,"prompt",t,r),br(e,"question",t,r),"options"in e&&Fl(e.options,t,`${r}.options`)}function jT(e,t,r){Ft(e,t,r),Pt(e.id,t,`${r}.id`),$T(e.action,t,`${r}.action`),br(e,"next",t,r),"completionEvals"in e&&Fl(e.completionEvals,t,`${r}.completionEvals`)}function DT(e,t){let r="goal";Ft(e,t,r),Pt(e.statement,t,`${r}.statement`),Nn(e.inputs,t,`${r}.inputs`),e.inputs.forEach((n,i)=>{Rb(n,t,`${r}.inputs[${i}]`)}),Nn(e.outputs,t,`${r}.outputs`),e.outputs.forEach((n,i)=>{Rb(n,t,`${r}.outputs[${i}]`)}),Fl(e.success,t,`${r}.success`)}function qT(e,t){let r="orchestration";Ft(e,t,r),Tn(e.mode,_T,t,`${r}.mode`),br(e,"entry",t,r),"steps"in e&&(Nn(e.steps,t,`${r}.steps`),e.steps.forEach((n,i)=>{jT(n,t,`${r}.steps[${i}]`)}))}function _b(e,t){return Ft(e,t),Tn(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),Tn(e.kind,["Skill"],t,"kind"),Ft(e.metadata,t,"metadata"),Pt(e.metadata.name,t,"metadata.name"),Pt(e.metadata.version,t,"metadata.version"),Pt(e.metadata.description,t,"metadata.description"),DT(e.goal,t),qT(e.orchestration,t),Nn(e.skills,t,"skills"),e.skills.forEach((r,n)=>{OT(r,t,`skills[${n}]`)}),Nn(e.agents,t,"agents"),e.agents.forEach((r,n)=>{NT(r,t,`agents[${n}]`)}),Nn(e.tools,t,"tools"),e.tools.forEach((r,n)=>{TT(r,t,`tools[${n}]`)}),e}function Ab(e,t){Ft(e,t);for(let r of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])r in e&&Fl(e[r],t,r);for(let r of["maxIterations","maxRetriesPerAction"])if(r in e&&(typeof e[r]!="number"||!Number.isFinite(e[r])))throw bi(t,r,"must be a finite number");return e}function LT(e,t){return Ft(e,t),"runtime"in e&&xb(e.runtime,t,"runtime"),e}function xb(e,t,r){return Nn(e,t,r),e.forEach((n,i)=>{let o=`${r}[${i}]`;Ft(n,t,o),Pt(n.id,t,`${o}.id`),Tn(n.scope,PT,t,`${o}.scope`),Tn(n.type,IT,t,`${o}.type`),br(n,"artifact",t,o),br(n,"field",t,o),br(n,"equals",t,o)}),e}async function Wp(e){let t=await Mp.readFile(e,"utf8");try{return(0,Cb.parse)(t)}catch(r){let n=r instanceof Error?r.message:String(r);throw bi(e,"document",n)}}async function MT(e){try{return await Wp(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Sb(e){try{return await Mp.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function WT(e){let t=ir.join(e,"checks.yaml"),r=ir.join(e,"evals.yaml"),[n,i]=await Promise.all([Sb(t),Sb(r)]);if(i)throw new Error(`${r}: evals.yaml is no longer supported; use checks.yaml`);return n?{document:LT(await Wp(t),t)}:{document:null}}async function Pb(e){let t=ir.resolve(e.root),r=ir.resolve(e.controlRoot);e.requireSkillMarkdown&&await Mp.access(ir.join(t,"SKILL.md"));let n=ir.join(r,"skill.yaml"),i=ir.join(r,"guardrails.yaml"),o=_b(await Wp(n),n),s=await MT(i),c=s===null?null:Ab(s,i),u=await WT(r),f={allowedSkills:o.skills.map(a=>a.id),allowedAgents:o.agents.map(a=>a.id),allowedTools:o.tools.map(a=>a.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:o.tools.filter(a=>a.requiresConfirmation).map(a=>a.id)};return{root:t,packageKind:e.packageKind==="runtime"?"runtime":void 0,definition:o,guardrails:{...f,...c},evals:u.document?.runtime??[]}}async function Ib(e){let t=ir.resolve(e);return Pb({root:t,controlRoot:ir.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Ob(e){let t=ir.resolve(e);return Pb({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function Nb(e,t,r=ir.join(t,"package.json")){Ft(e,r);let n=e.packageKind==="runtime"?"runtime":void 0,i=_b(e.definition,r),o=Ab(e.guardrails,r),s=xb(e.evals,r,"evals"),c={allowedSkills:i.skills.map(u=>u.id),allowedAgents:i.agents.map(u=>u.id),allowedTools:i.tools.map(u=>u.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:i.tools.filter(u=>u.requiresConfirmation).map(u=>u.id)};return{root:ir.resolve(t),packageKind:n,definition:i,guardrails:{...c,...o},evals:s}}import Tb from"path";function FT(e,t,r,n){e.type==="invoke_skill"&&!t.definition.skills.some(i=>i.id===e.ref)&&r.push(`step ${n} references undeclared skill: ${e.ref??"(missing)"}`),e.type==="call_tool"&&!t.definition.tools.some(i=>i.id===e.ref)&&r.push(`step ${n} references undeclared tool: ${e.ref??"(missing)"}`),e.type==="handoff"&&!t.definition.agents.some(i=>i.id===e.ref)&&r.push(`step ${n} references undeclared agent: ${e.ref??"(missing)"}`),e.type==="ask_user"&&!e.question&&r.push(`step ${n} ask_user action requires question`)}function $b(e){let t=[],{definition:r,guardrails:n,evals:i}=e;r.apiVersion!=="comet/v1alpha1"&&t.push("unsupported apiVersion"),r.kind!=="Skill"&&t.push("kind must be Skill"),r.metadata.name||t.push("metadata.name is required"),r.goal.statement||t.push("goal.statement is required"),n.maxIterations<1&&t.push("maxIterations must be at least 1"),n.maxRetriesPerAction<0&&t.push("maxRetriesPerAction must not be negative");let o=r.orchestration.steps??[];if(r.orchestration.mode==="adaptive")(r.orchestration.entry||o.length>0)&&t.push("adaptive orchestration must not define entry or steps");else{let s=new Set;for(let c of o)s.has(c.id)&&t.push(`duplicate step id: ${c.id}`),s.add(c.id),FT(c.action,e,t,c.id);(!r.orchestration.entry||!s.has(r.orchestration.entry))&&t.push(`orchestration.entry references unknown step: ${r.orchestration.entry??"(missing)"}`);for(let c of o){c.next&&!s.has(c.next)&&t.push(`step ${c.id} has unknown next step: ${c.next}`);for(let u of c.completionEvals??[])i.some(f=>f.id===u)||t.push(`step ${c.id} references unknown eval: ${u}`)}}for(let s of r.tools){if(s.kind!=="script")continue;let c=Tb.posix.normalize(s.source.replaceAll("\\","/"));(Tb.isAbsolute(s.source)||c===".."||c.startsWith("../"))&&t.push(`script tool ${s.id} must reference a relative path inside the Skill package`)}for(let s of n.allowedSkills)r.skills.some(c=>c.id===s)||t.push(`guardrails allow undeclared skill: ${s}`);for(let s of n.allowedAgents)r.agents.some(c=>c.id===s)||t.push(`guardrails allow undeclared agent: ${s}`);for(let s of n.allowedTools)r.tools.some(c=>c.id===s)||t.push(`guardrails allow undeclared tool: ${s}`);return t}function Hl(e){return Array.isArray(e)?e.map(Hl):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Hl(r)])):e}function VT(e){return Hl({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function BT(e){return rt.posix.normalize(e.replaceAll("\\","/"))}function Co(e,t,r){let n=rt.relative(e,t);if(!(n===""||!rt.isAbsolute(n)&&!n.startsWith(`..${rt.sep}`)))throw new Error(`${r} resolves outside the Skill package`)}async function Db(e,t,r){let n=BT(t);if(rt.posix.isAbsolute(n)||n===".."||n.startsWith("../"))throw new Error(`${r} resolves outside the Skill package`);let i=rt.resolve(e,...n.split("/"));Co(e,i,r);let o;try{o=await ct.realpath(i)}catch(s){throw s.code==="ENOENT"?new Error(`${r} does not exist: ${t}`,{cause:s}):s}if(Co(e,o,r),!(await ct.stat(o)).isFile())throw new Error(`${r} is not a file: ${t}`);return{path:n,content:await ct.readFile(o)}}async function UT(e){let t=await ct.realpath(e.root),r=e.packageKind==="runtime"?[]:[await Db(t,"SKILL.md","SKILL.md")];for(let n of e.definition.tools)n.kind==="script"&&r.push(await Db(t,n.source,`Script tool ${n.id}`));return r.sort((n,i)=>n.path.localeCompare(i.path))}function KT(e,t){let r=t.map(n=>({path:n.path,sha256:jb("sha256").update(n.content).digest("hex")}));return jb("sha256").update(JSON.stringify(Hl({package:e,files:r}))).digest("hex")}function Mb(e){return JSON.stringify(e,null,2)+`
157
+ `}async function Wb(e){let t=VT(e),r=await UT(e);return{document:t,files:r,hash:KT(t,r)}}async function Vl(e){return(await Wb(e)).hash}async function qb(e){try{return await ct.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Lb(e,t){try{if((await ct.readFile(rt.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await ct.readFile(rt.join(e,"package.json"),"utf8")!==Mb(t.document))throw new Error("package mismatch");for(let i of t.files)if(!(await ct.readFile(rt.join(e,...i.path.split("/")))).equals(i.content))throw new Error(`file mismatch: ${i.path}`)}catch(r){throw new Error(`Existing Skill snapshot is invalid: ${t.hash}`,{cause:r})}}async function Fp(e,t){let r=await Wb(e),n=rt.resolve(t,".comet","skill-snapshots"),i=rt.join(n,r.hash);if(await ct.mkdir(n,{recursive:!0}),await qb(i))return await Lb(i,r),{hash:r.hash,snapshotDir:i};let o=rt.join(n,`.tmp-${HT()}`);Co(n,o,"Temporary snapshot"),Co(n,i,"Published snapshot");try{await ct.mkdir(o);for(let s of r.files){let c=rt.join(o,...s.path.split("/"));Co(o,c,`Snapshot file ${s.path}`),await ct.mkdir(rt.dirname(c),{recursive:!0}),await ct.writeFile(c,s.content)}await ct.writeFile(rt.join(o,"package.json"),Mb(r.document)),await ct.writeFile(rt.join(o,"sha256"),r.hash+`
158
+ `),await ct.rename(o,i)}catch(s){if(await qb(i)){try{await Lb(i,r)}finally{await ct.rm(o,{recursive:!0,force:!0})}return{hash:r.hash,snapshotDir:i}}throw await ct.rm(o,{recursive:!0,force:!0}),s}return{hash:r.hash,snapshotDir:i}}async function Hp(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let r=rt.resolve(e,".comet","skill-snapshots"),n=rt.join(r,t);Co(r,n,"Skill snapshot");try{let i=(await ct.readFile(rt.join(n,"sha256"),"utf8")).trim();if(i!==t)throw new Error(`stored hash is ${i||"(empty)"}`);let o=rt.join(n,"package.json"),s=JSON.parse(await ct.readFile(o,"utf8")),c=Nb(s,n,o),u=$b(c);if(u.length>0)throw new Error(u.map(a=>` - ${a}`).join(`
159
+ `));let f=await Vl(c);if(f!==t)throw new Error(`calculated hash is ${f}`);return c}catch(i){throw new Error(`Skill snapshot is invalid or missing: ${t}`,{cause:i})}}async function Fb(e){try{return await Vp.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Hb(e){return JT("sha256").update(e).digest("hex")}function GT(e){return Hb(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)))))}function YT(e){return e.replaceAll(".","_").replaceAll("-","_")}async function XT(e,t){let r=await at(e),n=Object.fromEntries(t.filter(s=>s.satisfied&&s.source).map(s=>[YT(s.code),s.source])),i=en.join(e,"subagent-progress.md");await Fb(i)&&(n.subagent_progress=en.relative(r,i).split(en.sep).join("/"));let o=t.find(s=>s.code==="design.handoff"&&s.satisfied);return o?.source&&(n.handoff_context=o.source),n}function QT(e,t,r){return[{sequence:1,timestamp:r,type:"run_started",runId:e.runId,data:{skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash}},{sequence:2,timestamp:r,type:"state_migrated",runId:e.runId,data:{kind:"classic",migrationVersion:wi,profile:t,source:"pre-migration"}}]}async function ZT(e){await Promise.all(e.map(t=>Vp.rm(t,{recursive:!0,force:!0})))}async function Vb(e,t){return Zr(e,()=>e$(e,t))}async function e$(e,t){let r=await at(e),n=await Fe(r,await Re(e),{label:"Classic migration state"});if(At(n))throw new Error("Classic managed Run is owned by the SDK and cannot be migrated to compat");let i=await Ro(e);if(!i.classic)throw new Error("Classic migration requires a legacy state projection");let o=i.classic,s=o.classicProfile??o.workflow;if(i.run){if(o.classicMigration!==wi)throw new Error("Classic Run exists without a supported classic_migration marker");if(i.run.skill!==t.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${t.skillPackage.definition.metadata.name}, got ${i.run.skill}`);if(await Vl(t.skillPackage)!==i.run.skillHash)return await Hp(await Se(e),i.run.skillHash),{classic:o,run:i.run,evidence:await bo(e,i),migrated:!1,snapshotDir:en.join(await Se(e),".comet","skill-snapshots",i.run.skillHash)};let m=await Fp(t.skillPackage,await Se(e));return{classic:o,run:i.run,evidence:await bo(e,i),migrated:!1,snapshotDir:m.snapshotDir}}let c=await bo(e,i),u=Wl(o,c);if(!t.skillPackage.definition.orchestration.steps?.some(l=>l.id===u))throw new Error(`Classic Skill package does not define resolved step: ${u}`);let f=await Vl(t.skillPackage),a=en.join(await Se(e),".comet","skill-snapshots",f),d=await Fb(a),p=[];try{let l=await Fp(t.skillPackage,await Se(e)),m=bb(t.skillPackage,t.runId?.()??zT(),l.hash);m.currentStep=u,u==="completed"&&(m.status="completed");let h={...o,classicProfile:s,classicMigration:wi},g=await XT(e,c),w=await at(e),k=c.find(O=>O.code==="design.handoff"&&O.satisfied),b=null;k?.source&&(b=await Fe(w,k.resolvedSource??k.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await ql(e,m.contextRef,b),p.push(en.resolve(await Se(e),m.contextRef))),await Dl(e,m.artifactsRef,g),p.push(en.resolve(await Se(e),m.artifactsRef));let S=(t.now?.()??new Date).toISOString(),E={runId:m.runId,stateVersion:1,trajectoryOffset:2,contextHash:b===null?null:Hb(b),artifactsHash:GT(g),createdAt:S};await fb(e,m.checkpointRef,E),p.push(en.resolve(await Se(e),m.checkpointRef)),p.push(en.resolve(await Se(e),m.trajectoryRef));for(let O of QT(m,s,S))await vo(e,m.trajectoryRef,O);return await So(e,{classic:h,run:m,unknownKeys:i.unknownKeys}),{classic:h,run:m,evidence:c,migrated:!0,snapshotDir:l.snapshotDir}}catch(l){throw await ZT(p),d||await Vp.rm(a,{recursive:!0,force:!0}),l}}async function t$(e){try{return(await Bb.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bl(e){try{return(await Bb.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function r$(e){return await t$(e)?await Bl(Qt.join(e,"skill.yaml"))?!0:await Bl(Qt.join(e,"SKILL.md"))&&await Bl(Qt.join(e,"comet","skill.yaml")):!1}function n$(e){return{root:e,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.configure"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function i$(){let e=Qt.dirname(Ub(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Qt.resolve(e,"..","runtime","classic"),Qt.resolve(e,"..","..","comet","runtime","classic"),Qt.resolve(e,"..","..","assets","skills","comet","runtime","classic"),Qt.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Qt.resolve(e,"..","..","comet-classic"),Qt.resolve(e,"..","..","assets","skills","comet-classic"),Qt.resolve("assets","skills","comet-classic")].filter(r=>!!r);for(let r of t)if(await r$(r))return r;return null}async function o$(e){return await Bl(Qt.join(e,"skill.yaml"))?Ob(e):Ib(e)}async function Kb(e){let t=await i$();return Vb(e,{skillPackage:t?await o$(t):n$(Qt.dirname(Ub(import.meta.url)))})}async function Jb(e,t,r,n){return Zr(e,()=>s$(e,t,r,n))}async function s$(e,t,r,n){let i=await Ro(e);if(!i.classic||!i.run)throw new Error("Classic transition requires synchronized Classic and Run projections");if(i.run.runId!==r.runId||i.run.iteration!==r.iteration||(t.checkEpoch??0)<(i.classic.checkEpoch??0))throw new Error("Classic transition became stale; reload the current state");let o=await bo(e,{classic:t,run:r,unknownKeys:i.unknownKeys}),s=Wl(t,o),c={...r,currentStep:s,iteration:r.iteration+1,status:s==="completed"?"completed":"running"};await So(e,{classic:t,run:c,unknownKeys:i.unknownKeys});let u=await jl(e,c.trajectoryRef);return await vo(e,c.trajectoryRef,{sequence:u.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:c.runId,data:{kind:"classic",fromStep:r.currentStep,toStep:s,...n}}),c}function c$(e,t,r,n){return["# Comet Design Handoff","","- Change: "+e,"- Phase: design","- Mode: "+t,"","Generated-by: comet handoff","","Read source files for current requirements and task completion.","",...n.flatMap(i=>["## "+i.reference,"","- Source: "+i.reference,"",i.content,""])].join(`
160
+ `)}async function zb(e){let{projectRoot:t,changeDir:r,change:n}=e,i=tt(t,r);if(e.run&&(e.run.input.change!==n||e.run.input.changeDir!==i))throw new Error("Classic Design context belongs to a different Run");let o=i+"/proposal.md";if(!(await Fe(t,o,{label:"Classic Design source"})).trim())throw new Error("Classic Design source is empty");return{handoffContext:o,handoffHash:e.run?.actions.at(-1)?.inputHash??null}}async function Ul(e){let t=tt(e.projectRoot,e.changeDir),r=e.contextCompression==="beta"?"spec-context":"design-context";return[t+"/proposal.md",t+"/.comet/handoff/"+r+".json"].includes(e.handoffContext)?(await zb(e)).handoffContext===t+"/proposal.md":!1}async function Bp(e){let{projectRoot:t,changeDir:r,change:n}=e,i=[],o=[...["proposal.md","design.md","tasks.md"].map(c=>r+"/"+c),...await wo(t,r+"/specs")];for(let c of o)await Lr(t,c,{label:"Classic handoff source",expected:"file"})&&i.push({reference:tt(t,c),content:await Fe(t,c,{label:"Classic handoff source"})});await jp(t,r+"/.comet/handoff","Classic handoff view directory");let s=r+"/.comet/handoff/design-context.md";return await go(t,s,c$(n,"full","",i),{label:"Classic handoff view"}),tt(t,s)}var Up=cl(async e=>{let[t,r,n,i]=e;if(r==="--hash-only")return{exitCode:64,stderr:`handoff --hash-only 已移除。由 Agent 读取实际文档并判断上下文是否需要更新。
161
+ `};if(r!=="design"||n!=="--write"||e.length!==3&&!(e.length===4&&i==="--full"))return{exitCode:64,stderr:`Usage: comet handoff <change-name> design --write [--full]
162
+ `};let o=Ks(t);if(o)return{exitCode:1,stderr:o};let s=al(),c=await fi(s),u=await Pl(t,c.projectRoot);return!u.exists||!u.stateExists?{exitCode:1,stderr:"Classic change directory or state is missing"}:Zr(u.directory,async()=>{let f=await Ro(u.directory);if(!f.classic||!["design","build"].includes(f.classic.phase))throw new Error("Design handoff requires phase: design or build");let a=await Ol(s,u.directory);if(a.problems.length)throw new Error(a.problems.join(`
163
+ `));let d=await Kb(u.directory),p=await ub(u.directory,d.run.pendingRef);if(d.run.pending&&p?.type!=="handoff")throw new Error("Another Classic action is pending");if(p&&d.run.pending!==p.id)throw new Error("Classic handoff pending identity does not match the original Run");let l=await zb({projectRoot:s,changeDir:u.directory,change:t,contextCompression:d.classic.contextCompression}),m=l.handoffContext.replace(/\.json$/u,".md"),h=await Fe(s,m,{label:"Classic handoff"}),g=i==="--full"?await Bp({projectRoot:s,changeDir:u.directory,change:t}):null;await ql(u.directory,d.run.contextRef,h),await Dl(u.directory,d.run.artifactsRef,{...await lb(u.directory,d.run.artifactsRef),handoff_context:l.handoffContext,handoff_markdown:m});let w={...d.classic,...l},k={...d.run,pending:null};if(k.currentStep==="full.design.handoff"&&(k=await Jb(u.directory,w,k,{actionId:p?.id??a$(),kind:"classic-handoff"})),await So(u.directory,{...f,classic:w,run:k}),p){let S=await jl(u.directory,k.trajectoryRef);S.some(E=>E.type==="recovery_reconciled"&&E.data?.actionId===p.id)||await vo(u.directory,k.trajectoryRef,{sequence:S.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:k.runId,data:{kind:"classic-handoff",actionId:p.id}}),await db(u.directory,d.run.pendingRef)}let b=Tl({name:t,locale:Nl(w.language)});return{exitCode:0,envelope:b,stderr:b.summary+`
164
+ [HANDOFF] source `+l.handoffContext+(g?`
165
+ [HANDOFF] view `+g:"")+`
166
+ `}})});import{promises as GW}from"node:fs";var Ig=Tt(Gt(),1);import O_ from"node:path";jr();Lt();ai();ye();import{promises as l$}from"node:fs";import{AsyncLocalStorage as u$}from"node:async_hooks";import Rr from"node:path";var Si="comet.change-owner.v1",Yb=["native","classic-full","classic-hotfix","classic-tweak"],d$=gt("changeOwnerRuntimeRoots",e=>Tp(e)),Xb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Sr(e,t,r="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!Xb.test(t))throw new Error(`Invalid change name: ${t}`);return`${r==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function Jp(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Change runtime owner must be a JSON object");let n=e,i=n.schema===Si&&n.workflow===t&&n.change===r,o=n.format==="compat"&&Object.keys(n).length===4,s=n.format==="sdk"&&Object.keys(n).length===6&&n.runId===r&&(typeof n.application=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(n.application)&&!Yb.includes(n.application)||(t==="native"?n.application==="native":n.application==="classic-full"||n.application==="classic-hotfix"||n.application==="classic-tweak"));if(!i||!o&&!s)throw new Error(`Invalid change runtime owner for ${t}/${r}`);return n}async function Kl(e,t,r,n){let i;try{({bytes:i}=await ae(e,t,Number.MAX_SAFE_INTEGER,{label:"change runtime owner"}))}catch(s){if(s.code==="ENOENT")return null;throw s}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new Error(`Invalid change runtime owner JSON for ${r}/${n}`)}return Jp(o,r,n)}function Qb(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function Zb(e,t){return Sr(e,t),`change-owner-records/${e}/${t}.json`}async function zp(e,t,r){let n;try{n=await ae(e,Zb(t,r),Number.MAX_SAFE_INTEGER,{label:"canonical change runtime owner",bigint:!0})}catch(o){if(o.code==="ENOENT")return null;throw o}let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n.bytes))}catch{throw new Error(`Invalid canonical Runtime owner for ${t}/${r}`)}return{owner:Jp(i,t,r),identity:Qb(n.stat)}}async function eR(e,t,r){let n=await $s(e,"change owner bindings"),i=async c=>{try{let{stat:u}=await n.stat(Sr(t,r,c));return Qb(u)}catch(u){if(u.code==="ENOENT")return null;throw u}},o=await i("active"),s=await i("history");return await n.finish({allowDirectoryContentChanges:!0}),{active:o,history:s}}async function f$(e,t,r=!1){let n=await eR(e,t.workflow,t.change);if(n.active===null&&n.history===null)return;if(n.active!==null&&n.history!==null)throw new Error(`Conflicting or missing Runtime owner for ${t.workflow}/${t.change}`);let i=r?null:await zp(e,t.workflow,t.change);if(i?.identity&&i.identity===(n.active??n.history))return;let o=Zb(t.workflow,t.change);await ft(e,Rr.posix.dirname(o),{label:"canonical change runtime owners"});let s=Sr(t.workflow,t.change,n.active?"active":"history");try{await ck(Rr.join(e,s),Rr.join(e,o),{containedRoot:e})}catch(c){if(!["ENOTSUP","EOPNOTSUPP"].includes(c.code??""))throw c}}async function p$(e,t,r){let n;try{n=await zp(e,t,r)}catch(o){if(o instanceof ut&&o.reason==="changed")return null;throw o}if(!n?.identity)return null;let i=await eR(e,t,r);return i.active===n.identity&&i.history===null||i.history===n.identity&&i.active===null?n:null}var Ri=new u$,tR=$r("verifiedOwnerBatchResults",()=>new Map),rR=(e,t,r)=>`${JSON.stringify([e,t])}\0${r}`;async function nR(e){let t=Ri.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??d$(e)}async function iR(e,t,r=!1){let n=Ri.getStore();if(n?.active&&e.every(o=>n.roots.has(o)))return t();let i={roots:new Set(e),runtimeRoots:new Map,owners:new Map,projects:new Set,active:!0};try{let o=await Ri.run(i,()=>An(()=>r?Yv(t):t())),s=tR();for(let c of s.keys())[...i.projects].some(u=>c.startsWith(u+"\0"))&&s.delete(c);for(let[c,u]of i.owners)s.set(c,u);return o}finally{i.active=!1}}async function Kp(e,t,r){let n=await p$(e,t,r);return n?n.owner:iR([e],async()=>{let i=await Kl(e,Sr(t,r),t,r),o=await Kl(e,Sr(t,r,"history"),t,r);if(i&&o)throw new Error(`Conflicting active and history Runtime owners for ${t}/${r}`);return i??o})}async function $n(e,t,r,n={}){if(Sr(t,r),!n.readOnly)return Ri.run(null,()=>An(async()=>Kp(await Qr(e),t,r)));let[i,o]=await nR(e),s=Rr.parse(i).root,u=(await U(s,Rr.relative(s,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await Kp(i,t,r):null,f=o?await Kp(o,t,r):null;if(u&&f&&JSON.stringify(Object.entries(u).sort())!==JSON.stringify(Object.entries(f).sort()))throw new Error(`Conflicting current and legacy Runtime owners for ${t}/${r}`);return u??f}async function Gb(e,t,r,n={}){let i=await $n(e,t,r,n),o=i?.format==="sdk"?i:null,s=Ri.getStore();return n.readOnly&&s?.active&&s.owners.set(rR(e,t,r),o),o}async function ea(e,t,r,n={}){if(!n.readOnly||Ri.getStore()?.active)return Gb(e,t,r,n);let i=tR(),o=rR(e,t,r);if(i.has(o))return i.get(o);let s=Gb(e,t,r,n).catch(c=>{throw i.get(o)===s&&i.delete(o),c});return i.set(o,s),s}async function m$(e,t,r,n=!1){Sr(t,"validate");let i=r.readOnly?await nR(e):[await Qr(e)],o=async()=>{let s={active:new Set,history:new Set};for(let c of i)for(let u of["active","history"]){let f=Rr.parse(c).root,a=Rr.posix.dirname(Sr(t,"validate",u)),d=await U(f,Rr.relative(f,Rr.join(c,a)).replaceAll("\\","/"),{label:`${t} ${u} change runtime owners`,expected:"directory"});if(!d.exists)continue;let p=await l$.readdir(d.target,{withFileTypes:!0});for(let l of p){if(l.isFile()&&/^\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.json\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/u.test(l.name))continue;if(t==="classic"&&u==="active"){let h=/^([a-z][a-z0-9]*(?:-[a-z0-9]+)*)\.lock(?:\.([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.(?:tmp|removed))?$/u;if(l.isFile()&&h.test(l.name)||l.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(l.name))continue}if(!l.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${l.name}`);let m=l.name.slice(0,-5);if(!l.isFile()||!Xb.test(m))throw new Error(`Invalid ${t} change runtime owner entry: ${l.name}`);s[u].add(m)}}return s};return n?o():iR(i,o)}var Vz=gt("changeOwnerPartitions",m$);async function h$(e,t,r){return Gv(),Ri.run(null,()=>An(async()=>{let n=await qr(e);return Sr(t.workflow,t.change),r(n)}))}async function oR(e,t,r={}){let n=Sr(t.workflow,t.change),i=Jp(t,t.workflow,t.change);return h$(e,i,async o=>{if(await Kl(o,Sr(t.workflow,t.change,"history"),t.workflow,t.change))throw new Error(`Change ${t.workflow}/${t.change} is in history; restore its active owner before registering`);await ft(o,Rr.posix.dirname(n),{label:"change runtime owner directory"});try{await $e(Rr.join(o,...n.split("/")),`${JSON.stringify(i)}
167
+ `,{containedRoot:o,exclusive:!0,requireAtomicPublication:!0})}catch(c){if(c.code!=="EEXIST")throw c;let u=await Kl(o,n,t.workflow,t.change);if(JSON.stringify(u)!==JSON.stringify(i))throw new Error(`Change ${t.workflow}/${t.change} is already bound to another Runtime`,{cause:c})}return(r.canonical||await zp(o,t.workflow,t.change))&&await f$(o,i),i})}function ta(e,t,r={}){return oR(e,t,r)}function sR(e,t){return oR(e,t)}ye();import zW from"node:path";import{randomUUID as A$}from"node:crypto";import{types as g$}from"node:util";import{createHash as w$}from"node:crypto";var aR=new WeakMap,cR=new WeakMap;function lR(e,t){let r=e!==null&&typeof e=="object"&&t?.(e);if(r){let i=cR.get(e);if(i!==void 0)return i}let n=JSON.stringify(e);return r&&n.length<=64*1024&&cR.set(e,n),n}function y$(e,t,r){let n=new WeakMap,i=w=>{let k=n.get(w);if(k)return k;let b=Array.isArray(w)?[...w]:{...w};return n.set(w,b),b},o=i(e),s=[],c=[],u=[],f=new Map,a=new Map,d=new WeakMap,p=new Map,l=new Map,m=new Map,h=w=>{let k=w&&typeof w=="object"?d.get(w):void 0;if(k!==void 0)return k;let b=lR(w,r);return k=f.get(b),k===void 0&&(k=s.length,s.push(w),f.set(b,k)),w&&typeof w=="object"&&d.set(w,k),k},g=w=>{let k=m.get(w);if(k!==void 0)return k;let b=w.base===void 0?void 0:g(w.base),S=c.length;return c.push({...b===void 0?{}:{base:b},entries:w.entries.map(([E,O])=>[E,h(O)]),removed:[...w.removed]}),m.set(w,S),S};for(let w of t){let k=o,b=e;for(let Y of w.path.slice(0,-1)){b=b[Y];let Q=i(b);Object.defineProperty(k,Y,{value:Q,enumerable:!0,writable:!0,configurable:!0}),k=Q}let S=w.path.at(-1),E=k[S];if(!E||typeof E!="object"||Array.isArray(E))continue;if(r?.(E)){let Y=aR.get(E);if(!Y){let Q=E,te=l.get(w.group),Z=Object.entries(Q),Pe=te?Z.filter(([Xe,I])=>!Object.hasOwn(te.source,Xe)||h(te.source[Xe])!==h(I)):Z,ee=te?Object.keys(te.source).filter(Xe=>!Object.hasOwn(Q,Xe)):[],he=te&&Pe.length+ee.length<Z.length;Y={...he?{base:te.node}:{},entries:he?Pe:Z,removed:he?ee:[]},aR.set(E,Y)}l.set(w.group,{source:E,node:Y}),u.push({path:w.path,map:g(Y)}),Object.defineProperty(k,S,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let O=new Map;for(let[Y,Q]of Object.entries(E)){let te=Q&&typeof Q=="object"?d.get(Q):void 0;if(te===void 0){let Z=lR(Q,r);te=f.get(Z),te===void 0&&(te=s.length,s.push(Q),f.set(Z,te)),Q&&typeof Q=="object"&&d.set(Q,te)}O.set(Y,te)}let K=JSON.stringify([...O]),D=a.get(K);if(D===void 0){let Y=p.get(w.group),Q=[...O].filter(([Pe,ee])=>Y?.entries.get(Pe)!==ee),te=Y?[...Y.entries.keys()].filter(Pe=>!O.has(Pe)):[],Z=Y&&Q.length+te.length<O.size;D=c.length,c.push({...Z?{base:Y.id}:{},entries:Z?Q:[...O],removed:Z?te:[]}),a.set(K,D)}p.set(w.group,{id:D,entries:O}),u.push({path:w.path,map:D}),Object.defineProperty(k,S,{value:{},enumerable:!0,writable:!0,configurable:!0})}return u.length?{record:o,pool:{version:1,values:s,maps:c,bindings:u}}:{record:o}}function v$(){let e=[],t=o=>o===null?0:e[o].height,r=(o,s,c,u)=>{let f=e.length;return e.push({key:o,value:s,left:c,right:u,height:1+Math.max(t(c),t(u))}),f},n=(o,s,c,u)=>{if(t(c)>t(u)+1){let f=e[c];if(t(f.left)>=t(f.right))return r(f.key,f.value,f.left,r(o,s,f.right,u));let a=e[f.right];return r(a.key,a.value,r(f.key,f.value,f.left,a.left),r(o,s,a.right,u))}if(t(u)>t(c)+1){let f=e[u];if(t(f.right)>=t(f.left))return r(f.key,f.value,r(o,s,c,f.left),f.right);let a=e[f.left];return r(a.key,a.value,r(o,s,c,a.left),r(f.key,f.value,a.right,f.right))}return r(o,s,c,u)},i=(o,s,c)=>{if(o===null)return c===void 0?null:r(s,c,null,null);let u=e[o];if(s<u.key){let a=i(u.left,s,c);return a===u.left?o:n(u.key,u.value,a,u.right)}if(s>u.key){let a=i(u.right,s,c);return a===u.right?o:n(u.key,u.value,u.left,a)}if(c!==void 0)return c===u.value?o:r(s,c,u.left,u.right);if(u.left===null)return u.right;if(u.right===null)return u.left;let f=e[u.right];for(;f.left!==null;)f=e[f.left];return n(f.key,f.value,u.left,i(u.right,f.key,void 0))};return{nodes:e,set:i}}function dR(e){let{nodes:t,set:r}=v$(),n=[];for(let u of e.maps){let f=u.base===void 0?null:n[u.base];for(let a of u.removed)f=r(f,a,void 0);for(let[a,d]of u.entries)f=r(f,a,d);n.push(f)}let i=[],o=new Map,s=u=>{if(u===null)return null;let f=o.get(u);if(f!==void 0)return f;let a=t[u],d=s(a.left),p=s(a.right),l=i.length;return i.push({...a,left:d,right:p}),o.set(u,l),l},c=n.map(s);return{version:3,values:e.values,nodes:i,maps:c,bindings:e.bindings}}function fR(e,t,r){let n=y$(e,t,r);return{record:n.record,...n.pool?{pool:dR(n.pool)}:{}}}var tn=new WeakMap,ra=new WeakMap;function*Jl(e,t=e.root){if(t===null)return;let r=e.pool.nodes[t];yield*Jl(e,r.left),yield[r.key,e.pool.values[r.value]],yield*Jl(e,r.right)}function k$(e){let t=n=>{let i=e.root;for(;i!==null;){let o=e.pool.nodes[i];if(n===o.key)return o.value;i=n<o.key?o.left:o.right}},r=new Proxy({},{ownKeys:()=>[...Jl(e)].map(([n])=>n),get:(n,i)=>typeof i=="string"?e.pool.values[t(i)??-1]:void 0,has:(n,i)=>typeof i=="string"&&t(i)!==void 0,getOwnPropertyDescriptor:(n,i)=>typeof i=="string"&&t(i)!==void 0?{value:e.pool.values[t(i)],enumerable:!0,configurable:!0,writable:!1}:void 0,set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1});return tn.set(r,e),r}var Je=e=>{throw new Error(e)},Eo=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;function pR(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return Je("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(o=>!["version","values","maps","bindings"].includes(o))&&Je("JSON 引用池字段无效"),i.maps.forEach((o,s)=>{(!o||!Array.isArray(o.entries)||!Array.isArray(o.removed)||o.base!==void 0&&!Eo(o.base,s)||Object.keys(o).some(u=>!["base","entries","removed"].includes(u)))&&Je("JSON 映射引用无效");let c=new Set;for(let u of o.removed)(typeof u!="string"||c.has(u))&&Je("JSON 删除键无效"),c.add(u);for(let u of o.entries)(!Array.isArray(u)||u.length!==2||typeof u[0]!="string"||!Eo(u[1],i.values.length)||c.has(u[0]))&&Je("JSON 值引用无效"),c.add(u[0])}),pR(dR(i))}let r=e;if(r.version!==3||!Array.isArray(r.nodes)||Object.keys(r).some(i=>!["version","values","maps","bindings","nodes"].includes(i)))return Je("JSON 引用池版本或字段无效");let n=[];return r.nodes.forEach((i,o)=>{(!i||typeof i.key!="string"||!Eo(i.value,r.values.length)||![i.left,i.right].every(u=>u===null||Eo(u,o))||Object.keys(i).some(u=>!["key","value","left","right","height"].includes(u)))&&Je("JSON 树引用无效");let s=i.left===null?void 0:r.nodes[i.left],c=i.right===null?void 0:r.nodes[i.right];(i.height!==1+Math.max(s?.height??0,c?.height??0)||Math.abs((s?.height??0)-(c?.height??0))>1||i.left!==null&&n[i.left].max>=i.key||i.right!==null&&n[i.right].min<=i.key)&&Je("JSON 树顺序或平衡无效"),n.push({min:i.left===null?i.key:n[i.left].min,max:i.right===null?i.key:n[i.right].max})}),r.maps.some(i=>i!==null&&!Eo(i,r.nodes.length))&&Je("JSON 映射根无效"),r}function b$(e,t){let r=(m,h=0,g=new Set)=>{if(h>64&&Je("JSON 数据嵌套过深"),!(m===null||typeof m=="string"||typeof m=="boolean"||typeof m=="number"&&Number.isFinite(m))){if(typeof m!="object"||m===null||g$.isProxy(m)||g.has(m))return Je("JSON 数据无效");Object.getPrototypeOf(m)!==Object.prototype&&Object.getPrototypeOf(m)!==null&&!Array.isArray(m)&&Je("JSON 数据必须为普通对象"),g.add(m);for(let w of Reflect.ownKeys(m)){if(Array.isArray(m)&&w==="length")continue;let k=Object.getOwnPropertyDescriptor(m,w);(typeof w!="string"||!k.enumerable||!("value"in k))&&Je("JSON 数据不能包含访问器"),r(k.value,h+1,g)}Array.isArray(m)&&Object.keys(m).length!==m.length&&Je("JSON 数组不能稀疏"),g.delete(m)}};r(e),r(t);let n=pR(structuredClone(t)),i=structuredClone(e),o={validatedNodes:n.nodes.length,validationActions:0,validationResultMaps:0,validationEntries:0,validationMaterializedEntries:0,materializedMaps:0,materializedEntries:0,hashBytes:0,logicalHashBytes:0},s=new Set,c=new Set,u=new Set,f=new Map;for(let m of n.bindings){(!m||!Array.isArray(m.path)||m.path.length<1||m.path.length>16||m.path.some(k=>typeof k!="string"||["__proto__","constructor","prototype"].includes(k))||!Eo(m.map,n.maps.length)||Object.keys(m).some(k=>!["path","map"].includes(k)))&&Je("JSON 池绑定无效");let h=JSON.stringify(m.path);(c.has(h)||m.path.some((k,b)=>s.has(JSON.stringify(m.path.slice(0,b+1)))))&&Je("JSON 池绑定重复或重叠"),s.add(h),m.path.forEach((k,b)=>c.add(JSON.stringify(m.path.slice(0,b+1))));let g=i;for(let k of m.path.slice(0,-1))(!g||typeof g!="object"||!Object.hasOwn(g,k))&&Je("JSON 池绑定缺失"),g=g[k];let w=m.path.at(-1);(!g||!Object.hasOwn(g,w)||!g[w]||typeof g[w]!="object"||Array.isArray(g[w])||Object.keys(g[w]).length)&&Je("JSON 池绑定必须替换空对象"),Object.defineProperty(g,w,{value:k$({pool:n,root:n.maps[m.map],stats:o,checked:u,origins:f}),enumerable:!0,writable:!0,configurable:!0})}let a=new WeakMap,d=new Map,p=m=>{if(!m||typeof m!="object")return 0;let h=a.get(m);if(h!==void 0)return h;let g=tn.get(m),w=b=>{if(b===null)return 0;let S=d.get(b);if(S!==void 0)return S;let E=n.nodes[b],O=Math.max(1+p(n.values[E.value]),w(E.left),w(E.right));return d.set(b,O),O},k=g?w(g.root):Object.values(m).reduce((b,S)=>Math.max(b,1+p(S)),0);return a.set(m,k),k};p(i)>64&&Je("JSON 逻辑数据嵌套超过 64 层"),na(n),na(i);let l=m=>{if(!(!m||typeof m!="object"||tn.has(m)||ra.has(m))){ra.set(m,o);for(let h of Object.values(m))l(h)}};return l(i),{value:i,stats:o,materialize:(m=[])=>Ht(m.reduce((h,g)=>h?.[g],i)),hash:()=>yt(i)}}function na(e){let t=new WeakSet,r=n=>{if(!(!n||typeof n!="object"||tn.has(n)||t.has(n))){t.add(n);for(let i of Object.values(n))r(i);Object.freeze(n)}};return r(e),e}function Ht(e){if(e===null||typeof e!="object")return e;let t=tn.get(e);if(t){t.stats.materializedMaps++;let r=[...Jl(t)];return t.stats.materializedEntries+=r.length,Object.fromEntries(r.map(([n,i])=>[n,Ht(i)]))}return Array.isArray(e)?e.map(Ht):Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ht(n)]))}function zl(e,t){let r=tn.get(e);if(!r){for(let[i,o]of Object.entries(e))t(i,o);return}r.stats.validationResultMaps++;let n=i=>{if(i===null||r.checked.has(i))return;let o=r.pool.nodes[i];n(o.left),t(o.key,r.pool.values[o.value]),r.stats.validationEntries++,n(o.right),r.checked.add(i)};n(r.root)}function Gl(e,t,r){let n=tn.get(e),i=(c,u)=>{let f=u.sequence;return t.get(f)!==c&&Je("WorkflowRun 结果来源不一致"),f};if(!n){for(let[c,u]of Object.entries(e))i(c,u)>=r&&Je("WorkflowRun 结果序号无效");return}let o=n.origins.get(t);o||(o=new Map,n.origins.set(t,o));let s=c=>{if(c===null)return 0;let u=o.get(c);if(u!==void 0)return u;let f=n.pool.nodes[c],a=Math.max(i(f.key,n.pool.values[f.value]),s(f.left),s(f.right));return o.set(c,a),a};s(n.root)>=r&&Je("WorkflowRun 结果序号无效")}function R$(e){return Object.keys(e).sort((t,r)=>{let n=i=>String(Number(i))===i&&Number.isInteger(Number(i))&&Number(i)>=0&&Number(i)<4294967295;return n(t)||n(r)?n(t)&&n(r)?Number(t)-Number(r):n(t)?-1:1:t<r?-1:t>r?1:0})}var uR=new WeakMap;function yt(e,t={}){let r=w$("sha256"),n=e&&typeof e=="object"?ra.get(e):void 0,i=f=>{if(!f||typeof f!="object")return;let a=tn.get(f)?.stats??ra.get(f);if(a)return a;for(let d of Object.values(f)){let p=i(d);if(p)return p}};n??=i(e);let o=n&&t.cachePrefixes!==!1?uR.get(n):void 0;n&&!o&&t.cachePrefixes!==!1&&(o={root:{hash:r.copy(),next:new Map},size:0},uR.set(n,o));let s=o?.root,c=f=>{let a=Buffer.byteLength(f);n&&(n.logicalHashBytes+=a);let d=s?.next.get(f);if(d){r=d.hash.copy(),s=d;return}if(r.update(f),n&&(n.hashBytes+=a),s&&o&&o.size<1e5){let p={hash:r.copy(),next:new Map};s.next.set(f,p),s=p,o.size++}else s=void 0},u=f=>{if(f===null||typeof f!="object"){c(JSON.stringify(f));return}if(Array.isArray(f)){c("["),f.forEach((a,d)=>{d&&c(","),u(a)}),c("]");return}c("{"),R$(f).forEach((a,d)=>{d&&c(","),c(JSON.stringify(a)+":"),u(f[a])}),c("}")};return u(e),r.digest("hex")}function ia(e){return ra.get(e)??tn.get(e)?.stats}function Yl(e,t,r=!0){let n=b$(e,t);return r?n.materialize():n.value}var mR=Object.freeze({STORE_WRITER_FENCED:"inspect-run",STORE_INDEX_CORRUPT:"repair-storage",STORE_INDEX_EPOCH_CHANGED:"inspect-run",STORE_BUSY:"inspect-run",SCOPE_HELD:"inspect-run",INVALID_VALIDATION:"restore-definition",ACTION_ACTIVE:"reconcile-execution",ACTION_ALREADY_ADVANCED:"inspect-run",ACTION_ALREADY_CLAIMED:"inspect-run",ACTION_IN_FLIGHT:"reconcile-execution",ACTION_NOT_FOUND:"inspect-run",ACTION_NOT_PENDING:"inspect-run",ACTION_NOT_RUNNING:"inspect-run",ACTION_TERMINAL:"inspect-run",CAPABILITY_REQUIRED:"correct-input",CHILD_DEPTH_LIMIT:"restore-definition",CHILD_MANAGED:"inspect-run",COMMAND_CONFLICT:"correct-input",COMMAND_DISPATCH_FAILED:"manual-review",COMMAND_NOT_FOUND:"inspect-run",COMMAND_REJECTED:"correct-input",COMMAND_VALIDATION_ERROR:"manual-review",COMMAND_VALIDATOR_UNAVAILABLE:"restore-definition",DECISION_CONFLICT:"inspect-run",DUPLICATE_COMMAND_VALIDATOR:"restore-definition",DUPLICATE_EVIDENCE_VALIDATOR:"restore-definition",DUPLICATE_EXECUTOR:"restore-definition",DUPLICATE_STATE_VALIDATOR:"restore-definition",DUPLICATE_TRANSITION_HANDLER:"restore-definition",DUPLICATE_VALIDATOR:"restore-definition",DUPLICATE_WORKFLOW:"restore-definition",EVIDENCE_INVALIDATION_UNAVAILABLE:"restore-definition",EVIDENCE_KIND_MISMATCH:"correct-input",EVIDENCE_REJECTED:"correct-input",EVIDENCE_STEP_CHANGED:"restore-definition",EVIDENCE_STILL_VALID:"inspect-run",EVIDENCE_VALIDATOR_UNAVAILABLE:"restore-definition",EVIDENCE_WAIT_NOT_FOUND:"inspect-run",EVIDENCE_WAIT_RESOLVED:"inspect-run",EXECUTION_UNKNOWN:"reconcile-execution",EXECUTOR_UNAVAILABLE:"restore-definition",EXECUTOR_UNSUPPORTED:"correct-input",INITIAL_STATE_CONFLICT:"correct-input",INITIAL_STATE_INVALID:"correct-input",INITIAL_STATE_REQUIRED:"correct-input",INVALID_ACTION:"correct-input",INVALID_COMMAND:"correct-input",INVALID_DECISION:"correct-input",INVALID_EVIDENCE:"correct-input",INVALID_JOIN:"correct-input",INVALID_JSON:"correct-input",INVALID_OUTCOME:"correct-input",INVALID_REQUEST:"correct-input",INVALID_RUN:"correct-input",INVALID_WORKFLOW:"correct-input",OUTCOME_ALREADY_RECORDED:"inspect-run",OUTCOME_CONFLICT:"inspect-outcome",OUTCOME_PROCESSING_ERROR:"inspect-outcome",OUTCOME_REJECTED:"inspect-outcome",OUTPUT_INVALID:"inspect-outcome",PROPOSAL_INPUT_MISSING:"correct-input",RECONCILIATION_REQUIRED:"reconcile-execution",REQUEST_ABORTED:"inspect-run",REVISION_CONFLICT:"inspect-run",RUN_CANCELLED:"inspect-run",RUN_CONFLICT:"correct-input",RUN_FAILED:"inspect-run",RUN_NOT_FOUND:"inspect-run",RUN_STATE_INVALID:"restore-definition",RUN_TERMINAL:"inspect-run",STALE_ACTION:"inspect-run",STALE_PROPOSAL:"review-proposal",STATE_VALIDATOR_UNAVAILABLE:"restore-definition",STORE_ATOMIC_PUBLICATION_UNSUPPORTED:"repair-storage",STORE_CHANGED_DIRECTORY:"repair-storage",STORE_CORRUPT_RECORD:"repair-storage",STORE_INVALID_ENTRY:"repair-storage",STORE_INVALID_REVISION:"repair-storage",STORE_INVALID_ROOT:"repair-storage",STORE_INVALID_RUN_ID:"repair-storage",STORE_MISSING_REVISION:"repair-storage",TRANSITION_HANDLER_UNAVAILABLE:"restore-definition",TRANSITION_STATE_INVALID:"restore-definition",TRANSITION_TARGET_INVALID:"restore-definition",TRANSITION_UNAVAILABLE:"restore-definition",UNSUPPORTED_PROTOCOL:"restore-definition",VALIDATOR_UNAVAILABLE:"restore-definition",WAIT_NOT_FOUND:"inspect-run",WORKFLOW_CHANGED:"restore-definition",WORKFLOW_UNAVAILABLE:"restore-definition"}),v=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.name="RuntimeProtocolError",this.recovery=Object.hasOwn(mR,r)?mR[r]:"manual-review"}code;recovery};import{createHash as S$}from"node:crypto";import{types as C$}from"node:util";var Gp=new WeakMap,hR=new WeakMap;function or(e){return Gp.has(e)}function Xl(e,t=!0,r=!1,n=!1){let i=new Set,o=new WeakMap;function s(c,u){if(u>64)throw new v("INVALID_JSON","数据嵌套超过 64 层");if(c===null||typeof c=="string"||typeof c=="boolean")return r?JSON.stringify(c):c;if(typeof c=="number"&&Number.isFinite(c))return r?JSON.stringify(c):c===0?0:c;if(typeof c!="object"||c===null)throw new v("INVALID_JSON","数据必须能无损保存为 JSON");if(i.has(c))throw new v("INVALID_JSON","数据包含循环引用");if(C$.isProxy(c))throw new v("INVALID_JSON","仅接受无执行行为的 JSON 数据");let f=Gp.get(c);if(!t&&!r&&f!==void 0){if(u+f>64)throw new v("INVALID_JSON","数据嵌套超过 64 层");return o.set(c,{value:c,height:f}),c}let a=o.get(c);if(a){if(u+a.height>64)throw new v("INVALID_JSON","数据嵌套超过 64 层");return t?xe(a.value):r?a.value:c}i.add(c);let d=0,p=m=>m&&typeof m=="object"?o.get(m)?.height??0:0,l=m=>(o.set(c,{value:m,height:d}),n&&(Object.freeze(c),Gp.set(c,d)),m);try{if(Array.isArray(c)){if(Reflect.ownKeys(c).length!==c.length+1)throw new v("INVALID_JSON","数组不能包含空洞或额外属性");let w=[];for(let k=0;k<c.length;k+=1){let b=Object.getOwnPropertyDescriptor(c,String(k));if(!b||!("value"in b))throw new v("INVALID_JSON","数组元素必须是普通数据");let S=s(b.value,u+1);d=Math.max(d,1+p(b.value)),(t||r)&&w.push(S)}return l(r?`[${w.join(",")}]`:t?w:c)}let m=Object.getPrototypeOf(c);if(m!==Object.prototype&&m!==null)throw new v("INVALID_JSON","仅接受普通 JSON 对象");let h=[],g=Reflect.ownKeys(c);(t||r)&&g.sort((w,k)=>{let b=String(w),S=String(k),E=String(Number(b))===b&&Number.isInteger(Number(b))&&Number(b)>=0&&Number(b)<4294967295,O=String(Number(S))===S&&Number.isInteger(Number(S))&&Number(S)>=0&&Number(S)<4294967295;return E||O?E&&O?Number(b)-Number(S):E?-1:1:b<S?-1:b>S?1:0});for(let w of g){let k=Object.getOwnPropertyDescriptor(c,w);if(typeof w!="string"||!k.enumerable||!("value"in k))throw new v("INVALID_JSON","对象属性必须是可枚举的字符串数据属性");let b=s(k.value,u+1);d=Math.max(d,1+p(k.value)),(t||r)&&h.push([w,b])}return l(r?`{${h.map(([w,k])=>`${JSON.stringify(w)}:${k}`).join(",")}}`:t?Object.fromEntries(h):c)}finally{i.delete(c)}}return s(e,0)}function rn(e){return Xl(e,!1,!0)}function Ue(e){return Xl(e)}function xe(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(xe(e[n]));return r}let t={};for(let r of Object.keys(e)){let n=xe(e[r]);r==="__proto__"?Object.defineProperty(t,r,{value:n,enumerable:!0,writable:!0,configurable:!0}):t[r]=n}return t}function sr(e){Xl(e,!1)}function $(e){let t=e!==null&&typeof e=="object"&&or(e),r=t?hR.get(e):void 0;if(r!==void 0)return r;let n=S$("sha256").update(rn(e)).digest("hex");return t&&hR.set(e,n),n}function Ci(e){return Xl(e,!1,!1,!0),e}function lt(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new v("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function Hr(e){return or(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function Yp(e,t,r){if(t!==e.attempt||r!==e.inputHash)throw new v("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Xp(e){return["succeeded","failed","cancelled"].includes(e.status)}function gR(e){return wR(e,e.input)}function wR(e,t,r){for(let s of["id","runId","stepId","type"])lt(e[s],s);e.ref!==void 0&&lt(e.ref,"ref");let n=e.attempt??1;if(!Number.isSafeInteger(n)||n<1)throw new v("INVALID_ACTION","attempt 必须是正安全整数");let i=e.retry??"manual";if(!["idempotent","reconcile","manual"].includes(i))throw new v("INVALID_ACTION","retry 策略无效");let o=e.requiredCapabilities??[];for(let s of o)lt(s,"requiredCapabilities");return{protocolVersion:1,id:e.id,runId:e.runId,stepId:e.stepId,type:e.type,...e.ref===void 0?{}:{ref:e.ref},attempt:n,input:t,inputHash:r??$(t),status:"pending",retry:i,requiredCapabilities:[...new Set(o)],receipts:[],reconciliations:[]}}function yR(e,t){Yp(e,t.attempt,t.inputHash),lt(t.executorId,"executorId"),lt(t.token,"token"),t.sessionId!==void 0&&lt(t.sessionId,"sessionId");let r={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if($(e.claim)===$(r)&&e.status==="running")return Hr(e);throw new v("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new v("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...Hr(e),claim:r,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Qp(e,t){if(t=Ql(t),lt(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new v("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&lt(t.event,"event");let r=$(t),n=e.rejectedOutcomes?.find(o=>o.outcome.outcomeId===t.outcomeId);if(n)throw $(n.outcome)!==r?new v("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken"):new v(n.code,n.reason);let i=e.receipts.find(o=>o.outcomeId===t.outcomeId);if(i){if(i.hash!==r)throw new v("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken");return{action:Hr(e),duplicate:!0}}if(Yp(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new v("STALE_ACTION","结果不属于当前 Action");if(Xp(e))throw new v("ACTION_TERMINAL","Action 已终止,不能接受新结果");if(!e.claim||!["running","unknown"].includes(e.status))throw new v("ACTION_NOT_RUNNING","Action 尚未交给执行者");if(t.claimToken!==e.claim.token)throw new v("STALE_ACTION","结果不属于当前执行者的领取记录");for(let o of t.artifacts??[])if(lt(o.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(o.sha256))throw new v("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...Hr(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:r}]},duplicate:!1}}function vR(e,t){if(lt(t,"reason"),!["running","unknown"].includes(e.status))throw new v("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...Hr(e),status:"unknown",reason:t}}function kR(e,t){if(e.rejectedOutcomes?.some(n=>n.outcome.attempt===e.attempt))throw new v("OUTCOME_ALREADY_RECORDED","当前执行尝试已记录结果,不能声明未执行并重试;请核对并修正同一次结果");if(!["failed","unknown"].includes(e.status))throw new v("ACTION_ACTIVE","仅失败或待核对的 Action 可以重试");if((e.retry!=="idempotent"||e.status==="unknown")&&!t)throw new v("RECONCILIATION_REQUIRED","先核对外部执行结果;不能把断连当作未执行");let r=Hr(e);if(t){if(t.resolution!=="not-executed"||t.evidence===null)throw new v("RECONCILIATION_REQUIRED","需要明确的未执行结论与核对证据");r.reconciliations.push({attempt:e.attempt,resolution:"not-executed",evidence:Ue(t.evidence)})}if(!Number.isSafeInteger(e.attempt+1))throw new v("INVALID_ACTION","执行尝试次数溢出");return r.attempt+=1,r.status="pending",delete r.claim,delete r.executionOrigin,delete r.executionStop,delete r.cancellation,delete r.outcome,delete r.reason,r}function Zp(e,t){return lt(t,"reason"),Xp(e)?Hr(e):{...Hr(e),status:"cancelled",reason:t}}function bR(e,t){Cr(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let r of["actionId","inputHash","claimToken","evidence"])lt(t[r],r);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new v("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(Yp(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new v("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function em(e,t){if(bR(e,t),e.status!=="cancelled")throw new v("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&$(e.cancellation)!==$(t))throw new v("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Hr(e),cancellation:structuredClone(t)}}function tm(e,t){if(bR(e,t),!Xp(e))throw new v("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&$(e.executionStop)!==$(t))throw new v("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Hr(e),executionStop:structuredClone(t)}}function Cr(e,t,r="INVALID_ACTION"){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(n=>!t.includes(n)))throw new v(r,"执行记录包含无效结构或未知字段")}function Ql(e){let t=Ue(e),r=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(Cr(t,[...r,"artifacts","summary","event"],"INVALID_OUTCOME"),r.some(n=>!Object.hasOwn(t,n)))throw new v("INVALID_OUTCOME","执行结果缺少身份、绑定或 output 字段");for(let n of["actionId","inputHash","claimToken","outcomeId"])if(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096)throw new v("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(typeof t.attempt!="number"||!Number.isSafeInteger(t.attempt)||t.attempt<1)throw new v("INVALID_OUTCOME","attempt 必须是正安全整数");if(t.status!=="succeeded"&&t.status!=="failed")throw new v("INVALID_OUTCOME","status 必须是 succeeded 或 failed");for(let n of["summary","event"])if(t[n]!==void 0&&(typeof t[n]!="string"||!t[n].trim()||t[n].length>4096))throw new v("INVALID_OUTCOME",`${n} 必须是非空字符串`);if(t.artifacts!==void 0){if(!Array.isArray(t.artifacts))throw new v("INVALID_OUTCOME","产物引用必须是数组");for(let n of t.artifacts)if(Cr(n,["uri","sha256"],"INVALID_OUTCOME"),typeof n.uri!="string"||!n.uri.trim()||typeof n.sha256!="string"||!/^[a-f0-9]{64}$/.test(n.sha256))throw new v("INVALID_OUTCOME","产物引用必须包含 URI 与 SHA-256")}return t}function Zl(e,t){if(Cr(e,["protocolVersion","id","runId","stepId","type","ref","attempt","input","inputHash","status","retry","requiredCapabilities","claim","outcome","receipts","rejectedOutcomes","reconciliations","reason","cancellation","executionOrigin","executionStop"]),e.protocolVersion!==1)throw new v("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Action 协议版本");if(!Array.isArray(e.requiredCapabilities)||!Array.isArray(e.receipts)||!Array.isArray(e.reconciliations))throw new v("INVALID_ACTION","Action 缺少能力、结果或核对记录");let r=e,n=wR(r,r.input,t);if(r.inputHash!==n.inputHash||r.retry!==n.retry||r.attempt!==n.attempt)throw new v("INVALID_ACTION","Action 输入绑定或执行参数不完整");if(!["pending","running","unknown","succeeded","failed","cancelled"].includes(r.status))throw new v("INVALID_ACTION","Action 状态无效");if(r.reason!==void 0&&lt(r.reason,"reason"),r.claim!==void 0&&(Cr(r.claim,["executorId","sessionId","token"]),lt(r.claim.executorId,"executorId"),lt(r.claim.token,"token"),r.claim.sessionId!==void 0&&lt(r.claim.sessionId,"sessionId")),r.status==="pending"&&r.claim||["running","unknown","succeeded","failed"].includes(r.status)&&!r.claim)throw new v("INVALID_ACTION","Action 状态与执行归属不一致");if(r.executionOrigin!==void 0&&(Cr(r.executionOrigin,["workflow"]),Cr(r.executionOrigin.workflow,["id","version","hash"]),lt(r.executionOrigin.workflow.id,"executionOrigin.workflow.id"),lt(r.executionOrigin.workflow.version,"executionOrigin.workflow.version"),!r.claim||!/^[a-f0-9]{64}$/u.test(r.executionOrigin.workflow.hash)))throw new v("INVALID_ACTION","执行来源必须包含领取记录和有效工作流摘要");r.cancellation!==void 0&&em({...r,input:null},r.cancellation),r.executionStop!==void 0&&tm({...r,input:null},r.executionStop);let i=new Set;for(let s of r.receipts){if(Cr(s,["outcomeId","hash"]),lt(s.outcomeId,"outcomeId"),!/^[a-f0-9]{64}$/.test(s.hash)||i.has(s.outcomeId))throw new v("INVALID_ACTION","结果记录的标识或摘要无效");i.add(s.outcomeId)}if(r.rejectedOutcomes!==void 0){if(!Array.isArray(r.rejectedOutcomes))throw new v("INVALID_ACTION","Action 的拒绝结果记录必须是数组");let s=new Set;for(let c of r.rejectedOutcomes){if(Cr(c,["outcome","code","reason"]),!["OUTPUT_INVALID","OUTCOME_REJECTED","OUTCOME_PROCESSING_ERROR"].includes(c.code))throw new v("INVALID_ACTION","Action 的拒绝结果代码无效");if(typeof c.reason!="string"||!c.reason.trim())throw new v("INVALID_ACTION","Action 的拒绝结果缺少原因");let u=Ql(c.outcome),f=r.receipts.find(a=>a.outcomeId===u.outcomeId);if(s.has(u.outcomeId)||!f||f.hash!==$(u)||u.actionId!==r.id||u.inputHash!==r.inputHash||u.attempt>r.attempt||u.attempt===r.attempt&&r.claim?.token!==u.claimToken)throw new v("INVALID_ACTION","Action 的拒绝结果与当前执行记录不一致");s.add(u.outcomeId)}}let o=new Set;for(let s of r.reconciliations){if(Cr(s,["attempt","resolution","evidence"]),!Number.isSafeInteger(s.attempt)||s.attempt<1||s.attempt>=r.attempt||o.has(s.attempt)||s.resolution!=="not-executed"||s.evidence===null||s.evidence===void 0)throw new v("INVALID_ACTION","核对记录与执行尝试不一致");o.add(s.attempt)}if(r.status==="succeeded"||r.status==="failed"){if(Cr(r.outcome,["actionId","attempt","inputHash","claimToken","outcomeId","status","output","artifacts","summary","event"]),r.outcome.status!==r.status||r.outcome.output===void 0)throw new v("INVALID_ACTION","终态 Action 缺少匹配的结果");let s=r.receipts.find(c=>c.outcomeId===r.outcome.outcomeId);if(!s||s.hash!==$(r.outcome))throw new v("INVALID_ACTION","终态结果与已接受摘要不一致");Qp({...r,input:null,status:"running",receipts:[]},r.outcome)}else if(r.outcome!==void 0)throw new v("INVALID_ACTION","非执行终态不能保存当前执行结果");return r}function rm(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}var ER=new WeakSet,_R=new WeakSet,nm=new WeakSet,RR=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"];function z(e){throw new v("INVALID_RUN",e)}function nt(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&z(`${t} 必须是 JSON 对象`),e}function ar(e,t,r){for(let n of Object.keys(e))t.includes(n)||z(`${r} 包含不支持的字段:${n}`)}function Ie(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&z(`${t} 必须是非空字符串且不超过 4096 字符`),e}function _o(e,t,r=0){return(!Number.isSafeInteger(e)||e<r)&&z(`${t} 必须是大于等于 ${r} 的安全整数`),e}function jn(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&z(`${t} 必须是 SHA-256 摘要`),e}function SR(e,t,r=!1){let n=nt(e,t);ar(n,r?["id","version","hash"]:["id","version"],t);let i={id:Ie(n.id,`${t}.id`),version:Ie(n.version,`${t}.version`)};return r&&(i.hash=jn(n.hash,`${t}.hash`)),i}function oa(e,t,r){let n=nt(e,t);if(!r&&or(n)&&_R.has(n))return n;let i=(o,s)=>{Ie(o,`${t} step id`);let c=nt(s,`${t}.${o}`);ar(c,["sequence","value"],`${t}.${o}`),(!Object.hasOwn(c,"sequence")||!Object.hasOwn(c,"value"))&&z(`${t}.${o} 缺少 sequence 或 value`),_o(c.sequence,`${t}.${o}.sequence`,1)};if(r)r.visitResults(n,i);else for(let[o,s]of Object.entries(n))i(o,s);return n}function CR(e,t,r){let n=nt(e,t);return ar(n,["from","to","results","activation"],t),(!Object.hasOwn(n,"from")||!Object.hasOwn(n,"to")||!Object.hasOwn(n,"results"))&&z(`${t} 缺少 from、to 或 results`),{from:n.from===null?null:Ie(n.from,`${t}.from`),to:Ie(n.to,`${t}.to`),results:oa(n.results,`${t}.results`,r),...Object.hasOwn(n,"activation")?{activation:n.activation}:{}}}function eu(e,t,r,n){let i=`${t}:`;e.startsWith(i)||z(`${r} 不属于当前 Run`);let o=e.slice(i.length);/^[1-9][0-9]*$/.test(o)||z(`${r} 的步骤序号无效`);let s=Number(o);return(!Number.isSafeInteger(s)||s>n)&&z(`${r} 的步骤序号超出 Run 范围`),s}function E$(e,t,r,n){let i=nt(e,"Wait");ar(i,["id","stepId","sequence","status","proposal","proposalHash","choices","results","decision"],"Wait");for(let d of["id","stepId","sequence","status","proposal","proposalHash","choices","results"])Object.hasOwn(i,d)||z(`Wait 缺少 ${d}`);let o=Ie(i.id,"Wait.id"),s=Ie(i.stepId,"Wait.stepId"),c=_o(i.sequence,"Wait.sequence",1);(c>r||eu(o,t,"Wait.id",r)!==c)&&z("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||z("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&z("Wait.choices 必须是非空数组");let u=i.choices.map(d=>Ie(d,"Wait.choices"));new Set(u).size!==u.length&&z("Wait.choices 不能重复");let f=jn(i.proposalHash,"Wait.proposalHash");$(i.proposal)!==f&&z("Wait.proposal 与 proposalHash 不一致");let a={id:o,stepId:s,sequence:c,status:i.status,proposal:i.proposal,proposalHash:f,choices:u,results:oa(i.results,"Wait.results",n)};if(i.decision!==void 0){let d=nt(i.decision,"Wait.decision");ar(d,["id","choice","proposalHash","reason"],"Wait.decision"),d.reason!==void 0&&!rm(d.reason)&&z("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let p={id:Ie(d.id,"Wait.decision.id"),choice:Ie(d.choice,"Wait.decision.choice"),proposalHash:jn(d.proposalHash,"Wait.decision.proposalHash"),...d.reason===void 0?{}:{reason:d.reason}};(i.status!=="resolved"||!u.includes(p.choice)||p.proposalHash!==f)&&z("Wait.decision 与 Wait 状态、选择或提案不一致"),a.decision=p}else i.status==="resolved"&&z("已解决的 Wait 必须保存对应 decision");return a}function _$(e,t,r,n){let i=nt(e,"EvidenceWait");ar(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let o=Ie(i.id,"EvidenceWait.id"),s=_o(i.sequence,"EvidenceWait.sequence",1);(s>r||eu(o,t,"EvidenceWait.id",r)!==s)&&z("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||z("EvidenceWait.status 无效");let c={id:o,stepId:Ie(i.stepId,"EvidenceWait.stepId"),sequence:s,kind:Ie(i.kind,"EvidenceWait.kind"),status:i.status,results:oa(i.results,"EvidenceWait.results",n)};if(i.receipt!==void 0){let u=nt(i.receipt,"EvidenceWait.receipt");ar(u,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),c.receipt={ref:Ie(u.ref,"EvidenceWait.receipt.ref"),contentHash:jn(u.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:Ie(u.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let u=nt(i.invalidation,"EvidenceWait.invalidation");ar(u,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),c.invalidation={ref:Ie(u.ref,"EvidenceWait.invalidation.ref"),contentHash:jn(u.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:Ie(u.submissionId,"EvidenceWait.invalidation.submissionId"),reason:Ie(u.reason,"EvidenceWait.invalidation.reason")}}return(c.status==="resolved"!=!!c.receipt||c.status==="invalidated"!=!!c.invalidation)&&z("EvidenceWait.receipt 与状态不一致"),c}function Ao(e,t){let r=nt(Ue(e),"WorkflowRun");return ru(r,t)}function AR(e,t){if(e&&typeof e=="object"&&nm.has(e)&&or(e)){let r=e;return t!==void 0&&r.runId!==t&&z("WorkflowRun.runId 与存储键不一致"),r}return sr(e),xR(ru(nt(structuredClone(e),"WorkflowRun"),t))}function sa(e,t,r){return ru(nt(e,"WorkflowRun"),t,void 0,r)}function tu(e,t){return sr(e),ru(nt(e,"WorkflowRun"),e.runId,t&&nm.has(t)&&or(t)?t:void 0),xR(e)}function xR(e){Ci(e),nm.add(e);for(let r of e.actions)ER.add(r);let t=r=>_R.add(r);for(let r of Object.values(e.actionContexts))t(r.results);for(let r of e.waits)t(r.results);for(let r of e.evidenceWaits??[])t(r.results);for(let r of e.ready)t(r.results);for(let r of Object.values(e.joins))for(let n of Object.values(r))for(let i of n)t(i.results);return t(e.outputs),e}function ru(e,t,r,n){ar(e,RR,"WorkflowRun");for(let I of RR.filter(H=>H!=="reason"&&H!=="state"&&H!=="evidenceWaits"&&H!=="initialStateHash"&&H!=="commands"))Object.hasOwn(e,I)||z(`WorkflowRun 缺少 ${I}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new v("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=Ie(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&z("WorkflowRun.runId 与存储键不一致");let o=_o(e.revision,"WorkflowRun.revision",1),s=_o(e.sequence,"WorkflowRun.sequence"),c=SR(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||z("WorkflowRun.status 无效"),e.reason!==void 0&&Ie(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||z("WorkflowRun 缺少 input");let u=nt(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(u).length===0&&z("WorkflowRun.definitionHashes 不能为空");for(let[I,H]of Object.entries(u)){let ie;try{ie=JSON.parse(I)}catch{z("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(ie)||ie.length!==2||typeof ie[0]!="string"||typeof ie[1]!="string"||JSON.stringify(ie)!==I)&&z("WorkflowRun.definitionHashes 包含非规范的工作流引用"),jn(H,`WorkflowRun.definitionHashes.${I}`)}let f=JSON.stringify([c.id,c.version]);u[f]!==c.hash&&z("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&z("WorkflowRun.lineage 必须是最多 32 层的数组");let a=e.lineage.map(I=>Ie(I,"WorkflowRun.lineage"));(new Set(a).size!==a.length||a.includes(i))&&z("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&z("WorkflowRun.actions 和 waits 必须是数组");let d=e.actions.map(I=>{let H;try{H=I&&typeof I=="object"&&ER.has(I)&&or(I)?I:Zl(I,n?.hash(I.input))}catch(ie){if(ie instanceof v&&ie.code==="UNSUPPORTED_PROTOCOL")throw ie;z(`WorkflowRun.actions 包含无效 Action:${ie.message}`)}return H.executionOrigin&&H.executionOrigin.workflow.id!==c.id&&z("Action 执行来源不属于当前工作流"),H.runId!==i&&z(`Action ${H.id} 不属于当前 Run`),new Set(H.requiredCapabilities).size!==H.requiredCapabilities.length&&z(`Action ${H.id} 的 requiredCapabilities 不能重复`),H}),p=new Map(d.map(I=>[I.id,I]));e.commands!==void 0&&!Array.isArray(e.commands)&&z("WorkflowRun.commands 必须是数组");let l=e.commands?.map(I=>{let H=nt(I,"WorkflowRun.commands item");ar(H,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let ie={id:Ie(H.id,"WorkflowRun.commands.id"),name:Ie(H.name,"WorkflowRun.commands.name"),inputHash:jn(H.inputHash,"WorkflowRun.commands.inputHash"),actionId:Ie(H.actionId,"WorkflowRun.commands.actionId")};return p.has(ie.actionId)||z("WorkflowRun.commands 指向不存在的 Action"),ie});l&&new Set(l.map(I=>I.id)).size!==l.length&&z("WorkflowRun.commands 标识不能重复");let m=e.waits.map(I=>E$(I,i,s,n));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&z("WorkflowRun.evidenceWaits 必须是数组");let h=e.evidenceWaits?.map(I=>_$(I,i,s,n))??[],g=new Map;for(let I of d){let H=eu(I.id,i,"Action.id",s);g.has(H)&&z("WorkflowRun 的步骤序号不能重复"),g.set(H,I.stepId)}for(let I of m)g.has(I.sequence)&&z("WorkflowRun 的步骤序号不能重复"),g.set(I.sequence,I.stepId);for(let I of h)g.has(I.sequence)&&z("WorkflowRun 的步骤序号不能重复"),g.set(I.sequence,I.stepId);g.size!==s&&z("WorkflowRun.sequence 与已激活步骤数量不一致");let w=nt(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(w).length!==d.length&&z("WorkflowRun.actionContexts 必须与 actions 一一对应");let k=new Map,b=r?new Map([...r.actions.map(I=>[r.actionContexts[I.id].sequence,I.stepId]),...r.waits.map(I=>[I.sequence,I.stepId]),...(r.evidenceWaits??[]).map(I=>[I.sequence,I.stepId])]):void 0;if(r&&b&&r.runId===i&&[...b].every(([I,H])=>g.get(I)===H)){let I=(H,ie)=>k.set(H,Math.min(k.get(H)??1/0,ie));for(let H of Object.values(r.actionContexts))I(H.results,H.sequence);for(let H of r.waits)I(H.results,H.sequence);for(let H of r.evidenceWaits??[])I(H.results,H.sequence);for(let H of r.ready)I(H.results,r.sequence+1);for(let H of Object.values(r.joins))for(let ie of Object.values(H))for(let Qe of ie)I(Qe.results,r.sequence+1);I(r.outputs,r.sequence+1)}let S=new Map;function E(I,H){let ie=H??s+1;if(n){n.validateOrigins(I,g,ie);return}let Qe=k.get(I);if(!(Qe!==void 0&&ie>=Qe&&or(I))&&!((S.get(I)??1/0)<=ie)){S.set(I,ie);for(let[C,T]of Object.entries(I))(T.sequence>=(H??s+1)||g.get(T.sequence)!==C)&&z(`WorkflowRun 结果 ${C} 的序号或来源不一致`)}}for(let I of d){Object.hasOwn(w,I.id)||z(`Action ${I.id} 缺少上下文`);let H=nt(w[I.id],`actionContexts.${I.id}`);ar(H,["sequence","results"],`actionContexts.${I.id}`);let ie=_o(H.sequence,`actionContexts.${I.id}.sequence`,1);ie!==eu(I.id,i,"Action.id",s)&&z(`Action ${I.id} 的上下文序号不一致`);let Qe=oa(H.results,`actionContexts.${I.id}.results`,n);E(Qe,ie)}for(let I of m)E(I.results,I.sequence);for(let I of h)E(I.results,I.sequence);Array.isArray(e.ready)||z("WorkflowRun.ready 必须是数组");let O=e.ready.map(I=>CR(I,"WorkflowRun.ready token",n));for(let I of O)E(I.results);let K=nt(e.joins,"WorkflowRun.joins"),D=Object.fromEntries(Object.entries(K).map(([I,H])=>{Ie(I,"WorkflowRun.joins step id");let ie=nt(H,`WorkflowRun.joins.${I}`),Qe=Object.fromEntries(Object.entries(ie).map(([C,T])=>{Ie(C,"WorkflowRun.joins parent id"),Array.isArray(T)||z(`WorkflowRun.joins.${I}.${C} 必须是数组`);let j=T.map(W=>{let F=CR(W,`WorkflowRun.joins.${I}.${C}`,n);return(F.to!==I||F.from!==C)&&z(`WorkflowRun.joins.${I}.${C} 包含错误来源的 token`),E(F.results),F});return[C,j]}));return[I,Qe]})),Y=oa(e.outputs,"WorkflowRun.outputs",n);E(Y),Array.isArray(e.children)||z("WorkflowRun.children 必须是数组");let Q=e.children.map(I=>{let H=nt(I,"WorkflowRun.children item");ar(H,["actionId","runId","workflow"],"WorkflowRun.children item");let ie=SR(H.workflow,"WorkflowRun.children.workflow"),Qe=Ie(H.actionId,"WorkflowRun.children.actionId"),C=Ie(H.runId,"WorkflowRun.children.runId"),T=p.get(Qe);return(!T||T.type!=="child_workflow"||T.ref!==`${ie.id}@${ie.version}`||C!==`child-${$(Qe)}`||!Object.hasOwn(u,JSON.stringify([ie.id,ie.version])))&&z("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:Qe,runId:C,workflow:ie}});(new Set(Q.map(I=>I.actionId)).size!==Q.length||d.filter(I=>I.type==="child_workflow").length!==Q.length)&&z("每个子工作流 Action 必须恰好对应一个 Child Run");let Z=d.some(I=>["pending","running","unknown"].includes(I.status)),Pe=m.some(I=>I.status==="pending"),ee=h.some(I=>I.status==="pending"),he=Object.values(D).some(I=>Object.values(I).some(H=>H.length>0));return e.status==="running"&&!Z&&O.length===0&&z("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(Z||!Pe&&!ee&&!he||O.length>0)&&z("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(Z||Pe||ee||he||O.length>0)&&z("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&z(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:o,workflow:c,definitionHashes:u,...e.initialStateHash===void 0?{}:{initialStateHash:jn(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:s,actions:d,...l===void 0?{}:{commands:l},actionContexts:w,waits:m,...e.evidenceWaits===void 0?{}:{evidenceWaits:h},ready:O,joins:D,outputs:Y,children:Q,lineage:a,...e.reason===void 0?{}:{reason:e.reason}}}var PR=new WeakMap;async function xo(e,t){let r=await(e.readProjection?e.readProjection(t):e.read(t));if(!r)throw new v("RUN_NOT_FOUND",`找不到工作流实例:${t}`);ia(r)||(sr(r),r=structuredClone(r),na(r));let n="run"in r?r.run:r;if(!n||n.runId!==r.runId||n.revision!==r.revision)throw new v("INVALID_RUN","Run 与存储 envelope 身份不一致");let i;try{i=sa(n,t,{hash:yt,visitResults:zl,validateOrigins:Gl})}catch(c){throw c instanceof v?c:new v("INVALID_RUN",c instanceof Error?c.message:String(c))}na(i);let o=ia(r);o&&(o.validationActions=i.actions.length,o.validationMaterializedEntries=o.materializedEntries);let s=e.queryScope??PR.get(e);return s||(s=A$(),PR.set(e,s)),Object.freeze({record:r,run:i,scope:s,stats:o,materialize:(c=[])=>Ht(c.reduce((u,f)=>u?.[f],i)),hash:()=>yt(i)})}var Dn=e=>{throw new v("INVALID_REQUEST",e)};function im(e,t){let{run:r,scope:n}=e;["current","summary","history","action","artifact"].includes(t.view)||Dn("query.view 无效");let i={runId:r.runId,revision:r.revision,status:r.status,workflow:r.workflow,sequence:r.sequence},o={actions:r.actions.length,waits:r.waits.length,evidenceWaits:r.evidenceWaits?.length??0},s=r.actions.filter(p=>["pending","running","unknown"].includes(p.status)||p.status==="cancelled"&&p.claim&&!p.executionStop&&!p.cancellation);if(t.view==="summary")return Ht({...i,history:o,pending:{actions:s.length,waits:r.waits.filter(p=>p.status==="pending").length,evidenceWaits:(r.evidenceWaits??[]).filter(p=>p.status==="pending").length}});if(t.view==="current")return Ht({...i,input:r.input,...r.state===void 0?{}:{state:r.state},...r.reason===void 0?{}:{reason:r.reason},actions:s,waits:r.waits.filter(p=>p.status==="pending"),evidenceWaits:(r.evidenceWaits??[]).filter(p=>p.status==="pending"),outputs:r.outputs,history:o});if(t.view==="action"||t.view==="artifact"){let p=r.actions.find(h=>h.id===t.actionId);if(p||Dn("query.actionId 不属于当前 Run"),t.view==="action")return Ht({...i,action:p,context:r.actionContexts[p.id]});let l=(p.outcome?.artifacts??[]).map(h=>({...h,artifactId:$({actionId:p.id,...h})})),m=t.artifactId===void 0?l:l.filter(h=>h.artifactId===t.artifactId);return t.artifactId!==void 0&&!m.length&&Dn("query.artifactId 不属于所选 Action"),Ht({...i,actionId:p.id,artifacts:m})}let c=t.limit??25;(!Number.isSafeInteger(c)||c<1||c>100)&&Dn("query.limit 必须在 1–100 之间");let u=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(u)||Dn("query.filter 无效");let f=$({scope:n,runId:r.runId,revision:r.revision,filter:u}),a=0;if(t.cursor)try{let p=JSON.parse(Buffer.from(t.cursor,"base64url").toString("utf8"));(p.binding!==f||!Number.isSafeInteger(p.offset)||p.offset<0||Object.keys(p).some(l=>!["binding","offset"].includes(l)))&&Dn("query.cursor 与当前存储、版本或筛选不匹配"),a=p.offset}catch{Dn("query.cursor 无效或已经过期")}let d=[...u==="all"||u==="actions"?r.actions.map((p,l)=>({kind:"action",sequence:r.actionContexts[p.id].sequence,path:["actions",String(l)]})):[],...u==="all"||u==="waits"?r.waits.map((p,l)=>({kind:"wait",sequence:p.sequence,path:["waits",String(l)]})):[],...u==="all"||u==="evidenceWaits"?(r.evidenceWaits??[]).map((p,l)=>({kind:"evidenceWait",sequence:p.sequence,path:["evidenceWaits",String(l)]})):[]].sort((p,l)=>l.sequence-p.sequence);return a>d.length&&Dn("query.cursor 超出历史范围"),{...Ht(i),records:d.slice(a,a+c).map(p=>({kind:p.kind,sequence:p.sequence,value:e.materialize(p.path)})),total:d.length,...a+c<d.length?{nextCursor:Buffer.from(JSON.stringify({binding:f,offset:a+c})).toString("base64url")}:{}}}import{randomUUID as eg}from"node:crypto";import{types as ng}from"node:util";var Xh=Tt(wE(),1);var Ye=Tt(dh(),1),RM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{action:{enum:["local","push","pr"]},commit:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$",type:"string"},prUrl:{minLength:1,type:"string"},remote:{minLength:1,type:"string"},targetBranch:{minLength:1,type:"string"}},required:["action","targetBranch","commit"],type:"object"},r=new RegExp("^[0-9a-f]{40}(?:[0-9a-f]{24})?$","u"),n=Ye.default.default??Ye.default;function i(o,{instancePath:s="",parentData:c,parentDataProperty:u,rootData:f=o}={}){let a=null,d=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.action===void 0){let p={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"action"},message:"must have required property 'action'"};a===null?a=[p]:a.push(p),d++}if(o.targetBranch===void 0){let p={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};a===null?a=[p]:a.push(p),d++}if(o.commit===void 0){let p={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"commit"},message:"must have required property 'commit'"};a===null?a=[p]:a.push(p),d++}for(let p in o)if(!(p==="action"||p==="commit"||p==="prUrl"||p==="remote"||p==="targetBranch")){let l={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[l]:a.push(l),d++}if(o.action!==void 0){let p=o.action;if(!(p==="local"||p==="push"||p==="pr")){let l={instancePath:s+"/action",schemaPath:"#/properties/action/enum",keyword:"enum",params:{allowedValues:t.properties.action.enum},message:"must be equal to one of the allowed values"};a===null?a=[l]:a.push(l),d++}}if(o.commit!==void 0){let p=o.commit;if(typeof p=="string"){if(!r.test(p)){let l={instancePath:s+"/commit",schemaPath:"#/properties/commit/pattern",keyword:"pattern",params:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},message:'must match pattern "^[0-9a-f]{40}(?:[0-9a-f]{24})?$"'};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/commit",schemaPath:"#/properties/commit/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}if(o.prUrl!==void 0){let p=o.prUrl;if(typeof p=="string"){if(n(p)<1){let l={instancePath:s+"/prUrl",schemaPath:"#/properties/prUrl/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/prUrl",schemaPath:"#/properties/prUrl/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}if(o.remote!==void 0){let p=o.remote;if(typeof p=="string"){if(n(p)<1){let l={instancePath:s+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}if(o.targetBranch!==void 0){let p=o.targetBranch;if(typeof p=="string"){if(n(p)<1){let l={instancePath:s+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}}else{let p={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),d++}return i.errors=a,d===0}return e.exports})(),SM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},autoTransition:{type:["boolean","null"]},baseRef:{type:["string","null"]},boundBranch:{type:["string","null"]},branchStatus:{enum:[null,"pending","handled"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},checkEpoch:{minimum:0,type:"integer"},classicMigration:{enum:[null,1]},classicProfile:{enum:[null,"full","hotfix","tweak"]},contextCompression:{enum:[null,"off","beta"]},createdAt:{type:["string","null"]},designDoc:{type:["string","null"]},directOverride:{type:["boolean","null"]},handoffContext:{type:["string","null"]},handoffHash:{anyOf:[{type:"null"},{pattern:"^[a-f0-9]{64}$",type:"string"}]},isolation:{enum:[null,"current","branch","worktree"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},plan:{type:["string","null"]},reviewMode:{enum:[null,"off","standard","thorough"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},verificationReport:{type:["string","null"]},verifiedAt:{type:["string","null"]},verifyFailures:{minimum:0,type:"integer"},verifyMode:{enum:[null,"light","full"]},verifyResult:{enum:["pending","pass","fail"]},workflow:{enum:["full"]}},required:["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],type:"object"},r=Object.prototype.hasOwnProperty,n=new RegExp("^[a-f0-9]{64}$","u");function i(o,{instancePath:s="",parentData:c,parentDataProperty:u,rootData:f=o}={}){let a=null,d=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.workflow===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[l]:a.push(l),d++}if(o.language===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[l]:a.push(l),d++}if(o.phase===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[l]:a.push(l),d++}if(o.contextCompression===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[l]:a.push(l),d++}if(o.buildMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[l]:a.push(l),d++}if(o.buildPause===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[l]:a.push(l),d++}if(o.subagentDispatch===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[l]:a.push(l),d++}if(o.tddMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[l]:a.push(l),d++}if(o.reviewMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[l]:a.push(l),d++}if(o.isolation===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[l]:a.push(l),d++}if(o.boundBranch===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[l]:a.push(l),d++}if(o.verifyMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[l]:a.push(l),d++}if(o.autoTransition===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[l]:a.push(l),d++}if(o.baseRef===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[l]:a.push(l),d++}if(o.designDoc===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[l]:a.push(l),d++}if(o.plan===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[l]:a.push(l),d++}if(o.verifyResult===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[l]:a.push(l),d++}if(o.verifyFailures===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[l]:a.push(l),d++}if(o.verificationReport===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[l]:a.push(l),d++}if(o.branchStatus===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[l]:a.push(l),d++}if(o.createdAt===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[l]:a.push(l),d++}if(o.verifiedAt===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[l]:a.push(l),d++}if(o.archiveConfirmation===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[l]:a.push(l),d++}if(o.archived===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[l]:a.push(l),d++}if(o.directOverride===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[l]:a.push(l),d++}if(o.handoffContext===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[l]:a.push(l),d++}if(o.handoffHash===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[l]:a.push(l),d++}if(o.classicProfile===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[l]:a.push(l),d++}if(o.classicMigration===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[l]:a.push(l),d++}for(let l in o)if(!r.call(t.properties,l)){let m={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(o.archiveConfirmation!==void 0){let l=o.archiveConfirmation;if(!(l===null||l==="pending"||l==="confirmed")){let m={instancePath:s+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.archived!==void 0&&typeof o.archived!="boolean"){let l={instancePath:s+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[l]:a.push(l),d++}if(o.autoTransition!==void 0){let l=o.autoTransition;if(typeof l!="boolean"&&l!==null){let m={instancePath:s+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(o.baseRef!==void 0){let l=o.baseRef;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.boundBranch!==void 0){let l=o.boundBranch;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.branchStatus!==void 0){let l=o.branchStatus;if(!(l===null||l==="pending"||l==="handled")){let m={instancePath:s+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.buildMode!==void 0){let l=o.buildMode;if(!(l===null||l==="subagent-driven-development"||l==="executing-plans"||l==="direct"||l==="autonomous")){let m={instancePath:s+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.buildPause!==void 0){let l=o.buildPause;if(!(l===null||l==="plan-ready")){let m={instancePath:s+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.checkEpoch!==void 0){let l=o.checkEpoch;if(!(typeof l=="number"&&!(l%1)&&!isNaN(l)&&isFinite(l))){let m={instancePath:s+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof l=="number"&&isFinite(l)&&(l<0||isNaN(l))){let m={instancePath:s+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(o.classicMigration!==void 0){let l=o.classicMigration;if(!(l===null||l===1)){let m={instancePath:s+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.classicProfile!==void 0){let l=o.classicProfile;if(!(l===null||l==="full"||l==="hotfix"||l==="tweak")){let m={instancePath:s+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.contextCompression!==void 0){let l=o.contextCompression;if(!(l===null||l==="off"||l==="beta")){let m={instancePath:s+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.createdAt!==void 0){let l=o.createdAt;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.designDoc!==void 0){let l=o.designDoc;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.directOverride!==void 0){let l=o.directOverride;if(typeof l!="boolean"&&l!==null){let m={instancePath:s+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(o.handoffContext!==void 0){let l=o.handoffContext;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.handoffHash!==void 0){let l=o.handoffHash,m=d,h=!1,g=d;if(l!==null){let w={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};a===null?a=[w]:a.push(w),d++}var p=g===d;if(h=h||p,!h){let w=d;if(typeof l=="string"){if(!n.test(l)){let b={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[b]:a.push(b),d++}}else{let b={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[b]:a.push(b),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(o.isolation!==void 0){let l=o.isolation;if(!(l===null||l==="current"||l==="branch"||l==="worktree")){let m={instancePath:s+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.language!==void 0){let l=o.language;if(!(l===null||l==="en"||l==="zh-CN")){let m={instancePath:s+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.phase!==void 0){let l=o.phase;if(!(l==="open"||l==="design"||l==="build"||l==="verify"||l==="archive")){let m={instancePath:s+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.plan!==void 0){let l=o.plan;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.reviewMode!==void 0){let l=o.reviewMode;if(!(l===null||l==="off"||l==="standard"||l==="thorough")){let m={instancePath:s+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.subagentDispatch!==void 0){let l=o.subagentDispatch;if(!(l===null||l==="confirmed")){let m={instancePath:s+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.tddMode!==void 0){let l=o.tddMode;if(!(l===null||l==="tdd"||l==="direct")){let m={instancePath:s+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.verificationReport!==void 0){let l=o.verificationReport;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.verifiedAt!==void 0){let l=o.verifiedAt;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.verifyFailures!==void 0){let l=o.verifyFailures;if(!(typeof l=="number"&&!(l%1)&&!isNaN(l)&&isFinite(l))){let m={instancePath:s+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof l=="number"&&isFinite(l)&&(l<0||isNaN(l))){let m={instancePath:s+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(o.verifyMode!==void 0){let l=o.verifyMode;if(!(l===null||l==="light"||l==="full")){let m={instancePath:s+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.verifyResult!==void 0){let l=o.verifyResult;if(!(l==="pending"||l==="pass"||l==="fail")){let m={instancePath:s+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.workflow!==void 0&&o.workflow!=="full"){let l={instancePath:s+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[l]:a.push(l),d++}return i.errors=a,d===0}return e.exports})(),CM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},autoTransition:{type:["boolean","null"]},baseRef:{type:["string","null"]},boundBranch:{type:["string","null"]},branchStatus:{enum:[null,"pending","handled"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},checkEpoch:{minimum:0,type:"integer"},classicMigration:{enum:[null,1]},classicProfile:{enum:[null,"full","hotfix","tweak"]},contextCompression:{enum:[null,"off","beta"]},createdAt:{type:["string","null"]},designDoc:{type:["string","null"]},directOverride:{type:["boolean","null"]},handoffContext:{type:["string","null"]},handoffHash:{anyOf:[{type:"null"},{pattern:"^[a-f0-9]{64}$",type:"string"}]},isolation:{enum:[null,"current","branch","worktree"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},plan:{type:["string","null"]},reviewMode:{enum:[null,"off","standard","thorough"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},verificationReport:{type:["string","null"]},verifiedAt:{type:["string","null"]},verifyFailures:{minimum:0,type:"integer"},verifyMode:{enum:[null,"light","full"]},verifyResult:{enum:["pending","pass","fail"]},workflow:{enum:["hotfix","full"]}},required:["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],type:"object"},r=Object.prototype.hasOwnProperty,n=new RegExp("^[a-f0-9]{64}$","u");function i(o,{instancePath:s="",parentData:c,parentDataProperty:u,rootData:f=o}={}){let a=null,d=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.workflow===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[l]:a.push(l),d++}if(o.language===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[l]:a.push(l),d++}if(o.phase===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[l]:a.push(l),d++}if(o.contextCompression===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[l]:a.push(l),d++}if(o.buildMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[l]:a.push(l),d++}if(o.buildPause===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[l]:a.push(l),d++}if(o.subagentDispatch===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[l]:a.push(l),d++}if(o.tddMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[l]:a.push(l),d++}if(o.reviewMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[l]:a.push(l),d++}if(o.isolation===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[l]:a.push(l),d++}if(o.boundBranch===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[l]:a.push(l),d++}if(o.verifyMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[l]:a.push(l),d++}if(o.autoTransition===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[l]:a.push(l),d++}if(o.baseRef===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[l]:a.push(l),d++}if(o.designDoc===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[l]:a.push(l),d++}if(o.plan===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[l]:a.push(l),d++}if(o.verifyResult===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[l]:a.push(l),d++}if(o.verifyFailures===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[l]:a.push(l),d++}if(o.verificationReport===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[l]:a.push(l),d++}if(o.branchStatus===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[l]:a.push(l),d++}if(o.createdAt===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[l]:a.push(l),d++}if(o.verifiedAt===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[l]:a.push(l),d++}if(o.archiveConfirmation===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[l]:a.push(l),d++}if(o.archived===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[l]:a.push(l),d++}if(o.directOverride===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[l]:a.push(l),d++}if(o.handoffContext===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[l]:a.push(l),d++}if(o.handoffHash===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[l]:a.push(l),d++}if(o.classicProfile===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[l]:a.push(l),d++}if(o.classicMigration===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[l]:a.push(l),d++}for(let l in o)if(!r.call(t.properties,l)){let m={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(o.archiveConfirmation!==void 0){let l=o.archiveConfirmation;if(!(l===null||l==="pending"||l==="confirmed")){let m={instancePath:s+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.archived!==void 0&&typeof o.archived!="boolean"){let l={instancePath:s+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[l]:a.push(l),d++}if(o.autoTransition!==void 0){let l=o.autoTransition;if(typeof l!="boolean"&&l!==null){let m={instancePath:s+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(o.baseRef!==void 0){let l=o.baseRef;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.boundBranch!==void 0){let l=o.boundBranch;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.branchStatus!==void 0){let l=o.branchStatus;if(!(l===null||l==="pending"||l==="handled")){let m={instancePath:s+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.buildMode!==void 0){let l=o.buildMode;if(!(l===null||l==="subagent-driven-development"||l==="executing-plans"||l==="direct"||l==="autonomous")){let m={instancePath:s+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.buildPause!==void 0){let l=o.buildPause;if(!(l===null||l==="plan-ready")){let m={instancePath:s+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.checkEpoch!==void 0){let l=o.checkEpoch;if(!(typeof l=="number"&&!(l%1)&&!isNaN(l)&&isFinite(l))){let m={instancePath:s+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof l=="number"&&isFinite(l)&&(l<0||isNaN(l))){let m={instancePath:s+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(o.classicMigration!==void 0){let l=o.classicMigration;if(!(l===null||l===1)){let m={instancePath:s+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.classicProfile!==void 0){let l=o.classicProfile;if(!(l===null||l==="full"||l==="hotfix"||l==="tweak")){let m={instancePath:s+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.contextCompression!==void 0){let l=o.contextCompression;if(!(l===null||l==="off"||l==="beta")){let m={instancePath:s+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.createdAt!==void 0){let l=o.createdAt;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.designDoc!==void 0){let l=o.designDoc;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.directOverride!==void 0){let l=o.directOverride;if(typeof l!="boolean"&&l!==null){let m={instancePath:s+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(o.handoffContext!==void 0){let l=o.handoffContext;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.handoffHash!==void 0){let l=o.handoffHash,m=d,h=!1,g=d;if(l!==null){let w={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};a===null?a=[w]:a.push(w),d++}var p=g===d;if(h=h||p,!h){let w=d;if(typeof l=="string"){if(!n.test(l)){let b={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[b]:a.push(b),d++}}else{let b={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[b]:a.push(b),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(o.isolation!==void 0){let l=o.isolation;if(!(l===null||l==="current"||l==="branch"||l==="worktree")){let m={instancePath:s+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.language!==void 0){let l=o.language;if(!(l===null||l==="en"||l==="zh-CN")){let m={instancePath:s+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.phase!==void 0){let l=o.phase;if(!(l==="open"||l==="design"||l==="build"||l==="verify"||l==="archive")){let m={instancePath:s+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.plan!==void 0){let l=o.plan;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.reviewMode!==void 0){let l=o.reviewMode;if(!(l===null||l==="off"||l==="standard"||l==="thorough")){let m={instancePath:s+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.subagentDispatch!==void 0){let l=o.subagentDispatch;if(!(l===null||l==="confirmed")){let m={instancePath:s+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.tddMode!==void 0){let l=o.tddMode;if(!(l===null||l==="tdd"||l==="direct")){let m={instancePath:s+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.verificationReport!==void 0){let l=o.verificationReport;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.verifiedAt!==void 0){let l=o.verifiedAt;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.verifyFailures!==void 0){let l=o.verifyFailures;if(!(typeof l=="number"&&!(l%1)&&!isNaN(l)&&isFinite(l))){let m={instancePath:s+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof l=="number"&&isFinite(l)&&(l<0||isNaN(l))){let m={instancePath:s+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(o.verifyMode!==void 0){let l=o.verifyMode;if(!(l===null||l==="light"||l==="full")){let m={instancePath:s+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.verifyResult!==void 0){let l=o.verifyResult;if(!(l==="pending"||l==="pass"||l==="fail")){let m={instancePath:s+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.workflow!==void 0){let l=o.workflow;if(!(l==="hotfix"||l==="full")){let m={instancePath:s+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}}else{let l={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[l]:a.push(l),d++}return i.errors=a,d===0}return e.exports})(),EM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},autoTransition:{type:["boolean","null"]},baseRef:{type:["string","null"]},boundBranch:{type:["string","null"]},branchStatus:{enum:[null,"pending","handled"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},checkEpoch:{minimum:0,type:"integer"},classicMigration:{enum:[null,1]},classicProfile:{enum:[null,"full","hotfix","tweak"]},contextCompression:{enum:[null,"off","beta"]},createdAt:{type:["string","null"]},designDoc:{type:["string","null"]},directOverride:{type:["boolean","null"]},handoffContext:{type:["string","null"]},handoffHash:{anyOf:[{type:"null"},{pattern:"^[a-f0-9]{64}$",type:"string"}]},isolation:{enum:[null,"current","branch","worktree"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},plan:{type:["string","null"]},reviewMode:{enum:[null,"off","standard","thorough"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},verificationReport:{type:["string","null"]},verifiedAt:{type:["string","null"]},verifyFailures:{minimum:0,type:"integer"},verifyMode:{enum:[null,"light","full"]},verifyResult:{enum:["pending","pass","fail"]},workflow:{enum:["tweak","full"]}},required:["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],type:"object"},r=Object.prototype.hasOwnProperty,n=new RegExp("^[a-f0-9]{64}$","u");function i(o,{instancePath:s="",parentData:c,parentDataProperty:u,rootData:f=o}={}){let a=null,d=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.workflow===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[l]:a.push(l),d++}if(o.language===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[l]:a.push(l),d++}if(o.phase===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[l]:a.push(l),d++}if(o.contextCompression===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[l]:a.push(l),d++}if(o.buildMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[l]:a.push(l),d++}if(o.buildPause===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[l]:a.push(l),d++}if(o.subagentDispatch===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[l]:a.push(l),d++}if(o.tddMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[l]:a.push(l),d++}if(o.reviewMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[l]:a.push(l),d++}if(o.isolation===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[l]:a.push(l),d++}if(o.boundBranch===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[l]:a.push(l),d++}if(o.verifyMode===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[l]:a.push(l),d++}if(o.autoTransition===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[l]:a.push(l),d++}if(o.baseRef===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[l]:a.push(l),d++}if(o.designDoc===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[l]:a.push(l),d++}if(o.plan===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[l]:a.push(l),d++}if(o.verifyResult===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[l]:a.push(l),d++}if(o.verifyFailures===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[l]:a.push(l),d++}if(o.verificationReport===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[l]:a.push(l),d++}if(o.branchStatus===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[l]:a.push(l),d++}if(o.createdAt===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[l]:a.push(l),d++}if(o.verifiedAt===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[l]:a.push(l),d++}if(o.archiveConfirmation===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[l]:a.push(l),d++}if(o.archived===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[l]:a.push(l),d++}if(o.directOverride===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[l]:a.push(l),d++}if(o.handoffContext===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[l]:a.push(l),d++}if(o.handoffHash===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[l]:a.push(l),d++}if(o.classicProfile===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[l]:a.push(l),d++}if(o.classicMigration===void 0){let l={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[l]:a.push(l),d++}for(let l in o)if(!r.call(t.properties,l)){let m={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(o.archiveConfirmation!==void 0){let l=o.archiveConfirmation;if(!(l===null||l==="pending"||l==="confirmed")){let m={instancePath:s+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.archived!==void 0&&typeof o.archived!="boolean"){let l={instancePath:s+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[l]:a.push(l),d++}if(o.autoTransition!==void 0){let l=o.autoTransition;if(typeof l!="boolean"&&l!==null){let m={instancePath:s+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(o.baseRef!==void 0){let l=o.baseRef;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.boundBranch!==void 0){let l=o.boundBranch;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.branchStatus!==void 0){let l=o.branchStatus;if(!(l===null||l==="pending"||l==="handled")){let m={instancePath:s+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.buildMode!==void 0){let l=o.buildMode;if(!(l===null||l==="subagent-driven-development"||l==="executing-plans"||l==="direct"||l==="autonomous")){let m={instancePath:s+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.buildPause!==void 0){let l=o.buildPause;if(!(l===null||l==="plan-ready")){let m={instancePath:s+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.checkEpoch!==void 0){let l=o.checkEpoch;if(!(typeof l=="number"&&!(l%1)&&!isNaN(l)&&isFinite(l))){let m={instancePath:s+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof l=="number"&&isFinite(l)&&(l<0||isNaN(l))){let m={instancePath:s+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(o.classicMigration!==void 0){let l=o.classicMigration;if(!(l===null||l===1)){let m={instancePath:s+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.classicProfile!==void 0){let l=o.classicProfile;if(!(l===null||l==="full"||l==="hotfix"||l==="tweak")){let m={instancePath:s+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.contextCompression!==void 0){let l=o.contextCompression;if(!(l===null||l==="off"||l==="beta")){let m={instancePath:s+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.createdAt!==void 0){let l=o.createdAt;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.designDoc!==void 0){let l=o.designDoc;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.directOverride!==void 0){let l=o.directOverride;if(typeof l!="boolean"&&l!==null){let m={instancePath:s+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};a===null?a=[m]:a.push(m),d++}}if(o.handoffContext!==void 0){let l=o.handoffContext;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.handoffHash!==void 0){let l=o.handoffHash,m=d,h=!1,g=d;if(l!==null){let w={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};a===null?a=[w]:a.push(w),d++}var p=g===d;if(h=h||p,!h){let w=d;if(typeof l=="string"){if(!n.test(l)){let b={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[b]:a.push(b),d++}}else{let b={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[b]:a.push(b),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(o.isolation!==void 0){let l=o.isolation;if(!(l===null||l==="current"||l==="branch"||l==="worktree")){let m={instancePath:s+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.language!==void 0){let l=o.language;if(!(l===null||l==="en"||l==="zh-CN")){let m={instancePath:s+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.phase!==void 0){let l=o.phase;if(!(l==="open"||l==="design"||l==="build"||l==="verify"||l==="archive")){let m={instancePath:s+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.plan!==void 0){let l=o.plan;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.reviewMode!==void 0){let l=o.reviewMode;if(!(l===null||l==="off"||l==="standard"||l==="thorough")){let m={instancePath:s+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.subagentDispatch!==void 0){let l=o.subagentDispatch;if(!(l===null||l==="confirmed")){let m={instancePath:s+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.tddMode!==void 0){let l=o.tddMode;if(!(l===null||l==="tdd"||l==="direct")){let m={instancePath:s+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.verificationReport!==void 0){let l=o.verificationReport;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.verifiedAt!==void 0){let l=o.verifiedAt;if(typeof l!="string"&&l!==null){let m={instancePath:s+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};a===null?a=[m]:a.push(m),d++}}if(o.verifyFailures!==void 0){let l=o.verifyFailures;if(!(typeof l=="number"&&!(l%1)&&!isNaN(l)&&isFinite(l))){let m={instancePath:s+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof l=="number"&&isFinite(l)&&(l<0||isNaN(l))){let m={instancePath:s+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(o.verifyMode!==void 0){let l=o.verifyMode;if(!(l===null||l==="light"||l==="full")){let m={instancePath:s+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.verifyResult!==void 0){let l=o.verifyResult;if(!(l==="pending"||l==="pass"||l==="fail")){let m={instancePath:s+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}if(o.workflow!==void 0){let l=o.workflow;if(!(l==="tweak"||l==="full")){let m={instancePath:s+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};a===null?a=[m]:a.push(m),d++}}}else{let l={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[l]:a.push(l),d++}return i.errors=a,d===0}return e.exports})(),_M=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{archiveDirectory:{minLength:1,type:"string"}},required:["archiveDirectory"],type:"object"},r=Ye.default.default??Ye.default;function n(i,{instancePath:o="",parentData:s,parentDataProperty:c,rootData:u=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.archiveDirectory===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveDirectory"},message:"must have required property 'archiveDirectory'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(d!=="archiveDirectory"){let p={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.archiveDirectory!==void 0){let d=i.archiveDirectory;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/archiveDirectory",schemaPath:"#/properties/archiveDirectory/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/archiveDirectory",schemaPath:"#/properties/archiveDirectory/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),AM=(()=>{let e={exports:{}};e.exports=o,e.exports.default=o;let t={additionalProperties:!1,properties:{baseCommit:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$",type:"string"},deliveryAction:{enum:["local","push","pr"]},deliveryPaths:{items:{minLength:1,type:"string"},type:"array"},prBaseBranch:{minLength:1,type:"string"},remote:{minLength:1,type:"string"},remoteIdentity:{pattern:"^[0-9a-f]{64}$",type:"string"},targetBranch:{minLength:1,type:"string"},verifiedBranch:{minLength:1,type:"string"}},required:["deliveryAction","targetBranch","verifiedBranch","baseCommit"],type:"object"},r=new RegExp("^[0-9a-f]{40}(?:[0-9a-f]{24})?$","u"),n=new RegExp("^[0-9a-f]{64}$","u"),i=Ye.default.default??Ye.default;function o(s,{instancePath:c="",parentData:u,parentDataProperty:f,rootData:a=s}={}){let d=null,p=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.deliveryAction===void 0){let l={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"deliveryAction"},message:"must have required property 'deliveryAction'"};d===null?d=[l]:d.push(l),p++}if(s.targetBranch===void 0){let l={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};d===null?d=[l]:d.push(l),p++}if(s.verifiedBranch===void 0){let l={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedBranch"},message:"must have required property 'verifiedBranch'"};d===null?d=[l]:d.push(l),p++}if(s.baseCommit===void 0){let l={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseCommit"},message:"must have required property 'baseCommit'"};d===null?d=[l]:d.push(l),p++}for(let l in s)if(!(l==="baseCommit"||l==="deliveryAction"||l==="deliveryPaths"||l==="prBaseBranch"||l==="remote"||l==="remoteIdentity"||l==="targetBranch"||l==="verifiedBranch")){let m={instancePath:c,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};d===null?d=[m]:d.push(m),p++}if(s.baseCommit!==void 0){let l=s.baseCommit;if(typeof l=="string"){if(!r.test(l)){let m={instancePath:c+"/baseCommit",schemaPath:"#/properties/baseCommit/pattern",keyword:"pattern",params:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},message:'must match pattern "^[0-9a-f]{40}(?:[0-9a-f]{24})?$"'};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/baseCommit",schemaPath:"#/properties/baseCommit/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(s.deliveryAction!==void 0){let l=s.deliveryAction;if(!(l==="local"||l==="push"||l==="pr")){let m={instancePath:c+"/deliveryAction",schemaPath:"#/properties/deliveryAction/enum",keyword:"enum",params:{allowedValues:t.properties.deliveryAction.enum},message:"must be equal to one of the allowed values"};d===null?d=[m]:d.push(m),p++}}if(s.deliveryPaths!==void 0){let l=s.deliveryPaths;if(Array.isArray(l)){let m=l.length;for(let h=0;h<m;h++){let g=l[h];if(typeof g=="string"){if(i(g)<1){let w={instancePath:c+"/deliveryPaths/"+h,schemaPath:"#/properties/deliveryPaths/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[w]:d.push(w),p++}}else{let w={instancePath:c+"/deliveryPaths/"+h,schemaPath:"#/properties/deliveryPaths/items/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[w]:d.push(w),p++}}}else{let m={instancePath:c+"/deliveryPaths",schemaPath:"#/properties/deliveryPaths/type",keyword:"type",params:{type:"array"},message:"must be array"};d===null?d=[m]:d.push(m),p++}}if(s.prBaseBranch!==void 0){let l=s.prBaseBranch;if(typeof l=="string"){if(i(l)<1){let m={instancePath:c+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(s.remote!==void 0){let l=s.remote;if(typeof l=="string"){if(i(l)<1){let m={instancePath:c+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(s.remoteIdentity!==void 0){let l=s.remoteIdentity;if(typeof l=="string"){if(!n.test(l)){let m={instancePath:c+"/remoteIdentity",schemaPath:"#/properties/remoteIdentity/pattern",keyword:"pattern",params:{pattern:"^[0-9a-f]{64}$"},message:'must match pattern "^[0-9a-f]{64}$"'};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/remoteIdentity",schemaPath:"#/properties/remoteIdentity/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(s.targetBranch!==void 0){let l=s.targetBranch;if(typeof l=="string"){if(i(l)<1){let m={instancePath:c+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}if(s.verifiedBranch!==void 0){let l=s.verifiedBranch;if(typeof l=="string"){if(i(l)<1){let m={instancePath:c+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),p++}}else{let m={instancePath:c+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),p++}}}else{let l={instancePath:c,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),p++}return o.errors=d,p===0}return e.exports})(),xM=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={additionalProperties:!1,properties:{boundBranch:{type:["string","null"]},buildMode:{enum:["subagent-driven-development","executing-plans","direct","autonomous"]},directOverride:{type:"boolean"},isolation:{enum:["current","branch","worktree"]},reviewMode:{enum:["off","standard","thorough"]},subagentDispatch:{enum:["confirmed",null]},tddMode:{enum:["tdd","direct"]}},required:["buildMode","tddMode","reviewMode","isolation"],type:"object"};function r(n,{instancePath:i="",parentData:o,parentDataProperty:s,rootData:c=n}={}){let u=null,f=0;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.buildMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};u===null?u=[a]:u.push(a),f++}if(n.tddMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};u===null?u=[a]:u.push(a),f++}if(n.reviewMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};u===null?u=[a]:u.push(a),f++}if(n.isolation===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};u===null?u=[a]:u.push(a),f++}for(let a in n)if(!(a==="boundBranch"||a==="buildMode"||a==="directOverride"||a==="isolation"||a==="reviewMode"||a==="subagentDispatch"||a==="tddMode")){let d={instancePath:i,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:a},message:"must NOT have additional properties"};u===null?u=[d]:u.push(d),f++}if(n.boundBranch!==void 0){let a=n.boundBranch;if(typeof a!="string"&&a!==null){let d={instancePath:i+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};u===null?u=[d]:u.push(d),f++}}if(n.buildMode!==void 0){let a=n.buildMode;if(!(a==="subagent-driven-development"||a==="executing-plans"||a==="direct"||a==="autonomous")){let d={instancePath:i+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};u===null?u=[d]:u.push(d),f++}}if(n.directOverride!==void 0&&typeof n.directOverride!="boolean"){let a={instancePath:i+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};u===null?u=[a]:u.push(a),f++}if(n.isolation!==void 0){let a=n.isolation;if(!(a==="current"||a==="branch"||a==="worktree")){let d={instancePath:i+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};u===null?u=[d]:u.push(d),f++}}if(n.reviewMode!==void 0){let a=n.reviewMode;if(!(a==="off"||a==="standard"||a==="thorough")){let d={instancePath:i+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};u===null?u=[d]:u.push(d),f++}}if(n.subagentDispatch!==void 0){let a=n.subagentDispatch;if(!(a==="confirmed"||a===null)){let d={instancePath:i+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};u===null?u=[d]:u.push(d),f++}}if(n.tddMode!==void 0){let a=n.tddMode;if(!(a==="tdd"||a==="direct")){let d={instancePath:i+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};u===null?u=[d]:u.push(d),f++}}}else{let a={instancePath:i,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};u===null?u=[a]:u.push(a),f++}return r.errors=u,f===0}return e.exports})(),PM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={additionalProperties:!1,properties:{checks:{items:{additionalProperties:!1,properties:{name:{minLength:1,type:"string"},note:{minLength:1,type:"string"},result:{enum:["passed","failed","not-run"]}},required:["name","result"],type:"object"},type:"array"},checksReason:{minLength:1,type:"string"},event:{enum:["build-complete","escalation-requested"]},proposal:{minLength:1,type:"string"},requirementsEvidence:{additionalProperties:!1,properties:{contentHash:{pattern:"^[a-f0-9]{64}$",type:"string"},ref:{minLength:1,type:"string"}},required:["ref","contentHash"],type:"object"}},required:["event"],type:"object"},r=Ye.default.default??Ye.default,n=new RegExp("^[a-f0-9]{64}$","u");function i(o,{instancePath:s="",parentData:c,parentDataProperty:u,rootData:f=o}={}){let a=null,d=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.event===void 0){let p={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};a===null?a=[p]:a.push(p),d++}for(let p in o)if(!(p==="checks"||p==="checksReason"||p==="event"||p==="proposal"||p==="requirementsEvidence")){let l={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[l]:a.push(l),d++}if(o.checks!==void 0){let p=o.checks;if(Array.isArray(p)){let l=p.length;for(let m=0;m<l;m++){let h=p[m];if(h&&typeof h=="object"&&!Array.isArray(h)){if(h.name===void 0){let g={instancePath:s+"/checks/"+m,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};a===null?a=[g]:a.push(g),d++}if(h.result===void 0){let g={instancePath:s+"/checks/"+m,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};a===null?a=[g]:a.push(g),d++}for(let g in h)if(!(g==="name"||g==="note"||g==="result")){let w={instancePath:s+"/checks/"+m,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};a===null?a=[w]:a.push(w),d++}if(h.name!==void 0){let g=h.name;if(typeof g=="string"){if(r(g)<1){let w={instancePath:s+"/checks/"+m+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[w]:a.push(w),d++}}else{let w={instancePath:s+"/checks/"+m+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[w]:a.push(w),d++}}if(h.note!==void 0){let g=h.note;if(typeof g=="string"){if(r(g)<1){let w={instancePath:s+"/checks/"+m+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[w]:a.push(w),d++}}else{let w={instancePath:s+"/checks/"+m+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[w]:a.push(w),d++}}if(h.result!==void 0){let g=h.result;if(!(g==="passed"||g==="failed"||g==="not-run")){let w={instancePath:s+"/checks/"+m+"/result",schemaPath:"#/properties/checks/items/properties/result/enum",keyword:"enum",params:{allowedValues:t.properties.checks.items.properties.result.enum},message:"must be equal to one of the allowed values"};a===null?a=[w]:a.push(w),d++}}}else{let g={instancePath:s+"/checks/"+m,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[g]:a.push(g),d++}}}else{let l={instancePath:s+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};a===null?a=[l]:a.push(l),d++}}if(o.checksReason!==void 0){let p=o.checksReason;if(typeof p=="string"){if(r(p)<1){let l={instancePath:s+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}if(o.event!==void 0){let p=o.event;if(!(p==="build-complete"||p==="escalation-requested")){let l={instancePath:s+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};a===null?a=[l]:a.push(l),d++}}if(o.proposal!==void 0){let p=o.proposal;if(typeof p=="string"){if(r(p)<1){let l={instancePath:s+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}if(o.requirementsEvidence!==void 0){let p=o.requirementsEvidence;if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.ref===void 0){let l={instancePath:s+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"ref"},message:"must have required property 'ref'"};a===null?a=[l]:a.push(l),d++}if(p.contentHash===void 0){let l={instancePath:s+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};a===null?a=[l]:a.push(l),d++}for(let l in p)if(!(l==="contentHash"||l==="ref")){let m={instancePath:s+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(p.contentHash!==void 0){let l=p.contentHash;if(typeof l=="string"){if(!n.test(l)){let m={instancePath:s+"/requirementsEvidence/contentHash",schemaPath:"#/properties/requirementsEvidence/properties/contentHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[m]:a.push(m),d++}}else{let m={instancePath:s+"/requirementsEvidence/contentHash",schemaPath:"#/properties/requirementsEvidence/properties/contentHash/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[m]:a.push(m),d++}}if(p.ref!==void 0){let l=p.ref;if(typeof l=="string"){if(r(l)<1){let m={instancePath:s+"/requirementsEvidence/ref",schemaPath:"#/properties/requirementsEvidence/properties/ref/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[m]:a.push(m),d++}}else{let m={instancePath:s+"/requirementsEvidence/ref",schemaPath:"#/properties/requirementsEvidence/properties/ref/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[m]:a.push(m),d++}}}else{let l={instancePath:s+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[l]:a.push(l),d++}}}else{let p={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),d++}return i.errors=a,d===0}return e.exports})(),IM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{checks:{items:{additionalProperties:!1,properties:{name:{minLength:1,type:"string"},note:{minLength:1,type:"string"},result:{enum:["passed","failed","not-run"]}},required:["name","result"],type:"object"},type:"array"},checksReason:{minLength:1,type:"string"},event:{enum:["verification-ready","verify-fail"]},reason:{minLength:1,type:"string"},verificationReport:{minLength:1,type:"string"}},required:["event"],type:"object"},r=Ye.default.default??Ye.default;function n(i,{instancePath:o="",parentData:s,parentDataProperty:c,rootData:u=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(!(d==="checks"||d==="checksReason"||d==="event"||d==="reason"||d==="verificationReport")){let p={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.checks!==void 0){let d=i.checks;if(Array.isArray(d)){let p=d.length;for(let l=0;l<p;l++){let m=d[l];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};f===null?f=[h]:f.push(h),a++}if(m.result===void 0){let h={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};f===null?f=[h]:f.push(h),a++}for(let h in m)if(!(h==="name"||h==="note"||h==="result")){let g={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:h},message:"must NOT have additional properties"};f===null?f=[g]:f.push(g),a++}if(m.name!==void 0){let h=m.name;if(typeof h=="string"){if(r(h)<1){let g={instancePath:o+"/checks/"+l+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:o+"/checks/"+l+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.note!==void 0){let h=m.note;if(typeof h=="string"){if(r(h)<1){let g={instancePath:o+"/checks/"+l+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:o+"/checks/"+l+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.result!==void 0){let h=m.result;if(!(h==="passed"||h==="failed"||h==="not-run")){let g={instancePath:o+"/checks/"+l+"/result",schemaPath:"#/properties/checks/items/properties/result/enum",keyword:"enum",params:{allowedValues:t.properties.checks.items.properties.result.enum},message:"must be equal to one of the allowed values"};f===null?f=[g]:f.push(g),a++}}}else{let h={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[h]:f.push(h),a++}}}else{let p={instancePath:o+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};f===null?f=[p]:f.push(p),a++}}if(i.checksReason!==void 0){let d=i.checksReason;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.event!==void 0){let d=i.event;if(!(d==="verification-ready"||d==="verify-fail")){let p={instancePath:o+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};f===null?f=[p]:f.push(p),a++}}if(i.reason!==void 0){let d=i.reason;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/reason",schemaPath:"#/properties/reason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/reason",schemaPath:"#/properties/reason/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.verificationReport!==void 0){let d=i.verificationReport;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/verificationReport",schemaPath:"#/properties/verificationReport/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),OM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{contentHash:{pattern:"^[a-f0-9]{64}$",type:"string"}},required:["contentHash"],type:"object"},r=new RegExp("^[a-f0-9]{64}$","u");function n(i,{instancePath:o="",parentData:s,parentDataProperty:c,rootData:u=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.contentHash===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(d!=="contentHash"){let p={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.contentHash!==void 0){let d=i.contentHash;if(typeof d=="string"){if(!r.test(d)){let p={instancePath:o+"/contentHash",schemaPath:"#/properties/contentHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/contentHash",schemaPath:"#/properties/contentHash/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),NM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={additionalProperties:!1,properties:{deliveryPaths:{items:{minLength:1,type:"string"},type:"array"},prBaseBranch:{minLength:1,type:"string"},remote:{minLength:1,type:"string"},summary:{minLength:1,type:"string"},targetBranch:{minLength:1,type:"string"}},required:["targetBranch","summary"],type:"object"},r=Ye.default.default??Ye.default;function n(i,{instancePath:o="",parentData:s,parentDataProperty:c,rootData:u=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.targetBranch===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};f===null?f=[d]:f.push(d),a++}if(i.summary===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"summary"},message:"must have required property 'summary'"};f===null?f=[d]:f.push(d),a++}for(let d in i)if(!(d==="deliveryPaths"||d==="prBaseBranch"||d==="remote"||d==="summary"||d==="targetBranch")){let p={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.deliveryPaths!==void 0){let d=i.deliveryPaths;if(Array.isArray(d)){let p=d.length;for(let l=0;l<p;l++){let m=d[l];if(typeof m=="string"){if(r(m)<1){let h={instancePath:o+"/deliveryPaths/"+l,schemaPath:"#/properties/deliveryPaths/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[h]:f.push(h),a++}}else{let h={instancePath:o+"/deliveryPaths/"+l,schemaPath:"#/properties/deliveryPaths/items/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[h]:f.push(h),a++}}}else{let p={instancePath:o+"/deliveryPaths",schemaPath:"#/properties/deliveryPaths/type",keyword:"type",params:{type:"array"},message:"must be array"};f===null?f=[p]:f.push(p),a++}}if(i.prBaseBranch!==void 0){let d=i.prBaseBranch;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.remote!==void 0){let d=i.remote;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.summary!==void 0){let d=i.summary;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/summary",schemaPath:"#/properties/summary/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/summary",schemaPath:"#/properties/summary/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.targetBranch!==void 0){let d=i.targetBranch;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),TM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={properties:{buildPause:{enum:["plan-ready"]},plan:{minLength:1,type:"string"}},required:["plan"],type:"object"},r=Ye.default.default??Ye.default;function n(i,{instancePath:o="",parentData:s,parentDataProperty:c,rootData:u=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.plan===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};f===null?f=[d]:f.push(d),a++}if(i.buildPause!==void 0&&i.buildPause!=="plan-ready"){let d={instancePath:o+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};f===null?f=[d]:f.push(d),a++}if(i.plan!==void 0){let d=i.plan;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/plan",schemaPath:"#/properties/plan/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),$M=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={properties:{checks:{items:{additionalProperties:!1,properties:{name:{minLength:1,type:"string"},note:{minLength:1,type:"string"},result:{enum:["passed","failed","not-run"]}},required:["name","result"],type:"object"},type:"array"},checksReason:{minLength:1,type:"string"},event:{enum:["build-complete"]}},required:["event"],type:"object"},r=Ye.default.default??Ye.default;function n(i,{instancePath:o="",parentData:s,parentDataProperty:c,rootData:u=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};f===null?f=[d]:f.push(d),a++}if(i.checks!==void 0){let d=i.checks;if(Array.isArray(d)){let p=d.length;for(let l=0;l<p;l++){let m=d[l];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};f===null?f=[h]:f.push(h),a++}if(m.result===void 0){let h={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};f===null?f=[h]:f.push(h),a++}for(let h in m)if(!(h==="name"||h==="note"||h==="result")){let g={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:h},message:"must NOT have additional properties"};f===null?f=[g]:f.push(g),a++}if(m.name!==void 0){let h=m.name;if(typeof h=="string"){if(r(h)<1){let g={instancePath:o+"/checks/"+l+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:o+"/checks/"+l+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.note!==void 0){let h=m.note;if(typeof h=="string"){if(r(h)<1){let g={instancePath:o+"/checks/"+l+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[g]:f.push(g),a++}}else{let g={instancePath:o+"/checks/"+l+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[g]:f.push(g),a++}}if(m.result!==void 0){let h=m.result;if(!(h==="passed"||h==="failed"||h==="not-run")){let g={instancePath:o+"/checks/"+l+"/result",schemaPath:"#/properties/checks/items/properties/result/enum",keyword:"enum",params:{allowedValues:t.properties.checks.items.properties.result.enum},message:"must be equal to one of the allowed values"};f===null?f=[g]:f.push(g),a++}}}else{let h={instancePath:o+"/checks/"+l,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[h]:f.push(h),a++}}}else{let p={instancePath:o+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};f===null?f=[p]:f.push(p),a++}}if(i.checksReason!==void 0){let d=i.checksReason;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}if(i.event!==void 0&&i.event!=="build-complete"){let d={instancePath:o+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};f===null?f=[d]:f.push(d),a++}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),jM=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;let t={properties:{designDoc:{minLength:1,type:"string"}},required:["designDoc"],type:"object"},r=Ye.default.default??Ye.default;function n(i,{instancePath:o="",parentData:s,parentDataProperty:c,rootData:u=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.designDoc===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};f===null?f=[d]:f.push(d),a++}if(i.designDoc!==void 0){let d=i.designDoc;if(typeof d=="string"){if(r(d)<1){let p={instancePath:o+"/designDoc",schemaPath:"#/properties/designDoc/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};f===null?f=[p]:f.push(p),a++}}else{let p={instancePath:o+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:"string"},message:"must be string"};f===null?f=[p]:f.push(p),a++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return n.errors=f,a===0}return e.exports})(),DM=(()=>{let e={exports:{}};e.exports=i,e.exports.default=i;let t={properties:{handoffContext:{minLength:1,type:"string"},handoffHash:{pattern:"^[a-f0-9]{64}$",type:"string"},proposal:{minLength:1,type:"string"}},required:["proposal"],type:"object"},r=Ye.default.default??Ye.default,n=new RegExp("^[a-f0-9]{64}$","u");function i(o,{instancePath:s="",parentData:c,parentDataProperty:u,rootData:f=o}={}){let a=null,d=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.proposal===void 0){let p={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"proposal"},message:"must have required property 'proposal'"};a===null?a=[p]:a.push(p),d++}if(o.handoffContext!==void 0){let p=o.handoffContext;if(typeof p=="string"){if(r(p)<1){let l={instancePath:s+"/handoffContext",schemaPath:"#/properties/handoffContext/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}if(o.handoffHash!==void 0){let p=o.handoffHash;if(typeof p=="string"){if(!n.test(p)){let l={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/handoffHash",schemaPath:"#/properties/handoffHash/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}if(o.proposal!==void 0){let p=o.proposal;if(typeof p=="string"){if(r(p)<1){let l={instancePath:s+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[l]:a.push(l),d++}}else{let l={instancePath:s+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[l]:a.push(l),d++}}}else{let p={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),d++}return i.errors=a,d===0}return e.exports})(),yE=new Map([['{"additionalProperties":false,"properties":{"action":{"enum":["local","push","pr"]},"commit":{"pattern":"^[0-9a-f]{40}(?:[0-9a-f]{24})?$","type":"string"},"prUrl":{"minLength":1,"type":"string"},"remote":{"minLength":1,"type":"string"},"targetBranch":{"minLength":1,"type":"string"}},"required":["action","targetBranch","commit"],"type":"object"}',RM],['{"additionalProperties":false,"properties":{"archiveConfirmation":{"enum":[null,"pending","confirmed"]},"archived":{"type":"boolean"},"autoTransition":{"type":["boolean","null"]},"baseRef":{"type":["string","null"]},"boundBranch":{"type":["string","null"]},"branchStatus":{"enum":[null,"pending","handled"]},"buildMode":{"enum":[null,"subagent-driven-development","executing-plans","direct","autonomous"]},"buildPause":{"enum":[null,"plan-ready"]},"checkEpoch":{"minimum":0,"type":"integer"},"classicMigration":{"enum":[null,1]},"classicProfile":{"enum":[null,"full","hotfix","tweak"]},"contextCompression":{"enum":[null,"off","beta"]},"createdAt":{"type":["string","null"]},"designDoc":{"type":["string","null"]},"directOverride":{"type":["boolean","null"]},"handoffContext":{"type":["string","null"]},"handoffHash":{"anyOf":[{"type":"null"},{"pattern":"^[a-f0-9]{64}$","type":"string"}]},"isolation":{"enum":[null,"current","branch","worktree"]},"language":{"enum":[null,"en","zh-CN"]},"phase":{"enum":["open","design","build","verify","archive"]},"plan":{"type":["string","null"]},"reviewMode":{"enum":[null,"off","standard","thorough"]},"subagentDispatch":{"enum":[null,"confirmed"]},"tddMode":{"enum":[null,"tdd","direct"]},"verificationReport":{"type":["string","null"]},"verifiedAt":{"type":["string","null"]},"verifyFailures":{"minimum":0,"type":"integer"},"verifyMode":{"enum":[null,"light","full"]},"verifyResult":{"enum":["pending","pass","fail"]},"workflow":{"enum":["full"]}},"required":["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],"type":"object"}',SM],['{"additionalProperties":false,"properties":{"archiveConfirmation":{"enum":[null,"pending","confirmed"]},"archived":{"type":"boolean"},"autoTransition":{"type":["boolean","null"]},"baseRef":{"type":["string","null"]},"boundBranch":{"type":["string","null"]},"branchStatus":{"enum":[null,"pending","handled"]},"buildMode":{"enum":[null,"subagent-driven-development","executing-plans","direct","autonomous"]},"buildPause":{"enum":[null,"plan-ready"]},"checkEpoch":{"minimum":0,"type":"integer"},"classicMigration":{"enum":[null,1]},"classicProfile":{"enum":[null,"full","hotfix","tweak"]},"contextCompression":{"enum":[null,"off","beta"]},"createdAt":{"type":["string","null"]},"designDoc":{"type":["string","null"]},"directOverride":{"type":["boolean","null"]},"handoffContext":{"type":["string","null"]},"handoffHash":{"anyOf":[{"type":"null"},{"pattern":"^[a-f0-9]{64}$","type":"string"}]},"isolation":{"enum":[null,"current","branch","worktree"]},"language":{"enum":[null,"en","zh-CN"]},"phase":{"enum":["open","design","build","verify","archive"]},"plan":{"type":["string","null"]},"reviewMode":{"enum":[null,"off","standard","thorough"]},"subagentDispatch":{"enum":[null,"confirmed"]},"tddMode":{"enum":[null,"tdd","direct"]},"verificationReport":{"type":["string","null"]},"verifiedAt":{"type":["string","null"]},"verifyFailures":{"minimum":0,"type":"integer"},"verifyMode":{"enum":[null,"light","full"]},"verifyResult":{"enum":["pending","pass","fail"]},"workflow":{"enum":["hotfix","full"]}},"required":["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],"type":"object"}',CM],['{"additionalProperties":false,"properties":{"archiveConfirmation":{"enum":[null,"pending","confirmed"]},"archived":{"type":"boolean"},"autoTransition":{"type":["boolean","null"]},"baseRef":{"type":["string","null"]},"boundBranch":{"type":["string","null"]},"branchStatus":{"enum":[null,"pending","handled"]},"buildMode":{"enum":[null,"subagent-driven-development","executing-plans","direct","autonomous"]},"buildPause":{"enum":[null,"plan-ready"]},"checkEpoch":{"minimum":0,"type":"integer"},"classicMigration":{"enum":[null,1]},"classicProfile":{"enum":[null,"full","hotfix","tweak"]},"contextCompression":{"enum":[null,"off","beta"]},"createdAt":{"type":["string","null"]},"designDoc":{"type":["string","null"]},"directOverride":{"type":["boolean","null"]},"handoffContext":{"type":["string","null"]},"handoffHash":{"anyOf":[{"type":"null"},{"pattern":"^[a-f0-9]{64}$","type":"string"}]},"isolation":{"enum":[null,"current","branch","worktree"]},"language":{"enum":[null,"en","zh-CN"]},"phase":{"enum":["open","design","build","verify","archive"]},"plan":{"type":["string","null"]},"reviewMode":{"enum":[null,"off","standard","thorough"]},"subagentDispatch":{"enum":[null,"confirmed"]},"tddMode":{"enum":[null,"tdd","direct"]},"verificationReport":{"type":["string","null"]},"verifiedAt":{"type":["string","null"]},"verifyFailures":{"minimum":0,"type":"integer"},"verifyMode":{"enum":[null,"light","full"]},"verifyResult":{"enum":["pending","pass","fail"]},"workflow":{"enum":["tweak","full"]}},"required":["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],"type":"object"}',EM],['{"additionalProperties":false,"properties":{"archiveDirectory":{"minLength":1,"type":"string"}},"required":["archiveDirectory"],"type":"object"}',_M],['{"additionalProperties":false,"properties":{"baseCommit":{"pattern":"^[0-9a-f]{40}(?:[0-9a-f]{24})?$","type":"string"},"deliveryAction":{"enum":["local","push","pr"]},"deliveryPaths":{"items":{"minLength":1,"type":"string"},"type":"array"},"prBaseBranch":{"minLength":1,"type":"string"},"remote":{"minLength":1,"type":"string"},"remoteIdentity":{"pattern":"^[0-9a-f]{64}$","type":"string"},"targetBranch":{"minLength":1,"type":"string"},"verifiedBranch":{"minLength":1,"type":"string"}},"required":["deliveryAction","targetBranch","verifiedBranch","baseCommit"],"type":"object"}',AM],['{"additionalProperties":false,"properties":{"boundBranch":{"type":["string","null"]},"buildMode":{"enum":["subagent-driven-development","executing-plans","direct","autonomous"]},"directOverride":{"type":"boolean"},"isolation":{"enum":["current","branch","worktree"]},"reviewMode":{"enum":["off","standard","thorough"]},"subagentDispatch":{"enum":["confirmed",null]},"tddMode":{"enum":["tdd","direct"]}},"required":["buildMode","tddMode","reviewMode","isolation"],"type":"object"}',xM],['{"additionalProperties":false,"properties":{"checks":{"items":{"additionalProperties":false,"properties":{"name":{"minLength":1,"type":"string"},"note":{"minLength":1,"type":"string"},"result":{"enum":["passed","failed","not-run"]}},"required":["name","result"],"type":"object"},"type":"array"},"checksReason":{"minLength":1,"type":"string"},"event":{"enum":["build-complete","escalation-requested"]},"proposal":{"minLength":1,"type":"string"},"requirementsEvidence":{"additionalProperties":false,"properties":{"contentHash":{"pattern":"^[a-f0-9]{64}$","type":"string"},"ref":{"minLength":1,"type":"string"}},"required":["ref","contentHash"],"type":"object"}},"required":["event"],"type":"object"}',PM],['{"additionalProperties":false,"properties":{"checks":{"items":{"additionalProperties":false,"properties":{"name":{"minLength":1,"type":"string"},"note":{"minLength":1,"type":"string"},"result":{"enum":["passed","failed","not-run"]}},"required":["name","result"],"type":"object"},"type":"array"},"checksReason":{"minLength":1,"type":"string"},"event":{"enum":["verification-ready","verify-fail"]},"reason":{"minLength":1,"type":"string"},"verificationReport":{"minLength":1,"type":"string"}},"required":["event"],"type":"object"}',IM],['{"additionalProperties":false,"properties":{"contentHash":{"pattern":"^[a-f0-9]{64}$","type":"string"}},"required":["contentHash"],"type":"object"}',OM],['{"additionalProperties":false,"properties":{"deliveryPaths":{"items":{"minLength":1,"type":"string"},"type":"array"},"prBaseBranch":{"minLength":1,"type":"string"},"remote":{"minLength":1,"type":"string"},"summary":{"minLength":1,"type":"string"},"targetBranch":{"minLength":1,"type":"string"}},"required":["targetBranch","summary"],"type":"object"}',NM],['{"properties":{"buildPause":{"enum":["plan-ready"]},"plan":{"minLength":1,"type":"string"}},"required":["plan"],"type":"object"}',TM],['{"properties":{"checks":{"items":{"additionalProperties":false,"properties":{"name":{"minLength":1,"type":"string"},"note":{"minLength":1,"type":"string"},"result":{"enum":["passed","failed","not-run"]}},"required":["name","result"],"type":"object"},"type":"array"},"checksReason":{"minLength":1,"type":"string"},"event":{"enum":["build-complete"]}},"required":["event"],"type":"object"}',$M],['{"properties":{"designDoc":{"minLength":1,"type":"string"}},"required":["designDoc"],"type":"object"}',jM],['{"properties":{"handoffContext":{"minLength":1,"type":"string"},"handoffHash":{"pattern":"^[a-f0-9]{64}$","type":"string"},"proposal":{"minLength":1,"type":"string"}},"required":["proposal"],"type":"object"}',DM]]);var qM=128,vE=1024*1024,qi=new Map,Yh=0;function Wu(e){let t=rn(e),r=qi.get(t);if(r)return qi.delete(t),qi.set(t,r),r;let i=yE.get(t)??new Xh.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),o={validate:i,errorsText:()=>Xh.Ajv.prototype.errorsText(i.errors)};if(t.length<=vE){for(;qi.size>=qM||Yh+t.length>vE;){let s=qi.keys().next().value;qi.delete(s),Yh-=s.length}qi.set(t,o),Yh+=t.length}return o}var LM=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];function it(e){throw new v("INVALID_WORKFLOW",e)}function Bn(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&it(`${t} 必须是 JSON 对象`),e}function Da(e,t,r){for(let n of Object.keys(e))t.includes(n)||it(`${r} 包含不支持的字段:${n}`)}function St(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&it(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Qh(e,t,r=!1){(!Array.isArray(e)||!r&&e.length===0)&&it(`${t} 必须是${r?"":"非空"}字符串数组`);let n=e.map(i=>St(i,t));return new Set(n).size!==n.length&&it(`${t} 不能包含重复值`),n}function Zh(e,t){return Qh(typeof e=="string"?[e]:e,t)}function qa(e,t){let r=Bn(e,t);return Da(r,["id","version"],t),{id:St(r.id,`${t}.id`),version:St(r.version,`${t}.version`)}}function bE(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))bE(t);Object.freeze(e)}return e}function RE(e,t){try{let r=typeof e=="boolean"?e:Bn(e,t);typeof r!="boolean"&&r.$async===!0&&it(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),Wu(r)}catch(r){it(`${t} 不是受支持的 JSON Schema:${r.message}`)}}function MM(e){let t=Bn(e,"step"),r=St(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(r)||it(`不支持的步骤类型:${r}`);let n=r==="ask_user"?["proposalFrom","choices"]:r==="child_workflow"?["workflow"]:r==="await_evidence"?["kind"]:[];Da(t,[...LM,...n],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&it("step.retry 必须是 manual、idempotent 或 reconcile");let o={...t.ref===void 0?{}:{ref:St(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:qa(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:Qh(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:Qh(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&RE(t.outputSchema,"outputSchema"),r==="ask_user"?{...o,type:r,proposalFrom:Zh(t.proposalFrom,"step.proposalFrom"),choices:Zh(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:r==="child_workflow"?{...o,type:r,workflow:qa(t.workflow,"step.workflow")}:r==="await_evidence"?(o.validator||it("await_evidence 必须声明验证器"),{...o,type:r,kind:St(t.kind,"step.kind"),validator:o.validator}):{...o,type:r,ref:St(t.ref,"step.ref")}}var kE=new WeakSet;function Pr(e){if(kE.has(e))return e;let t=Bn(Ue(e),"workflow");Da(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let r=St(t.id,"workflow.id"),n=St(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&it("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&it("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&RE(t.stateSchema,"stateSchema");let i=Bn(t.steps,"workflow.steps");Object.keys(i).length===0&&it("workflow.steps 必须至少包含一个步骤");let o=Object.fromEntries(Object.entries(i).map(([h,g])=>(St(h,"step id"),[h,MM(g)])));function s(h,g){Object.hasOwn(o,h)||it(`${g} 引用了不存在的步骤:${h}`)}let c=Zh(t.entry,"workflow.entry");for(let h of c)s(h,"workflow.entry");let u=t.commands===void 0?{}:Bn(t.commands,"workflow.commands"),f={};for(let[h,g]of Object.entries(u)){St(h,"workflow command name");let w=typeof g=="string"?{stepId:St(g,`workflow.commands.${h}`)}:Bn(g,`workflow.commands.${h}`);Da(w,["stepId","validator"],`workflow.commands.${h}`);let k=St(w.stepId,`workflow.commands.${h}.stepId`);s(k,`workflow.commands.${h}`);let b=o[k];(b.join||!["invoke_skill","call_tool","handoff"].includes(b.type))&&it(`workflow.commands.${h} 必须指向不带 join 的执行步骤`),Object.defineProperty(f,h,{value:{stepId:k,...w.validator===void 0?{}:{validator:qa(w.validator,`workflow.commands.${h}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let a=t.transitions===void 0?[]:t.transitions;Array.isArray(a)||it("workflow.transitions 必须是数组");let d=new Set,p=a.map(h=>{let g=Bn(h,"transition");Da(g,["from","to","on"],"transition");let w=St(g.from,"transition.from"),k=St(g.to,"transition.to"),b=St(g.on===void 0?"succeeded":g.on,"transition.on");s(w,"transition.from"),s(k,"transition.to");let S=JSON.stringify([w,k,b]);return d.has(S)&&it(`重复的状态转移:${w} -> ${k} (${b})`),d.add(S),{from:w,to:k,on:b}});for(let[h,g]of Object.entries(o)){if(g.join){let w=new Set(p.filter(k=>k.to===h).map(k=>k.from));for(let k of g.join)s(k,`${h}.join`),w.has(k)||it(`${h}.join 依赖缺少对应的进入边:${k}`);w.size!==g.join.length&&it(`${h}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let w of g.proposalFrom)s(w,`${h}.proposalFrom`)}let l=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof l!="number"||!Number.isSafeInteger(l)||l<1)&&it("workflow.maxTransitions 必须是正安全整数");let m=bE({id:r,version:n,entry:c,steps:o,...t.commands===void 0?{}:{commands:f},transitions:p,maxTransitions:l,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:qa(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:qa(t.transitionHandler,"workflow.transitionHandler")}});return kE.add(m),m}function La(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!0,enumerable:!0,writable:!0})}function Fu(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.value]))}function WM(e){let t={};for(let r of e)for(let[n,i]of Object.entries(r.results))(!Object.hasOwn(t,n)||i.sequence>t[n].sequence)&&La(t,n,i);return t}function cn(e,t){if(e.status==="cancelled"||e.status==="failed")return;for(;e.ready.length>0;){let o=e.ready.shift(),s=t.steps[o.to],c=o.results;if(s.join?.length){if(o.from===null||!s.join.includes(o.from))throw new v("INVALID_JOIN","join 必须由其声明的父节点触发");Object.hasOwn(e.joins,o.to)||La(e.joins,o.to,Object.fromEntries(s.join.map(p=>[p,[]])));let d=e.joins[o.to];if(d[o.from].push(o),s.join.some(p=>d[p].length===0))continue;c=WM(s.join.map(p=>d[p].shift()))}if(e.sequence>=t.maxTransitions){e.ready.unshift(o),e.status="failed",e.reason="TRANSITION_LIMIT: 工作流已达到允许的步骤激活次数";return}let u=++e.sequence,f=`${e.runId}:${u}`,a={input:s.input===void 0?e.input:s.input,outputs:Fu(c),...o.activation===void 0?{}:{activation:o.activation}};if(s.type==="ask_user"){let d=Object.fromEntries(s.proposalFrom.map(l=>{if(!Object.hasOwn(c,l))throw new v("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${l}`);return[l,c[l].value]})),p={input:a.input,outputs:d,...o.activation===void 0?{}:{activation:o.activation}};e.waits.push({id:f,stepId:o.to,sequence:u,status:"pending",proposal:p,proposalHash:$(p),choices:[...s.choices],results:c})}else if(s.type==="await_evidence")e.evidenceWaits??=[],e.evidenceWaits.push({id:f,stepId:o.to,sequence:u,kind:s.kind,status:"pending",results:c});else{let d=s.type==="child_workflow"?`${s.workflow.id}@${s.workflow.version}`:s.ref,p=gR({id:f,runId:e.runId,stepId:o.to,type:s.type,ref:d,input:a,retry:s.retry,requiredCapabilities:s.requiredCapabilities});e.actions.push(p),La(e.actionContexts,f,{sequence:u,results:c}),s.type==="child_workflow"&&e.children.push({actionId:f,runId:`child-${$(f)}`,workflow:s.workflow})}}let r=e.actions.some(o=>["pending","running","unknown"].includes(o.status)),n=e.waits.some(o=>o.status==="pending")||(e.evidenceWaits?.some(o=>o.status==="pending")??!1),i=Object.values(e.joins).some(o=>Object.values(o).some(s=>s.length>0));e.status=r?"running":n||i?"waiting":"completed"}function Bo(e,t,r,n,i,o,s,c){let u={sequence:n,value:o},f={...i};La(f,r,u),(!Object.hasOwn(e.outputs,r)||e.outputs[r].sequence<=n)&&La(e.outputs,r,u);let a=t.transitions.filter(l=>l.from===r),d=a.filter(l=>l.on===s),p=c??d.map(l=>l.to);if(p.length===0&&s==="failed"){e.status="failed",e.reason=`ACTION_FAILED: ${r}`;return}if(p.length===0&&c===void 0&&a.length>0)throw new v("TRANSITION_UNAVAILABLE",`步骤 ${r} 未声明 ${s} 的后续转换`);for(let l of p){let m=typeof l=="string"?l:l.stepId;if(!d.some(h=>h.to===m))throw new v("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:r,to:m,results:f,...typeof l=="string"?{}:{activation:l.input}})}}function SE(e){return xe({runId:e.runId,revision:e.revision,status:e.status,sequence:e.sequence,workflow:e.workflow,input:e.input,...e.state===void 0?{}:{state:e.state},...e.reason===void 0?{}:{reason:e.reason},actions:e.actions.filter(t=>["pending","running","unknown"].includes(t.status)||t.status==="cancelled"&&t.claim&&!t.cancellation&&!t.executionStop),waits:e.waits.filter(t=>t.status==="pending"),evidenceWaits:(e.evidenceWaits??[]).filter(t=>t.status==="pending"),outputs:e.outputs,history:{actions:e.actions.length,waits:e.waits.length,evidenceWaits:e.evidenceWaits?.length??0}})}function He(e){return JSON.stringify([e.id,e.version])}function Zt(e){if(e===void 0)return;if(!e||typeof e!="object"||ng.isProxy(e))throw new v("INVALID_JSON","context 必须是普通对象");let t={},r;for(let i of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new v("INVALID_JSON","context 必须使用普通数据属性");i==="signal"?r=o.value:o.value!==void 0&&Object.defineProperty(t,i,{value:o.value,enumerable:!0})}let n=Ue(t);if(r!==void 0){if(!(r instanceof AbortSignal))throw new v("INVALID_JSON","signal 必须是 AbortSignal");n.signal=r}return n}function ig(e,t=new Set){if(e===null||typeof e!="object")return e;if(ng.isProxy(e))throw new v("INVALID_JSON","请求不能包含代理对象");if(t.size>64)throw new v("INVALID_JSON","请求数据嵌套超过 64 层");if(t.has(e))throw new v("INVALID_JSON","请求包含循环引用");let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw new v("INVALID_JSON","请求必须使用普通数据对象");t.add(e);let n=Array.isArray(e)?[]:{};for(let i of Reflect.ownKeys(e)){if(Array.isArray(e)&&i==="length")continue;let o=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!o.enumerable||!("value"in o))throw new v("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(n,i,{enumerable:!0,writable:!0,configurable:!0,value:ig(o.value,t)})}return t.delete(e),n}function tg(e){if(e===null||typeof e!="object")return e;if(ng.isProxy(e))throw new v("INVALID_JSON","请求不能包含代理对象");let t={};for(let r of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,r);if(typeof r!="string"||!n.enumerable||!("value"in n))throw new v("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(t,r,{enumerable:!0,writable:!0,configurable:!0,value:r==="context"?Zt(n.value):ig(n.value)})}return t}function Li(e){let t=ig(e),r=Ue(t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0)):t);if(!r||typeof r.accepted!="boolean"||r.reason!==void 0&&typeof r.reason!="string"||"allowCompleted"in r&&typeof r.allowCompleted!="boolean"||"allowFailed"in r&&typeof r.allowFailed!="boolean")throw new v("INVALID_VALIDATION","验证器必须返回布尔 accepted 和有效原因");return r}function rg(e,t){let r=e.supports(xe(t));if(typeof r!="boolean")throw new v("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return r}function Kr(e){if(e?.signal?.aborted)throw new v("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function Mi(e,t){if(e===t)return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>Object.hasOwn(t,n)&&Mi(e[n],t[n]))}function CE(e){return{...e,definitionHashes:{...e.definitionHashes},actions:[...e.actions],...e.commands?{commands:[...e.commands]}:{},actionContexts:{...e.actionContexts},waits:e.waits.map(t=>({...t})),...e.evidenceWaits?{evidenceWaits:e.evidenceWaits.map(t=>({...t}))}:{},ready:[...e.ready],joins:Object.fromEntries(Object.entries(e.joins).map(([t,r])=>[t,Object.fromEntries(Object.entries(r).map(([n,i])=>[n,[...i]]))])),outputs:{...e.outputs},children:[...e.children],lineage:[...e.lineage]}}var EE=new WeakMap;function Wi(e){let t=new Map,r=new Map;for(let y of e.workflows){let R=Pr(y),x=He(R);if(t.has(x))throw new v("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set(x,R);let _=EE.get(R);_===void 0&&(_=$(R),EE.set(R,_)),r.set(R,_)}let n=new Map;for(let y of e.validators??[]){let R=He(y);if(n.has(R))throw new v("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");n.set(R,y)}let i=new Map;for(let y of e.stateValidators??[]){let R=He(y);if(i.has(R))throw new v("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(R,y)}let o=new Map;function s(y){let R=o.get(y);return R||(R=Wu(y),o.set(y,R)),R}let c=new Map,u=new Map;for(let y of e.transitionHandlers??[]){let R=He(y);if(u.has(R))throw new v("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");u.set(R,y)}let f=new Map;for(let y of e.evidenceValidators??[]){let R=He(y);if(f.has(R))throw new v("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");f.set(R,y)}let a=new Map;for(let y of e.commandValidators??[]){let R=He(y);if(a.has(R))throw new v("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");a.set(R,y)}for(let y of e.executors??[]){if(c.has(y.id))throw new v("DUPLICATE_EXECUTOR","不能重复注册同一执行器");c.set(y.id,y)}function d(y){let R=t.get(He(y));if(!R)throw new v("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(y.hash!==void 0&&y.hash!==r.get(R))throw new v("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return R}function p(y){if(y.transitionHandler&&!u.has(He(y.transitionHandler)))throw new v("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function l(y){if(y.stateValidator&&!i.has(He(y.stateValidator)))throw new v("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function m(y){for(let R of Object.values(y.steps))if(R.type==="await_evidence"&&!f.has(He(R.validator)))throw new v("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function h(y){for(let R of Object.values(y.commands??{}))if(R.validator&&!a.has(He(R.validator)))throw new v("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(y,R,x){if(y.stateSchema!==void 0){let _=s(y.stateSchema);if(!_.validate(R))throw new v(x,_.errorsText())}if(y.stateValidator){let _=i.get(He(y.stateValidator));if(!_)throw new v("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let P=Li(_.validate({state:Ue(R)}));if(!P.accepted)throw new Error(P.reason??"业务状态未通过验证")}catch(P){throw new v(x,P instanceof Error?P.message:String(P))}}}function w(y,R,x,_){if(!R.transitionHandler)return;let P=u.get(He(R.transitionHandler));if(!P)throw new v("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let L=Ue(P.apply({run:xe(y),event:xe(x)})),M=Ue(L.state);g(R,M,"TRANSITION_STATE_INVALID");let V=new Set(R.transitions.filter(G=>G.from===x.stepId&&G.on===_).map(G=>G.to));if(!Array.isArray(L.next))throw new v("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let q=[],B=new Set;for(let G of L.next){let N;if(typeof G=="string")N=G;else if(G!==null&&typeof G=="object"&&!Array.isArray(G)){let le=Object.keys(G);if(le.length!==2||!le.includes("stepId")||!le.includes("input")||typeof G.stepId!="string")throw new v("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");N={stepId:G.stepId,input:Ue(G.input)}}else throw new v("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let ne=typeof N=="string"?N:N.stepId,J=$(N);if(!V.has(ne)||B.has(J))throw new v("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");B.add(J),q.push(N)}return y.state=M,q}function k(y,R=$){if(t.size>0)for(let[x,_]of Object.entries(y.definitionHashes)){let[P,L]=JSON.parse(x),M=d({id:P,version:L,hash:_});if(p(M),l(M),m(M),h(M),P===y.workflow.id&&L===y.workflow.version){let V=new Map(y.actions.map(q=>[q.id,q]));for(let q of y.commands??[]){let B=V.get(q.actionId),G=Object.hasOwn(M.commands??{},q.name),N=B&&!G&&!Object.hasOwn(M.steps,B.stepId)&&["succeeded","failed","cancelled"].includes(B.status);if(!B||!N&&(!G||M.commands?.[q.name].stepId!==B.stepId)||B.input===null||typeof B.input!="object"||!Object.hasOwn(B.input,"activation")||R(B.input.activation)!==q.inputHash)throw new v("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(M.stateSchema!==void 0&&M.initialState===void 0&&y.initialStateHash===void 0)throw new v("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(M,y.state,"RUN_STATE_INVALID");for(let q of y.ready){let B=()=>{throw new v("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(M.steps,q.to)||B(),q.from===null){(!M.entry.includes(q.to)||Object.keys(q.results).length>0||y.sequence!==0&&!(y.status==="failed"&&y.reason?.startsWith("TRANSITION_LIMIT:")))&&B();continue}let G=q.results[q.from];G||B();let N=y.actions.find(Nt=>Nt.stepId===q.from&&y.actionContexts[Nt.id].sequence===G.sequence),ne=y.waits.find(Nt=>Nt.stepId===q.from&&Nt.sequence===G.sequence),J=y.evidenceWaits?.find(Nt=>Nt.stepId===q.from&&Nt.sequence===G.sequence),le=N?.outcome?N.outcome.status==="failed"?"failed":N.outcome.event??"succeeded":ne?.decision?.choice??(J?.invalidation?"invalidated":J?.receipt?"succeeded":void 0),Ve=N?y.actionContexts[N.id].results:ne?.results??J?.results,rs=N?.outcome?N.outcome.output:ne?.decision?{choice:ne.decision.choice,proposal:ne.proposal}:J?.invalidation?{ref:J.invalidation.ref,contentHash:J.invalidation.contentHash,reason:J.invalidation.reason}:J?.receipt?{ref:J.receipt.ref,contentHash:J.receipt.contentHash}:void 0;(!le||!Ve||N&&!["succeeded","failed"].includes(N.status)||ne&&ne.status!=="resolved"||J&&!["resolved","invalidated"].includes(J.status)||rs===void 0||R(q.results)!==R({...Ve,[q.from]:{sequence:G.sequence,value:rs}})||!M.transitions.some(Nt=>Nt.from===q.from&&Nt.to===q.to&&Nt.on===le))&&B()}for(let q of y.evidenceWaits??[]){let B=M.steps[q.stepId];if(!(!B&&q.status!=="pending")&&(!B||B.type!=="await_evidence"||B.kind!==q.kind))throw new v("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function b(y){let R=await e.store.read(y);if(!R)throw new v("RUN_NOT_FOUND",`找不到工作流实例:${y}`);let x=AR(R,y);return k(x),Ci(x)}async function S(y,R,x){for(let _=0;_<32;_+=1){Kr(y.context);let P=_===0&&x?x:await b(y.runId),L=d(P.workflow);if(y.expectedRevision!==void 0&&y.expectedRevision!==P.revision)throw new v("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let M=CE(P);if(await R(M,L),sr(M),Mi(M,P))return P;if(M.revision=P.revision+1,tu(M,P),k(M),Ci(M),Kr(y.context),await e.store.compareAndSwap(y.runId,P.revision,M))return M}throw new v("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function E(y,R){let x=y.actions.find(_=>_.id===R);if(!x)throw new v("ACTION_NOT_FOUND","Run 不包含此 Action");return x}function O(y){if(y.status==="cancelled")throw new v("RUN_CANCELLED","Run 已取消,不能继续推进")}function K(y,R={}){let x=He(y);if(Object.hasOwn(R,x))return R;R[x]=r.get(y);for(let _ of Object.values(y.steps))_.type==="child_workflow"&&K(d(_.workflow),R);return R}async function D(y,R){if(Kr(y.context),R.length>32)throw new v("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let x=d(y.workflow);p(x),l(x),m(x),h(x);let _=Object.hasOwn(y,"initialState");if(_&&x.initialState!==void 0)throw new v("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let P=_?Ue(y.initialState):x.initialState;if(x.stateSchema!==void 0&&P===void 0)throw new v("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");P!==void 0&&g(x,P,"INITIAL_STATE_INVALID");let L=P===void 0?void 0:$(P),M=y.runId??eg(),V=Ue(y.input),q={id:x.id,version:x.version,hash:r.get(x)},B=await e.store.read(M);if(B){if($(B.workflow)!==$(q)||$(B.input)!==$(V)||$(B.lineage)!==$(R)||(B.initialStateHash??(x.initialState===void 0?void 0:$(x.initialState)))!==L)throw new v("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return b(M)}let G={protocolVersion:1,schemaVersion:1,runId:M,revision:1,workflow:q,definitionHashes:K(x),input:V,...P===void 0?{}:{state:Ue(P),initialStateHash:L},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:x.entry.map(N=>({from:null,to:N,results:{}})),joins:{},outputs:{},children:[],lineage:R};return cn(G,x),Ci(G),Kr(y.context),tu(G),k(G),await e.store.compareAndSwap(M,null,G)?xe(G):D({...y,runId:M},R)}async function Y(y){return D(y,[])}async function Q(y){let R=Ue(y.input),x=$(R);if(!y.commandId.trim()||y.commandId.length>4096||!y.name.trim()||y.name.length>4096)throw new v("INVALID_COMMAND","命令标识和名称不能为空");for(let _=0;_<32;_+=1){Kr(y.context);let P=await b(y.runId),L=P.commands?.find(J=>J.id===y.commandId);if(L){if(L.name!==y.name||L.inputHash!==x)throw new v("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return P}if(y.expectedRevision!==P.revision)throw new v("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let M=d(P.workflow),V=Object.hasOwn(M.commands??{},y.name)?M.commands?.[y.name]:void 0;if(!V)throw new v("COMMAND_NOT_FOUND","工作流未声明此命令");let q=V.stepId;if(P.status==="cancelled")throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.actions.some(J=>["running","unknown"].includes(J.status)))throw new v("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let B=!1,G=!1;if(V.validator){let J=a.get(He(V.validator));if(!J)throw new v("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let le;try{le=Li(await J.validate({run:xe(P),name:y.name,input:xe(R),context:Zt(y.context)}))}catch(Ve){throw new v("COMMAND_VALIDATION_ERROR",Ve instanceof Error?Ve.message:String(Ve))}if(B=le.accepted&&le.allowCompleted===!0,G=le.accepted&&le.allowFailed===!0,P.status==="failed"&&!G)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="completed"&&!B)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!le.accepted)throw new v("COMMAND_REJECTED",le.reason??"命令未通过当前工作流状态验证")}if(P.status==="completed"&&!B)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="failed"&&!G)throw new v("RUN_TERMINAL","已停止的 Run 不能接受命令");let N=xe(P);P.status==="failed"&&(N.status="running",delete N.reason),N.actions=N.actions.map(J=>J.status==="pending"?Zp(J,`命令 ${y.name} 已取代待执行 Action`):J);for(let J of N.waits)J.status==="pending"&&(J.status="cancelled");for(let J of N.evidenceWaits??[])J.status==="pending"&&(J.status="cancelled");N.ready=[{from:null,to:q,results:{},activation:R}],N.joins={},cn(N,M);let ne=N.actions.at(-1);if(!ne||ne.stepId!==q||ne.status!=="pending")throw new v("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if(N.commands=[...N.commands??[],{id:y.commandId,name:y.name,inputHash:x,actionId:ne.id}],N.revision=P.revision+1,tu(N,P),k(N),Ci(N),Kr(y.context),await e.store.compareAndSwap(y.runId,P.revision,N))return xe(N)}throw new v("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function te(y){for(let R of y.children)await e.store.read(R.runId)&&await j({runId:R.runId,reason:y.reason??"父工作流已取消"})}function Z(y,R,x){let _=d(y.workflow),P=Object.hasOwn(_.steps,x.stepId)?_.steps[x.stepId]:void 0;if(!P||P.type!=="child_workflow"||He(P.workflow)!==He(R.workflow)||x.type!==P.type||x.ref!==`${P.workflow.id}@${P.workflow.version}`||x.attempt!==1||x.retry!==P.retry||!Mi(x.requiredCapabilities,P.requiredCapabilities??[])||x.claim&&(x.claim.executorId!=="comet-child-workflow"||x.claim.sessionId!==void 0||![R.runId,`portable-${$(R.runId)}`].includes(x.claim.token)))throw new v("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let L=x.input;if(!L||typeof L!="object"||Array.isArray(L)||!Mi(L,{input:P.input===void 0?y.input:P.input,outputs:Fu(y.actionContexts[x.id].results),...Object.hasOwn(L,"activation")?{activation:L.activation}:{}}))throw new v("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let M=d({...R.workflow,hash:y.definitionHashes[He(R.workflow)]});if(Object.entries(K(M)).some(([V,q])=>y.definitionHashes[V]!==q))throw new v("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return M}function Pe(y,R,x,_,P){let L=_.initialState===void 0?void 0:$(_.initialState);if(P.runId!==R.runId||He(P.workflow)!==He(R.workflow)||P.workflow.hash!==y.definitionHashes[He(R.workflow)]||!Mi(P.definitionHashes,K(_))||!Mi(P.input,x.input)||!Mi(P.lineage,[...y.lineage,y.runId])||(P.initialStateHash??L)!==L)throw new v("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function ee(y){let R=await S(y,(x,_)=>cn(x,_));if(R.status==="cancelled")return await te(R),R;if(R.status==="failed"||R.children.length===0)return R;for(let x of R.children){let _=E(R,x.actionId);if(!["pending","running","unknown"].includes(_.status))continue;let P=Z(R,x,_);_.status==="pending"&&(R=await he({runId:R.runId,actionId:_.id,attempt:_.attempt,inputHash:_.inputHash,executorId:"comet-child-workflow",claimToken:x.runId,capabilities:["child-workflow"],context:Zt(y.context)},!0),_=E(R,x.actionId));let L=_.status==="unknown"?await b(x.runId):await D({runId:x.runId,workflow:x.workflow,input:_.input,context:Zt(y.context)},[...R.lineage,R.runId]);Pe(R,x,_,P,L);let M=await b(R.runId);if(M.status==="cancelled")return await te(M),M;let V=await ee({runId:x.runId,context:y.context});Pe(R,x,_,P,V),["completed","failed","cancelled"].includes(V.status)&&(R=await I({runId:R.runId,context:Zt(y.context),outcome:{actionId:_.id,attempt:_.attempt,inputHash:_.inputHash,claimToken:_.claim.token,outcomeId:`${x.runId}:${V.revision}`,status:V.status==="completed"?"succeeded":"failed",output:Fu(V.outputs)}},!0))}return b(R.runId)}async function he(y,R=!1,x){let _=y.claimToken??(y.context?.requestId?$({runId:y.runId,actionId:y.actionId,attempt:y.attempt,executorId:y.executorId,requestId:y.context.requestId}):eg());return S(y,async P=>{if(O(P),P.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let L=E(P,y.actionId);if(L.type==="child_workflow"&&!R)throw new v("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let M=yR(L,{executionOrigin:{workflow:{...P.workflow}},attempt:y.attempt,inputHash:y.inputHash,executorId:y.executorId,token:_,...y.sessionId===void 0?{}:{sessionId:y.sessionId}});if(!L.claim){let V=new Set(y.capabilities??[]);if(L.requiredCapabilities.some(B=>!V.has(B)))throw new v("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let q=c.get(y.executorId);if(q&&rg(q,L)){if(L.requiredCapabilities.some(B=>!q.capabilities.includes(B)))throw new v("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await q.preflight?.(xe(L),Zt(y.context),q.includeRun===!1?void 0:xe(P)),Kr(y.context)}}P.actions[P.actions.indexOf(L)]=M},x)}async function Xe(y){return he(y)}async function I(y,R=!1,x){let _,P;try{_=Ql(y.outcome)}catch(V){P=V}y={...y,outcome:_};let L,M=await S(y,async(V,q)=>{if(L=void 0,O(V),!_)throw P;let B=E(V,y.outcome.actionId);if(B.type==="child_workflow"&&!R)throw new v("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let G=Qp(B,y.outcome);if(G.duplicate)return;let N=G.action.outcome,ne=V.actions.indexOf(B);try{if(e.validateOutcome){let le=Li(await e.validateOutcome({run:xe(V),action:xe(B),outcome:xe(N),context:Zt(y.context)}));le.accepted||(L={code:"OUTCOME_REJECTED",reason:le.reason??"应用结果契约拒绝此结果"})}let J=q.steps[B.stepId];if(!L&&N.status==="succeeded"&&J.outputSchema!==void 0){let le=s(J.outputSchema);le.validate(N.output)||(L={code:"OUTPUT_INVALID",reason:le.errorsText()})}if(!L&&J.validator){let le=n.get(He(J.validator));if(!le)throw new v("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let Ve=Li(await le.validate({run:xe(V),action:xe(B),outcome:xe(N),context:Zt(y.context)}));Ve.accepted||(L={code:"OUTCOME_REJECTED",reason:Ve.reason?.trim()?Ve.reason:"结果未满足业务验收条件"})}if(!L){let le=CE(V);le.actions[ne]=G.action;let Ve=le.actionContexts[B.id],rs=N.status==="failed"?"failed":N.event??"succeeded",Nt=w(le,q,{kind:"action-outcome",stepId:B.stepId,outcome:N},rs);Bo(le,q,B.stepId,Ve.sequence,Ve.results,N.output,rs,Nt),cn(le,q),Object.assign(V,le)}}catch(J){L={code:"OUTCOME_PROCESSING_ERROR",reason:J instanceof Error&&J.message.trim()?J.message:"结果处理失败,请检查验证器或工作流定义"}}L&&(V.actions[ne]={...B,receipts:G.action.receipts,rejectedOutcomes:[...B.rejectedOutcomes??[],{outcome:G.action.outcome,...L}]})},x);if(L)throw new v(L.code,L.reason);return M}async function H(y){return I(y)}async function ie(y){if(y.reason!==void 0&&!rm(y.reason))throw new v("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return S(y,(R,x)=>{O(R);let _=R.waits.find(L=>L.id===y.waitId);if(!_)throw new v("WAIT_NOT_FOUND","Run 不包含此等待项");if(_.decision){if(_.decision.id!==y.decisionId||_.decision.choice!==y.choice||_.decision.proposalHash!==y.proposalHash||_.decision.reason!==y.reason)throw new v("DECISION_CONFLICT","等待项已经接受了不同的决定");return}if(_.status!=="pending"||_.proposalHash!==y.proposalHash)throw new v("STALE_PROPOSAL","提案已改变或等待项已终止,请重新审阅");if(!y.decisionId.trim()||!_.choices.includes(y.choice))throw new v("INVALID_DECISION","决定标识或选择不符合当前等待项");_.status="resolved",_.decision={id:y.decisionId,choice:y.choice,proposalHash:y.proposalHash,...y.reason===void 0?{}:{reason:y.reason}};let P=w(R,x,{kind:"wait-resolved",stepId:_.stepId,choice:y.choice,proposalHash:y.proposalHash,decisionId:y.decisionId},y.choice);Bo(R,x,_.stepId,_.sequence,_.results,{choice:y.choice,proposal:_.proposal},y.choice,P),cn(R,x)})}async function Qe(y){return S(y,async(R,x)=>{if(O(R),R.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止,不能提交证据");let _=R.evidenceWaits?.find(q=>q.id===y.evidenceId);if(!_)throw new v("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(_.status!=="pending")throw new v("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(_.kind!==y.kind)throw new v("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!y.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(y.ref)||y.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(y.contentHash)||!y.submissionId.trim())throw new v("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let P=x.steps[_.stepId];if(!P||P.type!=="await_evidence"||P.kind!==y.kind)throw new v("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let L=f.get(He(P.validator));if(!L)throw new v("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let M=Li(await L.validate({run:xe(R),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:Zt(y.context)}));if(!M.accepted||M.actualHash!==y.contentHash)throw new v("EVIDENCE_REJECTED",M.reason??"证据未通过验证或内容已改变");_.status="resolved",_.receipt={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId};let V=w(R,x,{kind:"evidence-recorded",stepId:_.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId},"succeeded");Bo(R,x,_.stepId,_.sequence,_.results,{ref:y.ref,contentHash:y.contentHash},"succeeded",V),cn(R,x)})}async function C(y){return S(y,async(R,x)=>{if(O(R),R.status==="failed")throw new v("RUN_FAILED","Run 已因失败停止,不能使证据失效");let _=R.evidenceWaits?.find(B=>B.id===y.evidenceId);if(!_)throw new v("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(_.status!=="pending")throw new v("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(_.kind!==y.kind)throw new v("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!y.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(y.ref)||y.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(y.contentHash)||!y.submissionId.trim())throw new v("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let P=x.steps[_.stepId];if(!P||P.type!=="await_evidence"||P.kind!==y.kind)throw new v("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!x.transitions.some(B=>B.from===_.stepId&&B.on==="invalidated"))throw new v("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let L=f.get(He(P.validator));if(!L)throw new v("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let M=Li(await L.validate({run:xe(R),kind:y.kind,ref:y.ref,contentHash:y.contentHash,context:Zt(y.context)}));if(M.accepted&&M.actualHash===y.contentHash)throw new v("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let V=(M.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);_.status="invalidated",_.invalidation={ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:V};let q=w(R,x,{kind:"evidence-invalidated",stepId:_.stepId,evidenceKind:y.kind,ref:y.ref,contentHash:y.contentHash,submissionId:y.submissionId,reason:V},"invalidated");Bo(R,x,_.stepId,_.sequence,_.results,{ref:y.ref,contentHash:y.contentHash,reason:V},"invalidated",q),cn(R,x)})}async function T(y){return S(y,R=>{O(R);let x=R.waits.find(_=>_.id===y.waitId);if(!x||x.status!=="pending"||x.proposalHash!==y.proposalHash)throw new v("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");x.proposal=Ue(y.proposal),x.proposalHash=$(x.proposal)})}async function j(y){let R=await S(y,x=>{if(x.status==="completed"){if(y.stoppedActions?.length)throw new v("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let _=x.status==="cancelled";if(_||(x.actions=x.actions.map(P=>Zp(P,y.reason))),y.stoppedActions!==void 0){if(!Array.isArray(y.stoppedActions))throw new v("INVALID_ACTION","stoppedActions 必须是停止确认数组");let P=new Set;for(let L of y.stoppedActions){if(!L||typeof L!="object"||P.has(L.actionId))throw new v("INVALID_ACTION","停止确认重复或无效");P.add(L.actionId);let M=E(x,L.actionId);x.actions[x.actions.indexOf(M)]=em(M,L)}}if(!_){for(let P of x.waits)P.status==="pending"&&(P.status="cancelled");for(let P of x.evidenceWaits??[])P.status==="pending"&&(P.status="cancelled");x.ready=[],x.status="cancelled",x.reason=y.reason}});return R.status==="cancelled"&&await te(R),R}async function W(y){return S(y,R=>{if(!Array.isArray(y.stoppedActions)||!y.stoppedActions.length)throw new v("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let x=new Set;for(let _ of y.stoppedActions){if(!_||typeof _!="object"||x.has(_.actionId))throw new v("INVALID_ACTION","停止确认重复或无效");x.add(_.actionId);let P=E(R,_.actionId);R.actions[R.actions.indexOf(P)]=tm(P,_)}})}async function F(y){return S(y,R=>{O(R);let x=E(R,y.actionId);if(x.attempt!==y.attempt)throw new v("STALE_ACTION","Action 执行尝试已经改变");R.actions[R.actions.indexOf(x)]=vR(x,y.reason)})}async function oe(y){return S(y,async(R,x)=>{O(R);let _=E(R,y.actionId);if(_.attempt!==y.attempt)throw new v("STALE_ACTION","Action 执行尝试已经改变");if(_.type==="child_workflow")throw new v("CHILD_MANAGED","子工作流由 Runtime 管理,不支持通过通用 retry 重置父 Action;保留原有子 Run 和执行记录");if(_.status==="succeeded"&&e.validateRecovery){if(y.expectedRevision===void 0)throw new v("REVISION_CONFLICT","恢复已提交结果必须绑定当前 Run 版本");if(y.reconciliation!==void 0)throw new v("OUTCOME_ALREADY_RECORDED","已提交结果不能声明未执行;请使用应用的语义恢复");if(typeof y.proposalHash!="string"||!y.proposalHash.trim())throw new v("INVALID_REQUEST","恢复已提交结果必须绑定当前应用决定");if(R.actions.some(q=>["running","unknown"].includes(q.status)))throw new v("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(R.status!=="completed"||R.ready.length>0||R.actions.some(q=>q.status==="pending")||R.waits.some(q=>q.status==="pending")||R.evidenceWaits?.some(q=>q.status==="pending")||Object.values(R.joins).some(q=>Object.values(q).some(B=>B.length>0))||!_.outcome||_.outcome.status!=="succeeded")throw new v("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let P=Li(await e.validateRecovery({run:xe(R),action:xe(_),outcome:xe(_.outcome),context:Zt(y.context),proposalHash:y.proposalHash}));if(!P.accepted)throw new v("ACTION_TERMINAL",P.reason??"应用拒绝恢复此结果");let L=_.outcome.event??"succeeded",M=w(R,x,{kind:"action-outcome",stepId:_.stepId,outcome:_.outcome},L);if(M?.length===0||M===void 0&&!x.transitions.some(q=>q.from===_.stepId&&q.on===L))throw new v("ACTION_TERMINAL","应用未声明可恢复的后续工作");let V=R.actionContexts[_.id];Bo(R,x,_.stepId,V.sequence,V.results,_.outcome.output,L,M),cn(R,x);return}if(_.status==="failed"){let P=R.actionContexts[_.id].sequence,L=V=>Object.hasOwn(V,_.stepId)&&V[_.stepId].sequence===P;if(Object.values(R.actionContexts).some(V=>L(V.results))||R.waits.some(V=>L(V.results))||R.evidenceWaits?.some(V=>L(V.results))||R.ready.some(V=>L(V.results))||Object.values(R.joins).some(V=>Object.values(V).some(q=>q.some(B=>L(B.results)))))throw new v("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}R.actions[R.actions.indexOf(_)]=kR(_,y.reconciliation),R.status="running",delete R.reason})}async function ce(y,R){let x=c.get(y.executorId);if(!x)throw new v("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let _=R??await b(y.runId),P=E(_,y.actionId);if(P.status!=="pending")throw new v("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!rg(x,P))throw new v("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");Kr(y.context);let L=await he({...y,attempt:P.attempt,inputHash:P.inputHash,claimToken:eg(),capabilities:x.capabilities},!1,_),M=E(L,y.actionId),V;try{Kr(y.context),V=await x.execute(xe(M),Zt(y.context),x.includeRun===!1?void 0:xe(L))}catch(B){let G=await b(y.runId),N=E(G,M.id);throw G.status!=="cancelled"&&N.status==="running"&&N.attempt===M.attempt&&await F({runId:y.runId,actionId:M.id,attempt:M.attempt,reason:B instanceof Error?B.message:String(B)}),new v("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let q=`${M.id}:${M.attempt}:executor-result`;try{return await I({runId:y.runId,context:Zt(y.context),outcome:{...V,actionId:M.id,attempt:M.attempt,inputHash:M.inputHash,claimToken:M.claim.token,outcomeId:q}},!1,L)}catch(B){let G=await b(y.runId),N=E(G,M.id);if(N.receipts.some(ne=>ne.outcomeId===q)){if(N.rejectedOutcomes?.some(ne=>ne.outcome.outcomeId===q))throw B;if(N.outcome?.outcomeId===q)return G}throw G.status!=="cancelled"&&N.status==="running"&&N.attempt===M.attempt&&await F({runId:y.runId,actionId:M.id,attempt:M.attempt,reason:B instanceof Error?B.message.slice(0,4096):"执行结果无法提交"}),new v("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function Me(y){let R=y.maxActions??100;if(!Number.isSafeInteger(R)||R<1)throw new v("INVALID_REQUEST","maxActions 必须是正安全整数");let x=c.get(y.executorId);if(!x)throw new v("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let _=0,P=await b(y.runId),L=V=>({reason:V,run:P,actionsExecuted:_}),M=V=>{if(P.status==="completed"||P.status==="failed"||P.status==="cancelled")return P.status;if(P.actions.some(q=>q.status==="unknown"&&(!V||q.type!=="child_workflow")))return"execution-unknown";if(P.actions.some(q=>q.status==="running"&&(!V||q.type!=="child_workflow")))return"action-in-flight";if(P.waits.some(q=>q.status==="pending"))return"approval-required";if(P.evidenceWaits?.some(q=>q.status==="pending"))return"evidence-required"};for(;;){Kr(y.context);let V=M(!0);if(V)return L(V);(P.ready.length||P.children.length)&&(P=await ee({runId:y.runId,context:y.context}));let q=M(!1);if(q)return L(q);let B=P.actions.find(G=>G.status==="pending");if(!B)return L("idle");if(_>=R)return L("action-limit");if(!rg(x,B)||B.requiredCapabilities.some(G=>!x.capabilities.includes(G)))return L("executor-required");_++;try{P=await ce({...y,actionId:B.id},P)}catch(G){if(!(G instanceof v)||G.code!=="EXECUTION_UNKNOWN"||(P=await b(y.runId),!P.actions.some(N=>N.status==="unknown")))throw G;return L("execution-unknown")}}}async function ze(y){let R=await xo(e.store,y);return k(R.run,yt),R}async function zt(y){return im(await ze(y.runId),y)}function be(y){return async(...R)=>{let x=R.map(_=>tg(_));return xe(await y(...x))}}return{start:be(Y),dispatchCommand:be(Q),inspect:be(b),inspectProjection:ze,query:be(zt),inspectCurrent:async y=>await zt({runId:y,view:"current"}),executeCurrent:async y=>SE(await ce(tg(y))),runUntilBlockedCurrent:async y=>{let R=await Me(tg(y));return{...R,run:SE(R.run)}},next:be(ee),claim:be(Xe),recordOutcome:be(H),resolveWait:be(ie),recordEvidence:be(Qe),invalidateEvidence:be(C),reviseWait:be(T),cancel:be(j),acknowledgeStopped:be(W),markUnknown:be(F),retry:be(oe),execute:be(y=>ce(y)),runUntilBlocked:be(Me)}}Ts();ai();import{createHash as DE,randomUUID as h6}from"node:crypto";import{types as JM}from"node:util";import{promises as fr}from"node:fs";import ot from"node:path";import{randomUUID as BM}from"node:crypto";import{promises as Un}from"node:fs";import Ma from"node:path";import{performance as PE}from"node:perf_hooks";import{createRequire as FM}from"node:module";var HM=FM(import.meta.url??__filename),Hu;function Uo(e,t){if(!Hu){let r=process.emitWarning;process.emitWarning=((n,...i)=>{String(n instanceof Error?n.message:n).startsWith("SQLite is an experimental feature and might change at any time")||Reflect.apply(r,process,[n,...i])});try{Hu=HM("node:sqlite").DatabaseSync}finally{process.emitWarning=r}}return t===void 0?new Hu(e):new Hu(e,t)}import{AsyncLocalStorage as VM}from"node:async_hooks";var _E=new VM,og=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}};function AE(e){return Math.max(0,Math.min(e,(_E.getStore()?.deadline??1/0)-performance.now()))}function xE(){let e=_E.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new og}async function IE(e){let t,r;try{let n=await Un.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock metadata must be a regular file: "+e);r=[n.dev,n.ino,n.size,n.mtimeMs].join(":"),t=await Un.readFile(e,"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{let n=JSON.parse(t),i=n.nonce??n.id,o=typeof n.createdAt=="number"?n.createdAt:Date.parse(n.createdAt);if(typeof i=="string"&&i&&Number.isFinite(o))return{owner:{nonce:i,createdAt:o,...n.protocolVersion===2?{protocolVersion:2}:{},...typeof n.operation=="string"?{operation:n.operation}:{}},token:i,legacy:n.protocolVersion!==2}}catch{}return{owner:null,token:r,legacy:!0}}async function UM(e){let t=e+".sqlite";try{let n=await Un.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error("File lock database must be a regular file: "+t)}catch(n){if(n.code!=="ENOENT")throw n}let r;try{r=Uo(Ma.toNamespacedPath(t))}catch(n){throw new Error("Unable to open Runtime lock database "+t,{cause:n})}try{return r.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE;"),r}catch(n){if(r.close(),/database is (?:locked|busy)/iu.test(String(n)))return null;throw new Error("Unable to acquire Runtime lock transaction "+t,{cause:n})}}function OE(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function KM(e,t={}){e=Ma.resolve(e),await Un.mkdir(Ma.dirname(e),{recursive:!0});let r=await Un.lstat(Ma.dirname(e));if(!r.isDirectory()||r.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+Ma.dirname(e));let n=PE.now()+AE(t.timeoutMs??3e4),i;for(;xE(),i=await UM(e),!i;){if(PE.now()>=n)throw new Error("Timed out waiting for file lock: "+e);await new Promise(c=>setTimeout(c,t.retryMs??20))}let o={protocolVersion:2,nonce:BM(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let c=await IE(e);if(c?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
168
+ Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));c&&await Un.unlink(e),await Un.writeFile(e,JSON.stringify(o),{mode:384,flag:"wx"})}catch(c){throw OE(i),c}let s=!1;return{owner:o,async release(){if(s)return!0;s=!0;let c=!0;try{let u=await IE(e);u?.token===o.nonce?u.owner?.createdAt===o.createdAt&&u.owner.operation===o.operation?await Un.unlink(e):(c=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
169
+ `)):u&&(c=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
170
+ `))}finally{OE(i)}return c}}}async function NE(e,t,r={}){let n=await KM(e,r),i;try{i=await t()}catch(o){try{await n.release()}catch(s){process.stderr.write("[comet] lock cleanup failed; preserved the original operation error: "+String(s)+`
171
+ `)}throw o}return await n.release(),i}Lt();ye();jr();var TE=new WeakMap;function $E(e){return Vu(e).encoded}function Vu(e){let t=new WeakMap,r=new Map,n=a=>{if(typeof a=="string"){let m=r.get(a);return m===void 0&&(m=JSON.stringify(a).length,r.set(a,m)),m}if(a===null||typeof a!="object")return JSON.stringify(a).length;let d=TE.get(a)??t.get(a);if(d!==void 0)return d;let p=Object.entries(a),l=2+Math.max(0,p.length-1)+p.reduce((m,[h,g])=>m+(Array.isArray(a)?0:n(h)+1)+n(g),0);return t.set(a,l),or(a)&&TE.set(a,l),l},i=n(e),o=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return o();let s=[],c=(a,d)=>{if(!a||typeof a!="object")return;let p=a;if(!(p.protocolVersion!==1||!Array.isArray(p.actions)||!p.actionContexts)){for(let[l,m]of p.actions.entries())m.input&&typeof m.input=="object"&&Object.hasOwn(m.input,"outputs")&&s.push({path:[...d,"actions",String(l),"input","outputs"],group:"outputs"});for(let[l,m]of Object.entries(p.actionContexts))m?.results&&s.push({path:[...d,"actionContexts",l,"results"],group:"results"});p.outputs&&s.push({path:[...d,"outputs"],group:"results"});for(let l of["ready","waits","evidenceWaits"])for(let[m,h]of(p[l]??[]).entries())h.results&&s.push({path:[...d,l,String(m),"results"],group:"results"})}};if(c(e,[]),c(e.run,["run"]),!s.length)return o();let u=fR(e,s,or),f=JSON.stringify(u);return f.length<i*.9?{encoded:u,json:f}:o()}function Fi(e){if(typeof e!="string"||e.trim().length===0)throw new v("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function zM(e){return Fi(e),DE("sha256").update(JSON.stringify(e)).digest("hex")}function Bu(e){if(!Number.isSafeInteger(e)||e<1)throw new v("STORE_INVALID_REVISION","revision 必须是正安全整数")}function GM(e,t,r,n=!0){if(Fi(e),JM.isProxy(r))throw new v("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&Bu(t),sr(r);let i=n?structuredClone(r):r;if(!i||typeof i!="object"||Array.isArray(i)||i.runId!==e)throw new v("STORE_INVALID_RUN_ID","next.runId 必须与目标 runId 一致");if(Bu(i.revision),i.revision!==(t??0)+1)throw new v("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}var jE="comet.runtime-store-checkpoint.v1";function YM(e,t,r){let n=Ue(r);if(Fi(e),!n||n.runId!==e)throw new v("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(Bu(n.revision),t!==null&&t!==1||n.revision<=(t??0))throw new v("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(n)}function qE(e,t,r){let n=Ue(e);n.revision=t;for(let i of r){let o=n;for(let s of i.slice(0,-1))o=o[s];o[i.at(-1)]=t}return n}function XM(e,t,r,n=[]){return(e?.revision??null)===t&&(e===null||rn(e)===rn(qE(r,1,n)))}function pr(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new v("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(C=>{if(C!=="run.revision")throw new v("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function r(C){for(let T of t){let j=C;for(let W of T){if(!j||typeof j!="object"||Array.isArray(j)||!Object.hasOwn(j,W))throw new v("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");j=j[W]}if(j!==C.revision)throw new v("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let n=ot.resolve(e.rootDir),i=ot.parse(n).root,o=ot.relative(i,n).replaceAll("\\","/");if(!o)throw new v("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let s={label:"RuntimeStore root",expected:"directory"},c=zM,u="checkpoint.json",f="comet.runtime-store-format.v2",a=".runtime-store-v2",d=C=>`${a}/${c(C)}`,p=C=>`.runtime-store-history/${c(C)}`,l="comet.runtime-store-format.v3",m="comet.runtime-store-snapshot.v2",h=".write.lock",g=/^[0-9]{16}\.json$/u;function w(){return{record:null,compacted:!1,legacyRevision:null,formatPresent:!1}}async function k(C,T){let j=await ae(n,C?`${C}/${T}`:T,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let W=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(j.bytes));return sr(W),W}catch{throw new v("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function b(C,T,j){if(!C||typeof C!="object"||Array.isArray(C)||C.runId!==T||C.revision!==j||!Number.isSafeInteger(j)||j<1)throw new v("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");r(C)}async function S(C,T=!1,j=c(C),W=!0){if(Fi(C),!(await U(i,o,s)).exists)return w();let F=await U(n,j,{label:"RuntimeStore run",expected:"directory"});if(!F.exists)return w();let oe=await fr.lstat(F.target),ce=await fr.readdir(F.target,{withFileTypes:!0}),Me=await fr.lstat(F.target);if(await U(i,`${o}/${j}`,s),!oe.isDirectory()||oe.isSymbolicLink()||!Me.isDirectory()||Me.isSymbolicLink()||!rr({dev:oe.dev,ino:oe.ino,birthtime:oe.birthtimeMs},{dev:Me.dev,ino:Me.ino,birthtime:Me.birthtimeMs}))throw new v("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let ze=new Set,zt=[],be=0;for(let N of ce){if((N.name===`${h}.contenders`||N.name==="legacy"&&j===d(C))&&N.isDirectory()&&!N.isSymbolicLink())continue;if(!N.isFile()||N.isSymbolicLink())throw new v("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);if(/^\..+\.tmp$/u.test(N.name)||N.name===h||[h+".sqlite",h+".sqlite-journal",h+".sqlite-wal",h+".sqlite-shm"].includes(N.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test(N.name)||(ze.add(N.name),N.name===u))continue;if(!g.test(N.name))throw new v("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);let ne=Number(N.name.slice(0,-5));if(!Number.isSafeInteger(ne)||ne<1)throw new v("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);zt.push(N.name),be=Math.max(be,ne)}let y=!1;if([d(C),p(C)].includes(j)&&zt.length>0)throw new v("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(ze.has(u)){if(![d(C),p(C)].includes(j))throw new v("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let N=await k(j,u),ne=N?.record,J=N?.legacyRevision;if(!N||![m,"comet.runtime-store-snapshot.v3"].includes(String(N.schema))||!ne||Object.keys(N).some(Ve=>!["schema","record","hash","legacyRevision",...N.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(Ve))||J!==null&&(!Number.isSafeInteger(J)||J<1||J>ne.revision)||N.hash!==$({record:ne,legacyRevision:J,...N.schema==="comet.runtime-store-snapshot.v3"?{pool:N.pool}:{}}))throw new v("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let le;try{le=N.schema==="comet.runtime-store-snapshot.v3"?Yl(ne,N.pool,W):ne}catch(Ve){throw new v("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${Ve instanceof Error?Ve.message:String(Ve)}`)}return b(le,C,le.revision),{record:le,compacted:!0,legacyRevision:J,formatPresent:y}}if(!be)return w();let R=new Map,x=N=>`${String(N).padStart(16,"0")}.json`,_=N=>ze.has(x(N));async function P(N){if(R.has(N))return R.get(N);let ne=await k(j,x(N));return(N<=2||N===be)&&R.set(N,ne),ne}async function L(N,ne=0,J=be){if(b(N,C,J),T)for(let le of zt){let Ve=Number(le.slice(0,-5));Ve!==ne&&b(await P(Ve),C,Ve)}return{record:N,compacted:!1,legacyRevision:N.revision,formatPresent:!1}}let M=await P(be);if(be===zt.length&&(M?.schema!==jE||M?.runId!==void 0))return L(M);if(!_(1))throw new v("STORE_MISSING_REVISION","版本历史缺少 revision 1");let V=null;for(let N of[1,2]){if(!_(N))break;let ne=await P(N);if(ne?.schema!==jE||"runId"in ne)continue;let J=ne.record;if(J&&r(J),!J||J.runId!==C||!Number.isSafeInteger(J.revision)||J.revision<N||ne.hash!==$(J)||Object.keys(ne).some(le=>!["schema","record","hash"].includes(le))||N===2&&rn(await P(1))!==rn(qE(J,1,t)))throw new v("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");V={slot:N,record:J};break}let q=V?.record.revision??0,B=V?.slot??0,G=be===B?q:be;if(G<q||zt.length!==G-q+B||zt.some(N=>{let ne=Number(N.slice(0,-5));return ne>B&&ne<=q})){let N=q+1;for(;_(N);)N+=1;throw new v("STORE_MISSING_REVISION",`版本历史缺少 revision ${N}`)}return L(V&&be===V.slot?V.record:M,B,V&&be===V.slot?V.record.revision:be)}async function E(C){let T=await U(n,c(C),{label:"RuntimeStore format",expected:"any"}),j=await U(n,`${d(C)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if(T.kind==="directory"&&j.exists&&(T=await U(n,c(C),{label:"RuntimeStore format",expected:"any"})),T.kind==="directory"&&j.exists)throw new v("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let W=null;if(T.kind==="file"){let F=await k("",c(C));if(!F||F.runId!==C||(F.schema===f?!["pending","ready"].includes(F.state)||Object.keys(F).some(oe=>!["schema","runId","state","writerProtocol"].includes(oe)):F.schema!==l||!["closing","closed","reopening"].includes(F.state)||!Number.isSafeInteger(F.revision)||F.revision<1||typeof F.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(F.recordHash)||Object.keys(F).some(oe=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(oe))))throw new v("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(F.writerProtocol!==void 0&&F.writerProtocol!=="application-holder-v1")throw new v("STORE_WRITER_FENCED","存储协议版本不受支持");W=F}return{original:T,staged:j,marker:W}}function O(C){return ia(C)?yt(C,{cachePrefixes:!1}):$(C)}async function K(C,T){let j=await S(C,!1,d(C),!1),W=await S(C,!1,p(C),!1);if(!j.record&&!W.record||T.state==="closed"&&(j.record||!W.record))throw new v("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(j.record&&W.record){let oe=await fr.lstat(ot.join(n,d(C),u)),ce=await fr.lstat(ot.join(n,p(C),u)),Me={dev:oe.dev,ino:oe.ino,birthtime:oe.birthtimeMs},ze={dev:ce.dev,ino:ce.ino,birthtime:ce.birthtimeMs};if(!Zc(Me,ze)||!rr(Me,ze))throw new v("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let F=W.record??j.record;if(F.revision!==T.revision||O(F)!==T.recordHash||j.record&&j.record!==F&&O(j.record)!==T.recordHash)throw new v("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:F,active:!!j.record,history:!!W.record}}async function D(C){if(Fi(C),!(await U(i,o,s)).exists)return"missing";let T=await E(C),j=await U(n,`${d(C)}/${u}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),W=await U(n,`${p(C)}/${u}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(T.marker?.schema===l){if(!j.exists&&!W.exists||T.marker.state==="closed"&&(j.exists||!W.exists))throw new v("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return T.marker.state}if(W.exists)throw new v("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return T.marker||j.exists||T.original.kind==="directory"||T.staged.exists?"active":"missing"}async function Y(C,T,j){await $e(ot.join(n,c(C)),JSON.stringify({schema:l,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:C,state:T,revision:j.revision,recordHash:O(j)})+`
172
+ `,{containedRoot:n,requireAtomicPublication:!0})}async function Q(C){let T=(await E(C)).marker;if(!T||!["closing","reopening"].includes(T.state))return;let j=T.state==="closing",W=(await K(C,T)).record,F=await K(C,T),oe=j?d(C):p(C),ce=j?p(C):d(C);await ft(n,ce,{label:"RuntimeStore 历史目标"});let Me=ot.join(n,oe,u),ze=ot.join(n,ce,u),zt=j?F.active:F.history;(j?F.history:F.active)||(await U(n,`${oe}/${u}`,{label:"RuntimeStore 历史源",expected:"file"}),await U(n,ce,{label:"RuntimeStore 历史目标",expected:"directory"}),await fr.link(Me,ze),await K(C,T)),await he(ot.dirname(ze)),await he(ot.dirname(ot.dirname(ze))),await he(n),zt&&(await K(C,T),await Dr(Me,{containedRoot:n,beforeRemove:async()=>{await K(C,T)}}),await he(ot.dirname(Me))),j?await Y(C,"closed",W):await ee(C,"ready",!1);let y=await Z(C,!1);if(!y||y.revision!==W.revision||O(y)!==O(W))throw new v("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function te(C,T,j){return Fi(C),Bu(T),Xe(C,async()=>{await Q(C);let W=(await E(C)).marker,F;if(W?.schema===l){if(j&&W.state==="reopening")throw new v("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!j&&W.state==="closing")throw new v("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(F=(await K(C,W)).record,F.revision!==T)return!1;if(j&&W.state==="closed")return!0}else{if(F=(await ie(C,!1)).record,!F||F.revision!==T)return!1;if(!j)return!0}return await Y(C,j?"closing":"reopening",F),await Q(C),!0})}async function Z(C,T=!0){if(Fi(C),!(await U(i,o,s)).exists)return null;let j=await E(C);if(j.marker?.schema===l){let{record:oe}=await K(C,j.marker);return T?Ht(oe):oe}if((await S(C,!1,p(C),!1)).record)throw new v("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let F=await S(C,!1,d(C),T);if(F.record){if(!j.marker&&!(await E(C)).marker)throw new v("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return F.record}if(j.original.kind==="directory"){let oe=(await S(C)).record;if(!oe&&(await E(C)).original.kind!=="directory")throw new v("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return oe}if(j.marker?.state==="ready")throw new v("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(j.staged.exists){let oe;try{oe=(await S(C,!1,`${d(C)}/legacy`)).record}catch(ce){throw(await E(C)).marker?.state==="ready"?new v("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):ce}if(!oe){let ce=await E(C);if(!ce.staged.exists||ce.marker?.state==="ready")throw new v("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return oe}return null}async function Pe(C,T=!0){for(let j=0;;j+=1)try{return await Z(C,T)}catch(W){let F=W instanceof ut&&W.reason==="changed",oe=["ENOENT","ENOTDIR"].includes(W.code??""),ce=W instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(W.message);if(!F&&!oe&&!ce||j>=15)throw W}}async function ee(C,T,j){await $e(ot.join(n,c(C)),JSON.stringify({schema:f,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:C,state:T})+`
173
+ `,{containedRoot:n,exclusive:j,requireAtomicPublication:!0})}async function he(C){let T;try{T=await fr.open(C,"r"),await T.sync()}catch(j){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(j.code??""))throw j}finally{await T?.close()}}async function Xe(C,T){if(await ft(i,o,s),(await U(n,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new v("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await ft(n,d(C),{label:"RuntimeStore run"}),await he(ot.join(n,a)),await he(n);try{return e.singleWriter?await T():await NE(ot.join(n,d(C),h),T)}catch(W){throw["ENOTSUP","EOPNOTSUPP"].includes(W.code??"")?new v("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):W}}async function I(C,T,j,W=Vu(T)){let F=ot.join(n,d(C)),oe=j.legacyRevision,{encoded:ce,json:Me}=W,ze=ce.pool?{record:ce.record,legacyRevision:oe,pool:ce.pool}:{record:T,legacyRevision:oe},zt=ce.pool?"comet.runtime-store-snapshot.v3":m,be=`{"schema":${JSON.stringify(zt)},${Me.slice(1,-1)},"legacyRevision":${JSON.stringify(oe)},"hash":${JSON.stringify($(ze))}}
174
+ `;await $e(ot.join(F,u),be,{containedRoot:n,exclusive:!j.compacted,requireAtomicPublication:!0}),j.formatPresent||await ee(C,"ready",!1)}async function H(C,T){if(T===null)return;let j=`${d(C)}/legacy`,W=await U(n,j,{label:"RuntimeStore legacy",expected:"directory"});if(W.exists)try{for(let F of await fr.readdir(W.target,{withFileTypes:!0}))F.isFile()&&!F.isSymbolicLink()&&g.test(F.name)&&Number(F.name.slice(0,-5))<=T&&await Dr(ot.join(W.target,F.name),{containedRoot:n});await U(n,j,{label:"RuntimeStore legacy",expected:"directory"}),await fr.rmdir(W.target).catch(F=>{if(F.code!=="ENOTEMPTY"&&F.code!=="EEXIST")throw F})}catch(F){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${F instanceof Error?F.message:String(F)}
175
+ `)}}async function ie(C,T=!0){let j=(await E(C)).marker;if(j?.writerProtocol&&j.writerProtocol!==e.writerProtocol)throw new v("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await Q(C);let W=await E(C);if(W.marker?.schema===l)throw new v("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await S(C,!1,p(C),!1)).record)throw new v("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let oe=await S(C,!1,d(C),T);if(oe.record&&!W.marker)throw new v("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(W.original.kind==="directory"){await S(C,!0);let Me=await fr.lstat(W.original.target);await U(i,`${o}/${c(C)}`,s),await U(n,d(C),s),await fr.rename(W.original.target,W.staged.target);let ze=await fr.lstat(W.staged.target);if(!ze.isDirectory()||ze.isSymbolicLink()||!rr({dev:Me.dev,ino:Me.ino,birthtime:Me.birthtimeMs},{dev:ze.dev,ino:ze.ino,birthtime:ze.birthtimeMs}))throw new v("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await he(ot.join(n,d(C))),await he(n),W=await E(C)}if(!W.marker){try{await ee(C,"pending",!0)}catch(Me){throw["EEXIST","EISDIR","ENOTDIR"].includes(Me.code??"")?new v("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):Me}W=await E(C)}let ce=oe;if(!ce.record&&W.marker?.state==="ready")throw new v("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!ce.record&&W.staged.exists?(ce=await S(C,!0,`${d(C)}/legacy`),ce.record&&(await I(C,ce.record,ce),ce={...ce,compacted:!0,formatPresent:!0})):ce.record&&W.marker?.state==="pending"&&await ee(C,"ready",!1),ce.record&&(ce.formatPresent=!0,await H(C,ce.legacyRevision)),ce}return{queryScope:`file:${DE("sha256").update(n).digest("hex")}`,read:Pe,readProjection:C=>Pe(C,!1),readPartitionMetadata:D,settleRun:C=>An(async()=>await D(C)==="missing"?"missing":Xe(C,async()=>{await Q(C);let T=(await E(C)).marker;return T&&e.writerProtocol&&T.writerProtocol!==e.writerProtocol&&await $e(ot.join(n,c(C)),JSON.stringify({...T,writerProtocol:e.writerProtocol})+`
176
+ `,{containedRoot:n,requireAtomicPublication:!0}),D(C)})),closeRun:(C,T)=>An(()=>te(C,T,!0)),reopenRun:(C,T)=>An(()=>te(C,T,!1)),async readDisposition(C){if(!await Pe(C,!1))return"missing";let j=(await E(C)).marker;return j?.schema===l?j.state:"active"},async restoreCheckpoint(C,T,j){let W=JSON.parse(YM(C,T,j));return r(W),Xe(C,async()=>{let F=await ie(C);return XM(F.record,T,W,t)?(await I(C,W,F),!0):!1})},compareAndSwap:async(C,T,j)=>Qe(C,T,j)(),prepareCompareAndSwap:Qe};function Qe(C,T,j){GM(C,T,j,!1),r(j);let{json:W}=Vu(j),F=JSON.parse(W);return()=>Xe(C,async()=>{let oe=await ie(C,!1);return(oe.record?.revision??null)!==T?!1:(await I(C,F.record,oe,{encoded:F,json:W}),!0)})}}ye();import{isDeepStrictEqual as LE}from"node:util";var ht="run_checkpoint",sg="comet.workflow-run-checkpoint.v1",QM=/^portable-[a-f0-9]{64}$/u;function Uu(e){return QM.test(e)?e:`portable-${$(e)}`}function Ku(e){let t=$E(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:$(t)}:e}function Wa(e,t){return LE(e,t)||LE(e,Ku(t))}function ME(e){return{...e,revision:1,actions:e.actions.map(t=>{let r=new Set((t.rejectedOutcomes??[]).map(i=>i.outcome.outcomeId)),n={...t,receipts:t.receipts.filter(i=>!r.has(i.outcomeId)).map(i=>({...i}))};if(delete n.rejectedOutcomes,t.claim){let i=Uu(t.claim.token);if(n.claim={...t.claim,token:i},t.executionStop&&(n.executionStop={...t.executionStop,claimToken:i}),t.cancellation&&(n.cancellation={...t.cancellation,claimToken:i}),t.outcome){n.outcome={...t.outcome,claimToken:i};let o=n.receipts.find(s=>s.outcomeId===t.outcome.outcomeId);o&&(o.hash=$(n.outcome))}}return t.status==="running"&&(n.status="unknown",n.reason="Portable recovery requires reconciliation of external execution"),n})}}var WE={hash:yt,visitResults:zl,validateOrigins:Gl};function ZM(e){let t=sa(ME(e),e.runId,WE),r=yt(t);return{schema:sg,hash:r,run:t,sourceRevision:e.revision,sourceHash:$({hash:r,sourceRevision:e.revision})}}function Ko(e){let t=Ao(ME(e),e.runId),r=$(t);return{schema:sg,hash:r,run:t,sourceRevision:e.revision,sourceHash:$({hash:r,sourceRevision:e.revision})}}function FE(e,t,r={},n=!1){if(e===void 0)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Portable Run checkpoint for ${t} is invalid`);sr(e);let i=e;if(![sg,"comet.workflow-run-checkpoint.v2"].includes(String(i.schema))||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash)||Object.keys(i).some(c=>!["schema","hash","run","sourceRevision","sourceHash",...i.schema==="comet.workflow-run-checkpoint.v2"?["pool","storageHash"]:[]].includes(c))||i.schema==="comet.workflow-run-checkpoint.v2"&&$({record:i.run,pool:i.pool})!==i.storageHash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=i.schema==="comet.workflow-run-checkpoint.v2"?Yl(i.run,i.pool,!n):i.run;if((n?yt:$)(o)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let s=n?sa(o,t,WE):Ao(o,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==$({hash:i.hash,sourceRevision:i.sourceRevision}))throw new Error(`Portable Run checkpoint revision for ${t} is invalid or changed`);if(r.preserveSourceRevision)return{...s,revision:i.sourceRevision}}return s}function Ir(e,t,r={}){return FE(e,t,r)}function Ju(e,t,r={}){return FE(e,t,r,!0)}function Hi(e,t){if(e===void 0)return!1;let r=Ju(e,t.runId,{preserveSourceRevision:!0});if(!r)return!1;let n=e,i=ZM(t);return n.hash===i.hash&&n.sourceRevision===i.sourceRevision&&n.sourceHash===i.sourceHash&&r.revision===t.revision}function Vi(e){let t=structuredClone(e);for(let r of t.actions)r.claim&&!r.executionOrigin&&(r.executionOrigin={workflow:{...e.workflow}});return t}function ag(e,t){if(!t.claim)throw new Error("执行绑定需要原领取记录");return{workflow:{...t.executionOrigin?.workflow??e.workflow},runId:e.runId,actionId:t.id,attempt:t.attempt,inputHash:t.inputHash,claimToken:Uu(t.claim.token)}}ai();var Sg=Tt(Gt(),1);import{execFileSync as Gn}from"node:child_process";import hr from"node:path";import{isDeepStrictEqual as Rg}from"node:util";import{execFileSync as JE}from"node:child_process";import{AsyncLocalStorage as BE}from"node:async_hooks";import{performance as HE}from"node:perf_hooks";var oW=0,sW=0,cg=new BE,VE=new BE;async function UE(e,t=r=>{let n=r.completed===void 0?"":`:${r.completed}${r.total===void 0?"":`/${r.total}`} 项`;process.stderr.write(`[Comet] ${r.label}${n},已用 ${Math.floor(r.elapsedMs/1e3)} 秒
177
+ `)}){if(VE.getStore())return e();let r={label:"执行工作流命令"},n=Date.now(),i=setInterval(()=>{try{t({...r,elapsedMs:Date.now()-n})}catch{}},5e3);i.unref?.();try{return await VE.run(r,e)}finally{clearInterval(i)}}function aW(e=0){oW+=1,sW+=e;for(let t of cg.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}async function KE(e){let t={gitCommands:0,gitDurationMs:0};return{result:await cg.run([...cg.getStore()??[],t],e),metrics:t}}function Kn(e){let t=HE.now();try{return e()}finally{aW(HE.now()-t)}}var v9=8*1024*1024;var cW=3e4,lW=8*1024*1024;function zE(e,t){if(t.some(s=>!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(s)))throw new Error("Git commit paths require complete commit IDs");if(!t.length)return new Map;let r;try{r=Kn(()=>JE("git",["diff-tree","--stdin","--always","--no-renames","--name-status","-r","-z"],{cwd:e,input:t.join(`
178
+ `)+`
179
+ `,encoding:"utf8",timeout:cW,maxBuffer:lW,windowsHide:!0}))}catch(s){if(!["ENOBUFS","ETIMEDOUT"].includes(s.code??""))throw s;return new Map(t.map(c=>[c,Kn(()=>JE("git",["diff-tree","--no-commit-id","--no-renames","--name-only","-r","-z",c],{cwd:e,encoding:"utf8",windowsHide:!0})).split("\0").filter(Boolean)]))}let n=r.split("\0"),i=new Map,o=0;for(let s of t){if(n[o++]!==s)throw new Error(`Git commit path response does not match ${s}`);let c=[];for(;/^[ACDMTUXB]$/u.test(n[o]??"");){o+=1;let u=n[o++];if(!u)throw new Error("Git commit path response is incomplete");c.push(u)}i.set(s,c)}if(n.slice(o).some(Boolean))throw new Error("Git commit path response has unexpected records");return i}Yt();ye();function mr(e,t,r){if(!e)return null;let n=e.replaceAll("\\","/");return n.startsWith(`${t}/`)?`${r}/${n.slice(t.length+1)}`:n}import{execFileSync as lg}from"child_process";var uW=Tt(Gt(),1);jr();Lt();ye();function Jr(e){let t={cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0};try{let r=Kn(()=>lg("git",["rev-parse","--abbrev-ref","HEAD"],t).trim());if(r&&r!=="HEAD")return r}catch{}try{return Kn(()=>lg("git",["symbolic-ref","--quiet","--short","HEAD"],t).trim())||null}catch{return null}}var L9=$r("liveGitBranch",e=>Jr(e));function Jo(e){try{return Kn(()=>lg("git",["rev-parse","--is-inside-work-tree"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())==="true"}catch{return!1}}var M9=$r("isGitWorkTree",e=>Jo(e)),dW=["current","branch","worktree"];function ug(e){return dW.includes(e)}function Fa(e){return ug(e.isolation)?e.boundBranch===null&&e.currentBranch===null&&e.gitWorkTree===!1?{status:"not-applicable"}:e.boundBranch===null?e.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:e.currentBranch}:e.currentBranch===e.boundBranch?{status:"ok"}:{status:"drift",boundBranch:e.boundBranch,currentBranch:e.currentBranch}:{status:"not-applicable"}}import fW from"node:path";async function GE(e,t,r){if(r!=="en"&&r!=="zh-CN")return"Classic change language is not set";let n=t.replaceAll("\\","/");for(let i of["proposal.md","tasks.md","design.md"]){let o=fW.posix.join(n,i);if(i==="design.md"&&!await Lr(e,o,{label:"Classic Open design"}))continue;let s=await Fe(e,o,{label:`Classic Open ${i}`});if(!s.trim())return i+" is empty";if(i==="tasks.md"&&Gs(s).length===0)return"tasks.md has no task"}return null}function Le(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic delivery recovery evidence is missing");return e}function Bi(e,t){let r=e.state.workflow,n=e.actions.slice().reverse().find(u=>u.stepId===`${r}.archive.execute`&&u.status==="succeeded"),i=e.actions.slice().reverse().find(u=>u.stepId===r+(e.workflow.version==="2"?".archive.preflight":".verify.check")&&u.status==="succeeded");if(!n?.outcome||!i?.outcome||t&&(t.archiveActionId!==n.id||t.checkActionId!==i.id))throw new Error("Classic delivery recovery requires its original Archive and Verify");let o=Le(n.input).outputs,s=Le(Le(o)[`${r}.archive.preflight`]),c=Le(n.outcome.output).archiveDirectory;if(typeof c!="string"||typeof s?.baseCommit!="string")throw new Error("Classic delivery recovery lacks its approved archive target");return{profile:r,archive:n,check:i,approved:{...s,baseCommit:s.baseCommit},archiveRef:c}}function Go(e){return Le(Le(e.input).activation).deliveryRepair}function zo(e,t){let r=e.state;return r.archived&&r.phase==="archive"&&t.type==="call_tool"&&t.ref==="classic-check"&&t.stepId===`${r.workflow}.delivery.check`}function dg(e,t){let r=Bi(e,t),n=Le(r.check.outcome.output),i=Array.isArray(n.deliveryPaths)?n.deliveryPaths:Object.keys(n.deliveryInputs??{}),o=new Set(t.excludedOutputPaths??Object.keys(t.excludedOutputs??{}));return i.filter(s=>!o.has(s))}function YE(e){let t=e.state,r=e.actions.filter(i=>i.status==="pending"),n=e.waits.filter(i=>i.status==="pending");if(!t.archived||t.phase!=="archive"||!["running","waiting","failed"].includes(e.status)||e.actions.some(i=>["running","unknown"].includes(i.status))||e.evidenceWaits?.some(i=>i.status==="pending"))return!1;if(e.status==="failed"){let i=e.actions.at(-1);return r.length===0&&n.length===0&&i?.status==="failed"&&zo(e,i)}return n.length?e.status==="waiting"&&r.length===0&&n.length===1&&n[0].stepId===`${t.workflow}.delivery.confirm`:e.status==="running"&&r.length===1&&!r[0].claim&&(r[0].stepId===`${t.workflow}.archive.deliver`||zo(e,r[0]))}function XE(e,t){if(e===void 0||t.state.archived!==!0)return!1;let r=$(e);return!!t.commands?.some(n=>{if(!["repair-delivery","continue-work"].includes(n.name))return!1;let i=t.actions.find(s=>s.id===n.actionId);if(!i||$(i.input)!==i.inputHash)return!1;let o=Le(Le(i.input).activation);if(n.name==="continue-work"){let s=t.actions.find(c=>c.id===o.interruptedActionId);return i.stepId==="classic.resume-work"&&typeof o.deliveryCheckpointHash=="string"&&$(o)===n.inputHash&&o.deliveryCheckpointHash===r&&!!(s?.status==="failed"&&Jn(t,s))}return zo(t,i)&&$(o)===n.inputHash&&Le(o.deliveryRepair).checkpointHash===r})}function Jn(e,t){let r=e.state;if(!r.archived||t.type!=="invoke_skill"||t.stepId!==`${r.workflow}.archive.deliver`)return null;let n=Le(t.input).activation,i=n===void 0?{}:Le(n),o=i.deliveryRepairCheckId;if(o===void 0&&i.interruptedActionId!==void 0){let p=e.actions.find(g=>g.id===i.interruptedActionId),l=e.actionContexts[t.id]?.sequence,m=e.actionContexts[t.id]?.results["classic.resume-work"],h=e.actions.find(g=>g.stepId==="classic.resume-work"&&e.actionContexts[g.id]?.sequence===m?.sequence);if(!p||p.status!=="failed"||p.type!==t.type||p.ref!==t.ref||p.stepId!==t.stepId||l===void 0||(e.actionContexts[p.id]?.sequence??1/0)>=l||h?.status!=="succeeded"||h.claim?.executorId!=="comet-classic-work-continuation"||$(h.outcome?.output)!==$({interruptedActionId:p.id,resumeStepId:p.stepId})||Le(Le(h.input).activation).interruptedActionId!==p.id||!e.commands?.some(g=>g.name==="continue-work"&&g.actionId===h.id&&g.inputHash===$(Le(h.input).activation)))throw new Error("Classic delivery continuation is missing its original stopped Skill");return Jn(e,p)}let s=Bi(e),c=e.actionContexts[s.archive.id]?.results[`${r.workflow}.archive.confirm`]?.sequence,u=e.waits.find(p=>p.stepId===`${r.workflow}.archive.confirm`&&p.sequence===c&&p.status==="resolved"),f={outputs:{...Le(Le(s.archive.input).outputs),[s.archive.stepId]:s.archive.outcome.output},archiveActionId:s.archive.id,approvalWaitIds:u?[u.id]:[]};if(o===void 0){let p=Le(Le(t.input).outputs);if(e.actionContexts[t.id]?.results[s.archive.stepId]?.sequence!==e.actionContexts[s.archive.id]?.sequence||$(p[`${r.workflow}.archive.preflight`])!==$(s.approved)||$(p[s.archive.stepId])!==$(s.archive.outcome.output))throw new Error("Classic delivery is missing its original approved Archive context");return f}let a=e.actions.find(p=>p.id===o),d=e.waits.slice().reverse().find(p=>p.stepId===`${r.workflow}.delivery.confirm`&&p.results[`${r.workflow}.delivery.check`]?.sequence===(a&&e.actionContexts[a.id]?.sequence));if(!a||!zo(e,a)||a.status!=="succeeded"||d?.status!=="resolved"||d.decision?.choice!=="approved"||$(Le(Le(d.proposal).outputs)[a.stepId])!==$(a.outcome.output))throw new Error("Classic delivery repair is missing its current check and explicit approval");return Bi(e,Go(a)),{...f,outputs:{...f.outputs,[a.stepId]:a.outcome.output},repairCheckId:a.id,approvalWaitIds:[...f.approvalWaitIds,d.id]}}function Ha(e,t){let r=Jn(e,t);if(r){let f=e.actions.find(a=>a.id===r.archiveActionId);if(!f)throw new Error("Classic delivery recovery is missing its original Archive");return Ha(e,f)}let n=t.input.outputs??{};if(n["full.build.plan"]!==void 0)return{outputs:n,recovered:!1};let i=e.actionContexts[t.id]?.sequence;if(i===void 0)return{outputs:n,recovered:!1};let o=[...e.commands??[]].reverse().find(f=>f.actionId===t.id||(e.actionContexts[f.actionId]?.sequence??1/0)<i);if(!o||!["reopen-verification","continue-build"].includes(o.name))return{outputs:n,recovered:!1};let s=e.actionContexts[o.actionId].sequence,c=[...e.actions].reverse().filter(f=>f.stepId==="full.build.execute"&&(e.actionContexts[f.id]?.sequence??1/0)<s),u=c[0];if(u?.status!=="succeeded"||u.outcome?.status!=="succeeded"||u.outcome.output.event!=="build-complete")return{outputs:n,recovered:!1};for(let f of c){let a=e.actionContexts[f.id].sequence;if(e.commands?.some(p=>["revise-design","revise-plan"].includes(p.name)&&e.actionContexts[p.actionId]?.sequence>a&&e.actionContexts[p.actionId].sequence<s))break;let d=f.input.outputs;if(!(d?.["full.build.plan"]===void 0||d["full.design.document"]===void 0))return{recovered:!0,outputs:{"full.design.document":d["full.design.document"],"full.build.plan":d["full.build.plan"]}}}return{outputs:n,recovered:!1}}import{promises as mW}from"node:fs";import Ui from"node:path";Yt();ye();Yt();ye();import{promises as pW}from"node:fs";import zu from"node:path";async function QE(e,t,r,n){let i=t.input.changeDir;if(et(i,"Classic active path"),et(n,"Classic archive path"),r.status!=="succeeded"||r.outcome?.status!=="succeeded"||r.claim?.executorId!=="comet-classic-archive"||r.outcome.output?.archiveDirectory!==n)throw new Error("旧 Archive 缺少成功的原执行结果");let o=[],s=[];async function c(m){let h=await U(e,m,{label:"Classic legacy archive path",expected:"any"});if(h.exists)if(h.kind==="directory")for(let g of await pW.readdir(h.target)){if([".comet-state.lock",".comet-state-transaction.json"].includes(g)){let w=m+"/"+g+"/.comet-runtime-migration.json";(await U(e,w,{label:"Classic legacy migration marker",expected:"file"})).exists&&(s.push(w),o.push(i+"/"+w.slice(n.length+1)));continue}await c(m+"/"+g)}else o.push(m)}await c(n);let u=zu.relative(e,(await Xr(e)).specsDir).replaceAll("\\","/");for(let m of[...o])m.startsWith(n+"/specs/")&&m.endsWith("/spec.md")&&o.push(u+"/"+m.slice((n+"/specs/").length));let f=Ha(t,r).outputs,a=f["full.design.document"]?.designDoc,d=f["full.build.plan"]?.plan;for(let m of[a,d])m&&o.push(mr(m,i,n));let p=zu.relative(e,await Re(zu.join(e,n))).replaceAll("\\","/"),l=o.filter(m=>m.startsWith(n+"/")).map(m=>i+"/"+m.slice(n.length+1));return{paths:[...new Set([...o,...l])],sourcePaths:l,stateFiles:[p,i+"/"+zu.posix.basename(p)],optionalPaths:s}}var ZE=".comet/archive-manifest.json";function fg(e,t){return $(ag(e,t))}async function e_(e){return pr({singleWriter:!0,rootDir:Ui.join(await Qr(e),"archive-receipts/classic")})}async function hW(e){return pr({singleWriter:!0,rootDir:Ui.join(await Qr(e),"archive-inputs/classic")})}async function t_(e,t,r){if(r.status!=="failed"||r.outcome?.status!=="failed")throw new Error("原 Archive 尚未确认失败退出;先恢复原 Action 并核对实际归档进度");let n=t.input.changeDir;if(!(await U(e,n,{label:"Classic active change",expected:"directory"})).exists)throw new Error("原 change 目录已搬迁;恢复原 Archive 进度,不能重开执行");let o=await(await hW(e)).read(fg(t,r));if(o?.snapshot.archivePaths){let s=await U(e,Ui.posix.dirname(n)+"/archive",{label:"Classic Archive directory",expected:"directory"}),c=Ui.posix.basename(n);if(s.exists&&(await mW.readdir(s.target)).some(u=>/^\d{4}-\d{2}-\d{2}-/u.test(u)&&u.slice(11)===c&&!o.snapshot.archivePaths.includes(u)))throw new Error("原 Archive 已创建归档目录;先恢复该事务,不能重开执行")}}async function gW(e,t,r,n){let i=await(await e_(e)).read(fg(t,r));if(!i||i.manifest.archiveRef!==n||i.manifest.execution.actionId!==r.id)throw new Error("原 Archive 执行收据缺失;核对原命令结果并恢复原记录,不能重复执行或用当前文件补造成功");return i}async function r_(e,t,r,n,i){return await gW(e,t,r,n),Yo(e,t,r,n)}async function Yo(e,t,r,n,i=r.outcome?.artifacts){await U(e,n+"/"+ZE,{label:"Classic Archive manifest",expected:"file"});let o=await(await e_(e)).read(fg(t,r)),s=r.outcome?.output?.archiveManifest,c=o?.manifest??s;if(!c)return QE(e,t,r,n);if(!["comet.classic.archive-manifest.v1","comet.classic.archive-manifest.v2"].includes(c.schema)||c.activeRef!==t.input.changeDir||c.archiveRef!==n||c.execution?.actionId!==r.id||c.execution?.runId!==t.runId)throw new Error("归档交付记录不属于原 Run 和 Action");let u=c.paths??Object.keys(c.files??{}),f=c.sourcePaths??Object.keys(c.sources??{}),a=c.optionalPaths??Object.keys(c.optionalFiles??{});for(let p of[...u,...f,...a])et(p,"Classic Archive path");let d=Ui.relative(e,await Re(Ui.join(e,n))).replaceAll("\\","/");return{paths:[...new Set([...u,n+"/"+ZE,...f.filter(p=>p.startsWith(c.activeRef+"/"))])],sourcePaths:f,stateFiles:[d,c.activeRef+"/"+Ui.posix.basename(d)],optionalPaths:[...new Set([...a,...[".comet-state.lock",".comet-state-transaction.json"].map(p=>n+"/"+p+"/.comet-runtime-migration.json")])]}}function Gu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function zn(e,t){return yt(e)===yt(t)}function n_(e){return{protocolVersion:e.protocolVersion,id:e.id,runId:e.runId,stepId:e.stepId,type:e.type,...e.ref===void 0?{}:{ref:e.ref},input:e.input,inputHash:e.inputHash,retry:e.retry,requiredCapabilities:e.requiredCapabilities}}function Xo(e,t,r={}){if(Gu(t.state).archived!==!0||XE(e,t))return null;let n=(r.projection?Ju:Ir)(e,t.runId,{preserveSourceRevision:!0});if(!n)return null;let i=Gu(n.state),o=n.actions.at(-1),s=`${i.workflow}.archive.deliver`;if(i.archived!==!0||i.phase!=="archive"||!["full","tweak","hotfix"].includes(String(i.workflow))||n.status!=="running"||!o||o.stepId!==s||o.status!=="pending"||o.claim||o.outcome)return null;let c=()=>{throw new Error(`Classic SDK Run ${t.runId} does not match its archived delivery checkpoint; restore the original checkpoint and reconcile delivery on the same Run without changing its Archive or Verify history`)},u=n.outputs[s],f=n.actionContexts[o.id]?.sequence,a=u!==void 0&&u.sequence===f,d=u!==void 0&&!a&&n.actions.some(w=>w.id!==o.id&&w.stepId===s&&w.status==="failed"&&w.outcome?.status==="failed"&&n.actionContexts[w.id]?.sequence===u.sequence&&f!==void 0&&u.sequence<f&&zn(w.outcome.output,u.value));(i.branchStatus!=="pending"||o.type!=="invoke_skill"||typeof o.ref!="string"||!o.ref.trim()||o.retry!=="manual"||o.reconciliations.length!==o.attempt-1||o.reconciliations.some((w,k)=>w.attempt!==k+1)||o.receipts.length>=o.attempt||(o.rejectedOutcomes?.length??0)!==0||o.receipts.length!==0!==a||u!==void 0&&!a&&!d||o.reason!==void 0||n.reason!==void 0||!n.actions.some(w=>w.stepId===`${i.workflow}.archive.execute`&&w.ref==="classic-archive"&&w.status==="succeeded")||n.actions.slice(0,-1).some(w=>["pending","running","unknown"].includes(w.status))||n.ready.length!==0||n.waits.some(w=>w.status==="pending")||n.evidenceWaits?.some(w=>w.status==="pending")||Object.values(n.joins).some(w=>Object.values(w).some(k=>k.length!==0)))&&c();let p=t.actions.at(-1);if(!p)return c();zn(n_(p),n_(o))||c(),Zl(p,yt(p.input)),(!["pending","running","unknown","failed","succeeded"].includes(p.status)||p.cancellation||p.executionOrigin&&!zn(p.executionOrigin.workflow,t.workflow)||p.reconciliations.length!==p.attempt-1||p.reconciliations.some((w,k)=>w.attempt!==k+1)||p.attempt<o.attempt||!zn(p.receipts.slice(0,o.receipts.length),o.receipts)||!zn(p.reconciliations.slice(0,o.reconciliations.length),o.reconciliations)||p.receipts.length-(p.rejectedOutcomes?.length??0)>p.attempt||p.status==="pending"&&p.reason!==void 0)&&c();let l=p.status==="succeeded",m=p.status==="failed";(t.status!==(l?"completed":m?"failed":"running")||t.reason!==(m?`ACTION_FAILED: ${s}`:void 0)||Gu(t.state).branchStatus!==(l?"handled":i.branchStatus)||t.revision<n.revision+(p.attempt-o.attempt)*3+(p.status==="pending"?0:p.status==="running"?1:2))&&c(),!p.outcome&&p.receipts.length===o.receipts.length&&(Object.hasOwn(t.outputs,s)!==Object.hasOwn(n.outputs,s)||Object.hasOwn(n.outputs,s)&&!zn(t.outputs[s],n.outputs[s]))&&c(),p.outcome?zn(t.outputs[s],{sequence:n.actionContexts[o.id].sequence,value:p.outcome.output})||c():Object.hasOwn(t.outputs,s)&&!(d&&zn(t.outputs[s],u)&&p.receipts.length===(p.rejectedOutcomes?.length??0))&&(p.attempt===1||p.receipts.length===(p.rejectedOutcomes?.length??0)||t.outputs[s].sequence!==n.actionContexts[o.id].sequence)&&c();let h={...t.outputs};Object.hasOwn(n.outputs,s)?h[s]=n.outputs[s]:delete h[s];let g={...t,revision:n.revision,status:n.status,state:{...Gu(t.state),branchStatus:i.branchStatus},actions:[...t.actions.slice(0,-1),o],outputs:h};return delete g.reason,Hi(e,g)||c(),n}import{execFileSync as kW}from"node:child_process";var i_=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],wW={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}};function yW(e){return e.toISOString().slice(0,10)}function pe(e,t,r,n){let i=e[r];e[r]=n,i!==n&&t.push({field:r,from:i,to:n})}function Ct(e,t,r={}){let n=wW[t];if(e.phase!==n.from)throw new Error(`Cannot apply ${t}: phase is '${e.phase}', expected '${n.from}'`);let i={...e},o=[],s=e.checkEpoch??0;if(!Number.isSafeInteger(s)||s<0||s===Number.MAX_SAFE_INTEGER)throw new Error("Invalid Classic check epoch");pe(i,o,"checkEpoch",s+1);let c=r.now??new Date;if(t==="open-complete")pe(i,o,"phase",i.workflow==="full"?"design":"build");else if(t==="design-complete")pe(i,o,"phase","build");else if(t==="build-complete"){let u=i.verifyResult==="fail";pe(i,o,"phase","verify"),pe(i,o,"verifyResult","pending"),pe(i,o,"branchStatus","pending"),u||pe(i,o,"verificationReport",null)}else if(t==="verify-pass")pe(i,o,"verifyResult","pass"),pe(i,o,"verifyFailures",0),pe(i,o,"phase","archive"),pe(i,o,"verifiedAt",yW(c)),pe(i,o,"archiveConfirmation","pending"),pe(i,o,"branchStatus","pending");else if(t==="verify-fail")pe(i,o,"verifyResult","fail"),pe(i,o,"verifyFailures",i.verifyFailures+1),pe(i,o,"phase","build"),pe(i,o,"branchStatus","pending");else if(t==="preset-escalate"){if(i.workflow!=="hotfix"&&i.workflow!=="tweak")throw new Error(`Cannot apply ${t}: workflow must be hotfix or tweak, got '${i.workflow}'`);pe(i,o,"workflow","full"),pe(i,o,"classicProfile","full"),pe(i,o,"phase","design"),pe(i,o,"designDoc",null),pe(i,o,"buildPause",null),pe(i,o,"buildMode",null),pe(i,o,"subagentDispatch",null),pe(i,o,"tddMode",null),pe(i,o,"reviewMode",null),pe(i,o,"isolation",null),pe(i,o,"boundBranch",null),pe(i,o,"verifyMode",null),pe(i,o,"directOverride",null)}else if(t==="archive-confirm"){if(i.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(i.archived)throw new Error(`Cannot apply ${t}: already archived`);pe(i,o,"archiveConfirmation","confirmed")}else if(t==="archive-reopen"){if(i.archived)throw new Error(`Cannot apply ${t}: already archived`);pe(i,o,"verifyResult","pending"),pe(i,o,"verifyFailures",0),pe(i,o,"phase","verify"),pe(i,o,"verifiedAt",null),pe(i,o,"archiveConfirmation",null),pe(i,o,"branchStatus","pending")}else{if(i.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(i.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${t}: archiveConfirmation must be confirmed`);pe(i,o,"archived",!0)}return{classic:i,effects:o,definition:n}}function o_(e){let t=e.state,r=[...e.actions].reverse().find(s=>s.stepId===t.workflow+".verify.run"),n=[...e.actions].reverse().find(s=>s.stepId===t.workflow+".verify.check"),i=e.evidenceWaits?.slice().reverse().find(s=>s.stepId===t.workflow+".verify.check.evidence");if(!r||!n||n.executionOrigin?.workflow.version!=="1"||n.status!=="succeeded"||n.outcome?.status!=="succeeded"||i?.status!=="resolved"||i.results[n.stepId]?.sequence!==e.actionContexts[n.id]?.sequence||e.actionContexts[n.id]?.results[r.stepId]?.sequence!==e.actionContexts[r.id]?.sequence)return null;let o=n.outcome.output;return o.scope!=="verify"||o.exitCode!==0||o.tier!=="full"||!Array.isArray(o.argv)||!o.argv.length||typeof o.receiptRef!="string"||typeof o.contentHash!="string"||i.receipt?.ref!==o.receiptRef||i.receipt.contentHash!==o.contentHash?null:{action:n,output:o}}function pg(e,t,r){let n=Pr(t),i=$(n);if(e.workflow.version===n.version&&e.workflow.hash===i)return e;if(e.workflow.version===n.version)throw new Error("Classic 当前 Run 的 definition hash 不匹配;不能作为旧业务数据重新绑定。");if(!["1","2"].includes(e.workflow.version)||e.workflow.id!==n.id)throw new Error("Classic Run 不属于可升级的内置协议");let o=Vi(e),s=d=>Object.hasOwn(n.steps,d),c=new Set;for(let d of o.actions)!s(d.stepId)&&["pending","running","unknown"].includes(d.status)&&(c.add(d.stepId),d.status="cancelled",d.reason="旧检查调度已移交 Agent 平台;原进程结果未确认,不代表已经停止或通过。");for(let d of[...o.waits,...o.evidenceWaits??[]])!s(d.stepId)&&d.status==="pending"&&(c.add(d.stepId),d.status="cancelled");let u=o.ready;o.ready=u.filter(d=>s(d.to)&&(d.from===null||s(d.from)));for(let d of u)(!s(d.to)||d.from!==null&&!s(d.from))&&c.add(d.to);if(e.status==="failed"&&e.reason?.startsWith("ACTION_FAILED: ")){let d=e.reason.slice(15);s(d)||c.add(d)}let f=o.state;if(e.workflow.version==="1"&&f.phase==="verify"&&o.evidenceWaits?.some(d=>d.status==="pending"&&d.stepId.endsWith(".verify.report.evidence")))for(let d of o.evidenceWaits)d.status==="pending"&&d.stepId.endsWith(".verify.report.evidence")&&(d.status="cancelled",c.add(d.stepId));let a=o.actions.some(d=>["pending","running","unknown"].includes(d.status))||o.waits.some(d=>d.status==="pending")||o.evidenceWaits?.some(d=>d.status==="pending");if(c.size&&!a&&!o.ready.length&&!["completed","cancelled"].includes(e.status)){let d=[...o.actions].reverse().find(m=>m.stepId===f.workflow+".build.execute"&&m.status==="succeeded");if(!d)throw new Error("旧 Classic Run 缺少已接受的 Build 来源,原记录保持不变。");let p=f.phase==="build"&&r?r.apply({run:o,event:{kind:"action-outcome",stepId:d.stepId,outcome:d.outcome}}):void 0;p?o.state=p.state:f.phase==="build"&&(o.state=Ct(f,"build-complete").classic);let l=o.actionContexts[d.id];for(let m of p?.next??[f.workflow+".verify.run"])o.ready.push({from:d.stepId,to:typeof m=="string"?m:m.stepId,...typeof m=="string"?{}:{activation:m.input},results:{...l.results,[d.stepId]:{sequence:l.sequence,value:d.outcome.output}}});o.status="running",delete o.reason}o.workflow={id:n.id,version:n.version,hash:i};for(let d of Object.keys(o.definitionHashes))JSON.parse(d)[0]===n.id&&delete o.definitionHashes[d];return o.definitionHashes[JSON.stringify([n.id,n.version])]=i,o}import{randomUUID as bW}from"node:crypto";import mg from"node:path";Yt();ci();import vW from"node:path";async function s_(e){let t=await co(e,{allowPartialProject:!0,allowMissingNativeFields:!0});return t?.native?[vW.posix.join(t.native.artifact_root,"comet","changes")]:[]}function a_(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Yu(e,t){return kW("git",t,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:3e4,maxBuffer:Number.MAX_SAFE_INTEGER,stdio:["ignore","pipe","pipe"]})}function RW(e){let t;try{t=Yu(e,["diff","HEAD","--name-only","--no-renames","-z"])}catch{t=Yu(e,["ls-files","--cached","-z"])}return[...new Set([...t.split("\0"),...Yu(e,["ls-files","--others","--exclude-standard","-z"]).split("\0")].filter(Boolean))]}async function SW(e){let t=await Xr(e);return[".comet",t.openSpecRoot,t.superpowersRoot,...await s_(e)].map(r=>mg.isAbsolute(r)?mg.relative(e,r).replaceAll("\\","/"):r)}async function CW(e){return pr({singleWriter:!0,rootDir:mg.join(await Qr(e),"classic-delivery-baselines")})}async function EW(e){return Jo(e)?{schema:"comet.classic.workspace-baseline.v2",paths:RW(e)}:void 0}async function c_(e,t){let r=await EW(e);if(!r)return t;let n=bW();return await(await CW(e)).compareAndSwap(n,null,{runId:n,revision:1,paths:r.paths}),{...t,workspaceBaseline:{ref:n}}}async function l_(e,t){let r=t.state,n=[...t.actions].reverse().find(m=>m.stepId===r.workflow+".archive.deliver"),i=n?Jn(t,n)?.repairCheckId:void 0,o=o_(t),s=i?t.actions.find(m=>m.id===i):[...t.actions].reverse().find(m=>m.stepId===r.workflow+".archive.preflight");if(s?.status!=="succeeded"||s.outcome?.status!=="succeeded")throw new Error("Classic 交付需要当前成功的 Verify 检查");let c=s.outcome.output,u=o?.output.deliveryInputs,f=c.deliveryPaths?[]:await SW(e),a=(c.deliveryPaths??Object.keys(c.deliveryInputs??u??{})).filter(m=>!a_(m,f)),d=t.evidenceWaits?.slice().reverse().find(m=>m.stepId===r.workflow+".verify.report.evidence"&&m.status==="resolved")?.receipt,p=t.input.changeDir,l=t.outputs[r.workflow+".archive.execute"]?.value?.archiveDirectory;if(r.verificationReport&&!d)throw new Error("Classic 交付缺少已接受的验证报告");return d&&a.push(l?mr(d.ref,p,l):d.ref),hg(e,a)}async function hg(e,t,r){let n=Array.isArray(t)?t:Object.keys(t);for(let o of n)et(o,"Classic delivery path");let i=n.length?Yu(e,["status","--porcelain","--untracked-files=all","--",...n]).trim():"";if(i)throw new Error("Classic 交付路径尚有未提交修改:"+i);return new Set(n)}import{createHash as _W}from"node:crypto";import{execFileSync as wg}from"node:child_process";function gg(e,t,r){let n=wg("git",["remote","get-url",...r?["--push"]:[],t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim();if(!n)throw new Error("Classic delivery remote URL is empty");let i=null;try{i=new URL(n)}catch{}if(i&&(i.password||i.search||i.hash||["http:","https:"].includes(i.protocol)&&i.username))throw new Error("Classic delivery remote must not contain credentials");return n}function d_(e,t){if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/u.test(t))throw new Error("Classic delivery remote must be a configured remote name");let r=gg(e,t,!1),n=gg(e,t,!0);if(r!==n)throw new Error("Classic delivery remote has different fetch and push URLs");return _W("sha256").update(r).digest("hex")}function f_(e,t,r){let n=`refs/heads/${r}`,i=wg("git",["-c","protocol.allow=never","-c","protocol.https.allow=always","-c","protocol.ssh.allow=always","-c","protocol.file.allow=always","ls-remote","--refs",t,n],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4}).trim(),o=/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(i);return o?.[2]===n?o[1]:null}function AW(e){let t=/^git@([^:/]+):([^/]+\/[^/]+)$/u.exec(e);try{let r=new URL(t?`ssh://git@${t[1]}/${t[2]}`:e);if(!["https:","ssh:"].includes(r.protocol)||r.password||r.search||r.hash||r.port||r.protocol==="https:"&&r.username)return null;let n=r.pathname.replace(/\.git\/?$/u,"").replace(/\/$/u,"").split("/").filter(Boolean);return n.length!==2||n.some(i=>!/^[a-zA-Z0-9_.-]+$/u.test(i))?null:`${r.hostname}/${n.join("/")}`.toLowerCase()}catch{return null}}function u_(e,t){try{let r=new URL(e);if(r.protocol!=="https:"||r.username||r.password||r.port||r.search||r.hash)return null;let n=/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/u.exec(r.pathname);return n&&`${r.hostname}/${n[1]}/${n[2]}`.toLowerCase()===t?`https://${r.hostname}/${n[1]}/${n[2]}/pull/${n[3]}`:null}catch{return null}}function p_(e){let t=AW(gg(e.projectRoot,e.remote,!1)),r=t&&u_(e.prUrl,t);if(!t||!r)return!1;let n=wg("gh",["pr","view",r,"--repo",t,"--json","url,headRefName,headRefOid,baseRefName,state"],{cwd:e.projectRoot,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,env:{...process.env,GH_PROMPT_DISABLED:"1",GIT_TERMINAL_PROMPT:"0"}}),i=JSON.parse(n);return typeof i.url=="string"&&u_(i.url,t)===r&&i.headRefName===e.targetBranch&&i.headRefOid===e.commit&&i.baseRefName===e.baseBranch&&(i.state==="OPEN"||i.state==="MERGED")}ye();import Va from"node:path";async function m_(e,t,r){let n=await Xr(e),i=await U(e,t,{label:"Classic Verify report",expected:"file"}),o=Va.relative(n.superpowersReportsDir,i.target);if(!i.exists||!o||o.startsWith(`..${Va.sep}`)||Va.isAbsolute(o)||o.includes(Va.sep)||Va.extname(o).toLowerCase()!==".md")throw new Error("Classic Verify report is outside the configured reports directory");let s=i.relative.replaceAll("\\","/");if(!(await ae(e,s,Number.MAX_SAFE_INTEGER,{label:"Classic Verify report"})).bytes.toString("utf8").trim())throw new Error("Classic Verify report is empty");return{ref:s}}var Xu={type:"array",items:{type:"object",required:["name","result"],additionalProperties:!1,properties:{name:{type:"string",minLength:1},result:{enum:["passed","failed","not-run"]},note:{type:"string",minLength:1}}}},y_={id:"comet-classic-open-revalidate",capabilities:[],supports:e=>e.type==="call_tool"&&e.ref==="classic-open-revalidate",async execute(e,t){if(!t?.projectRoot)throw new Error("Classic Open requires its project root");return{status:"succeeded",output:{contentHash:e.inputHash}}}},yg={id:"comet-classic-open-revalidation",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=e.waits.find(s=>s.stepId==="full.open.confirm"&&s.status==="resolved"&&s.decision?.choice==="approved"),o=r.output;return i&&n?.projectRoot&&t.claim?.executorId===y_.id&&o?.contentHash===t.inputHash?{accepted:!0}:{accepted:!1,reason:"Classic Open has no approval for its current SDK request"}}},vg={id:"comet-classic-design-handoff",version:"1",async validate({run:e,outcome:t,context:r}){if(t.status==="failed")return{accepted:!0};let n=e.input,i=e.state,o=t.output;if(!r?.projectRoot||typeof n.change!="string"||typeof n.changeDir!="string"||typeof o?.proposal!="string"||typeof o.handoffContext!="string")return{accepted:!1,reason:"Classic Design handoff lacks a source-bound context pack"};try{if(o.sourceEvidence||o.requirementsEvidence){let c=await Cg(r.projectRoot,n.changeDir,{run:e}),u=c;if(o.sourceEvidence?.ref!==c.ref||o.requirementsEvidence?.ref!==u.ref)return{accepted:!1,reason:"Classic Design proposal sources changed before submission"}}return{accepted:await Ul({run:e,projectRoot:r.projectRoot,changeDir:hr.join(r.projectRoot,n.changeDir),change:n.change,contextCompression:i.contextCompression,handoffContext:o.handoffContext,handoffHash:typeof o.handoffHash=="string"?o.handoffHash:null}),reason:"Classic Design handoff no longer matches its OpenSpec sources"}}catch(s){return{accepted:!1,reason:s instanceof Error?s.message:String(s)}}}},kg={id:"comet-classic-build-configuration",version:"1",validate({run:e,outcome:t}){if(t.status==="failed")return{accepted:!0};let r=e.state,n=t.output;if(!n||!r.isolation||n.isolation!==r.isolation||n.boundBranch!==r.boundBranch)return{accepted:!1,reason:"Classic Build workspace binding changed in the proposal"};let i={...r,...n},o=zs(i);return o.missingFields.length||o.invalidFields.length?{accepted:!1,reason:"Classic Build configuration is incomplete or invalid"}:{accepted:!0}}},xW={id:"comet-classic-archive-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=n?.projectRoot,o=t.input,s=r.output;if(!i||t.claim?.executorId!=="comet-classic-archive"||typeof o.input?.changeDir!="string"||typeof s?.archiveDirectory!="string")return{accepted:!1,reason:"Classic Archive result lacks its execution identity"};try{let c=await Xr(i),[u,f]=await Promise.all([U(i,o.input.changeDir,{label:"Classic active change",expected:"directory"}),U(i,s.archiveDirectory,{label:"Classic archived change",expected:"directory"})]),a=hr.relative(c.archiveDir,f.target),d=hr.basename(f.target);if(u.exists||!f.exists||hr.dirname(u.target)!==c.changesDir||!a||a.startsWith(`..${hr.sep}`)||hr.isAbsolute(a)||a.includes(hr.sep)||!/^\d{4}-\d{2}-\d{2}-/u.test(d)||d.slice(11)!==hr.basename(u.target))return{accepted:!1,reason:"Classic Archive has not moved the approved change"};let p=await eb(i,f.target);if(p.length>0)return{accepted:!1,reason:p.join(`
180
+ `)};let l=e.actions.find(m=>m.id===t.id);return l?.status==="succeeded"&&l.outcome&&$(l)===$(t)&&$(l.outcome)===$(r)?await Yo(i,e,l,s.archiveDirectory):await r_(i,e,t,s.archiveDirectory,r.artifacts),{accepted:!0}}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}};async function PW(e,t,r,n){let i=hr.relative(e,await Re(hr.join(e,t))).replaceAll("\\","/");if(r!==`M ${i}`)return!1;let o=Gn("git",["show",`HEAD:${i}`],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}),s=await Fe(e,hr.join(e,i),{label:"Classic state file"}),c=(0,Sg.parseDocument)(o,{uniqueKeys:!0}),u=(0,Sg.parseDocument)(s,{uniqueKeys:!0});if(c.errors.length>0||u.errors.length>0)return!1;let f=c.toJS(),a=u.toJS();return!Ir(f[ht],n.runId)||!Ir(a[ht],n.runId)||!Wa(a[ht],Ko(n))&&!Xo(a[ht],n)?!1:(delete f[ht],delete a[ht],Rg(f,a))}var IW={id:"comet-classic-delivery-outcome",version:"1",async validate({run:e,action:t,outcome:r,context:n}){if(r.status==="failed")return{accepted:!0};let i=n?.projectRoot,o=t.stepId.split(".")[0],s=t.input,c=Jn(e,t)?.outputs??s.outputs,u=c?.[`${o}.archive.preflight`],f=c?.[`${o}.archive.execute`],a=r.output;if(!i||!["full","hotfix","tweak"].includes(o)||!u||!a||!["local","push","pr"].includes(String(u.deliveryAction))||a.action!==u.deliveryAction||a.targetBranch!==u.targetBranch||typeof u.baseCommit!="string"||!f||typeof f.archiveDirectory!="string"||typeof s.input?.changeDir!="string"||typeof a.commit!="string"||!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u.test(a.commit))return{accepted:!1,reason:"Classic delivery does not match its approval"};try{let d=Jr(i);if(d!==u.targetBranch)return{accepted:!1,reason:`Classic 当前分支 ${d??"(detached HEAD)"} 与已批准目标 ${String(u.targetBranch)} 不一致`};if(u.deliveryAction!=="local"&&(typeof u.remote!="string"||a.remote!==u.remote||typeof u.remoteIdentity!="string"||d_(i,u.remote)!==u.remoteIdentity))return{accepted:!1,reason:"Classic delivery remote changed after approval"};let p=Gn("git",["rev-parse","HEAD"],{cwd:i,encoding:"utf8"}).trim();if(p!==a.commit)return{accepted:!1,reason:`Classic 当前 HEAD ${p} 与交付提交 ${a.commit} 不一致`};if(!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u.test(u.baseCommit))return{accepted:!1,reason:"Classic 交付缺少有效的已批准基线 baseCommit"};let l=Gn("git",["rev-list","--reverse","--parents",`${u.baseCommit}..${p}`,"--"],{cwd:i,encoding:"utf8"}).trim().split(`
181
+ `).filter(Boolean);if(!l.length)return{accepted:!1,reason:`Classic 已批准基线 ${u.baseCommit} 之后没有交付提交`};let m=u.baseCommit,h=new Set,g=zE(i,l.map(T=>T.split(/\s+/u)[0]));for(let T of l){let[j,...W]=T.split(/\s+/u);if(W.length!==1)return{accepted:!1,reason:`Classic 交付范围包含非线性提交 ${j}(父提交数 ${W.length});只接受从已批准基线 ${u.baseCommit} 连续产生的单父提交`};if(W[0]!==m)return{accepted:!1,reason:`Classic 交付提交 ${j} 的父提交 ${W[0]} 不等于 ${m};交付范围必须从已批准基线 ${u.baseCommit} 连续开始`};let F=g.get(j);for(let oe of F)h.add(oe);m=j}let w=Gn("git",["ls-tree","-r","--name-only","HEAD","--",f.archiveDirectory],{cwd:i,encoding:"utf8"}).trim(),k=Gn("git",["status","--porcelain","--untracked-files=all","--",f.archiveDirectory],{cwd:i,encoding:"utf8"}).trim(),b=s.input.changeDir.replaceAll("\\","/"),S=f.archiveDirectory.replaceAll("\\","/"),O=Ha(e,t).outputs,K=O["full.build.plan"],D=O["full.design.document"]?.designDoc??K?.designEvidence?.ref,Y=K?.plan;if(o==="full"&&(typeof D!="string"||typeof Y!="string"))return{accepted:!1,reason:"Classic Archive documents are missing"};let Q=hr.posix.basename(S),te=typeof D=="string"?mr(D,b,S):null,Z=typeof Y=="string"?mr(Y,b,S):null,Pe=o==="full"?Gn("git",["show",`HEAD:${te}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,ee=o==="full"?Gn("git",["show",`HEAD:${Z}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,he=await l_(i,e),Xe=e.actions.slice().reverse().find(T=>T.stepId===`${o}.archive.execute`&&T.status==="succeeded");if(!Xe)throw new Error("Classic delivery 缺少成功的 Archive Action");let I=await Yo(i,e,Xe,S);for(let T of I.optionalPaths){let j=T.startsWith(`${S}/`)?`${b}/${T.slice(S.length+1)}`:null;if(Gn("git",["ls-tree","-z","HEAD","--",T],{cwd:i,encoding:"utf8"}))I.paths.push(T,...j?[j]:[]);else if(j&&[...g.values()].some(F=>F.includes(j)))throw new Error(`Classic archive commit deletes an optional input without committing the archived copy: ${T}`)}let H=await hg(i,I.paths),ie=T=>he.has(T)||H.has(T)||I.stateFiles.includes(T),Qe=[...h].filter(T=>!ie(T));if(Qe.length)return{accepted:!1,reason:`Classic 交付提交范围包含未批准的路径:${Qe.join(", ")}`};let C=k!==""&&await PW(i,S,k,e);return w?k&&!C?{accepted:!1,reason:`Classic 归档目录与交付 HEAD 不一致:${k}`}:[...h].some(T=>T.startsWith(`${S}/`))?o==="full"&&(!te||!Z||!h.has(te)||!h.has(Z)||!Pe?.includes(`archived-with: ${Q}`)||!Pe.includes("status: final")||!ee?.includes(`archived-with: ${Q}`))?{accepted:!1,reason:`Classic 交付范围缺少已归档的设计或计划,或归档标记不符:${te}, ${Z}`}:u.deliveryAction!=="local"&&f_(i,u.remote,u.targetBranch)!==a.commit?{accepted:!1,reason:"Classic remote branch does not contain the archive commit"}:u.deliveryAction==="pr"&&(typeof a.prUrl!="string"||typeof u.prBaseBranch!="string"||!p_({projectRoot:i,remote:u.remote,prUrl:a.prUrl,targetBranch:u.targetBranch,commit:a.commit,baseBranch:u.prBaseBranch}))?{accepted:!1,reason:"Classic PR does not match the approved delivery"}:{accepted:!0}:{accepted:!1,reason:`Classic 交付范围 ${u.baseCommit}..${p} 未包含归档目录:${S}`}:{accepted:!1,reason:`Classic 交付 HEAD 缺少归档目录:${S}`}}catch(d){return{accepted:!1,reason:d instanceof Error?d.message:String(d)}}}};async function Cg(e,t,r={}){let n=await U(e,t,{label:"Classic change",expected:"directory"});if(!n.exists||r.run&&r.run.input.changeDir!==n.relative)throw new Error("Classic artifacts do not belong to the current change");let i=await Ol(e,n.target);if(i.problems.length)throw new Error(i.problems.join(`
182
+ `));return{ref:n.relative}}async function OW(e,t){let r=et(t,"Classic Design document");if(!(await ae(e,r,Number.MAX_SAFE_INTEGER,{label:"Classic Design document"})).bytes.length)throw new Error("Classic Design document is empty");return{ref:r}}async function NW(e,t,r){if((await Ll(e,t)).status!=="ready")throw new Error("Classic Build plan is not ready");let i=await U(e,t,{label:"Classic Build plan",expected:"file"}),o=await U(e,r,{label:"Classic change",expected:"directory"});if(!i.exists||!o.exists)throw new Error("Classic Build plan or change is missing");return{ref:i.relative}}var h_={id:"comet-classic-open-artifacts",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,o=e.input.changeDir,s=e.actions.slice().reverse().find(c=>c.stepId===i.workflow+".open");if(!n?.projectRoot||t!==o||s?.status!=="succeeded"||r!==s.inputHash)return{accepted:!1,actualHash:"",reason:"Classic Open evidence does not belong to its completed Action"};try{await Cg(n.projectRoot,t,{run:e});let c=await GE(n.projectRoot,t,i.language);if(c)throw new Error(c);return{accepted:!0,actualHash:s.inputHash}}catch(c){return{accepted:!1,actualHash:"",reason:String(c)}}}},TW={id:"comet-classic-design-document",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,o=e.actions.slice().reverse().find(s=>s.stepId==="full.design.document");if(!n?.projectRoot||i.designDoc!==t||o?.status!=="succeeded"||r!==o.inputHash)return{accepted:!1,actualHash:"",reason:"Classic Design evidence does not belong to its completed Action"};try{return await OW(n.projectRoot,t),{accepted:!0,actualHash:o.inputHash}}catch(s){return{accepted:!1,actualHash:"",reason:String(s)}}}},$W={id:"comet-classic-build-plan",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,o=e.actions.slice().reverse().find(s=>s.stepId==="full.build.plan");if(!n?.projectRoot||i.plan!==t||o?.status!=="succeeded"||r!==o.inputHash)return{accepted:!1,actualHash:"",reason:"Classic plan evidence does not belong to its completed Action"};try{return await NW(n.projectRoot,t,String(e.input.changeDir)),{accepted:!0,actualHash:o.inputHash}}catch(s){return{accepted:!1,actualHash:"",reason:String(s)}}}},g_={id:"comet-classic-verification-report",version:"1",async validate({run:e,ref:t,contentHash:r,context:n}){let i=e.state,o=e.actions.slice().reverse().find(s=>s.stepId===i.workflow+".verify.run");if(!n?.projectRoot||i.phase!=="verify"||i.verificationReport!==t||o?.status!=="succeeded"||r!==o.inputHash)return{accepted:!1,actualHash:"",reason:"Classic report does not belong to its completed Verify Action"};try{return await m_(n.projectRoot,t,i.language),{accepted:!0,actualHash:o.inputHash}}catch(s){return{accepted:!1,actualHash:"",reason:String(s)}}}},jW=["workflow","language","phase","contextCompression","buildMode","buildPause","subagentDispatch","tddMode","reviewMode","isolation","boundBranch","verifyMode","autoTransition","baseRef","designDoc","plan","verifyResult","verifyFailures","verificationReport","branchStatus","createdAt","verifiedAt","archiveConfirmation","archived","directOverride","handoffContext","handoffHash","classicProfile","classicMigration"],ln={type:["string","null"]},w_={type:["boolean","null"]},bg={id:"comet-classic-preset-scope",version:"1",async validate({run:e,outcome:t,context:r}){let n=t.output;if(t.status!=="succeeded"||n?.event!=="escalation-requested"||!n.requirementsEvidence)return{accepted:!0};if(!r?.projectRoot)return{accepted:!1,reason:"Classic preset scope requires its project root"};try{let i=await Cg(r.projectRoot,e.input.changeDir,{presetRequirements:!0});return{accepted:n.requirementsEvidence.ref===i.ref,reason:"Classic preset scope changed before the proposal was recorded"}}catch(i){return{accepted:!1,reason:i instanceof Error?i.message:String(i)}}}};function v_(e){let t=e==="full"?null:v_("full"),r=`${e}.open`,n=`${e}.open.evidence`,i=e==="full"?"full.design.handoff":`${e}.build.execute`,o={id:`comet-classic-${e}-transition`,version:"2"},s={id:"comet-classic-open-artifacts",version:"1"};return{executors:e==="full"?[y_]:t.executors,validators:t?.validators??[...e==="full"?[yg,vg,kg]:[],xW,IW,bg],evidenceValidators:t?.evidenceValidators??(e==="full"?[h_,TW,$W,g_]:[h_,g_]),workflow:{id:`comet-classic-${e}`,version:"2",entry:r,stateSchema:{type:"object",required:jW,additionalProperties:!1,properties:{workflow:{enum:e==="full"?["full"]:[e,"full"]},language:{enum:[null,"en","zh-CN"]},phase:{enum:["open","design","build","verify","archive"]},contextCompression:{enum:[null,"off","beta"]},buildMode:{enum:[null,"subagent-driven-development","executing-plans","direct","autonomous"]},buildPause:{enum:[null,"plan-ready"]},subagentDispatch:{enum:[null,"confirmed"]},tddMode:{enum:[null,"tdd","direct"]},reviewMode:{enum:[null,"off","standard","thorough"]},isolation:{enum:[null,"current","branch","worktree"]},boundBranch:ln,verifyMode:{enum:[null,"light","full"]},autoTransition:w_,baseRef:ln,designDoc:ln,plan:ln,verifyResult:{enum:["pending","pass","fail"]},verifyFailures:{type:"integer",minimum:0},checkEpoch:{type:"integer",minimum:0},verificationReport:ln,branchStatus:{enum:[null,"pending","handled"]},createdAt:ln,verifiedAt:ln,archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},directOverride:w_,handoffContext:ln,handoffHash:{anyOf:[{type:"null"},{type:"string",pattern:"^[a-f0-9]{64}$"}]},classicProfile:{enum:[null,"full","hotfix","tweak"]},classicMigration:{enum:[null,1]}}},transitionHandler:o,steps:{[r]:{type:"invoke_skill",ref:e==="full"?"comet-open":`comet-${e}`},[n]:{type:"await_evidence",kind:"classic-open-artifacts",validator:s},...e==="full"?{"full.open.confirm":{type:"ask_user",proposalFrom:[r,n],choices:["approved","rejected"]},"full.open.revalidate":{type:"call_tool",ref:"classic-open-revalidate",validator:{id:yg.id,version:yg.version},outputSchema:{type:"object",required:["contentHash"],properties:{contentHash:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}}}:{},[i]:{type:"invoke_skill",ref:e==="full"?"comet-design":"comet-build",...e==="full"?{validator:{id:vg.id,version:vg.version}}:{validator:{id:bg.id,version:bg.version}},...e==="full"?{outputSchema:{type:"object",required:["proposal"],properties:{proposal:{type:"string",minLength:1},handoffContext:{type:"string",minLength:1},handoffHash:{type:"string",pattern:"^[a-f0-9]{64}$"}}}}:{outputSchema:{type:"object",required:["event"],properties:{event:{enum:["build-complete","escalation-requested"]},proposal:{type:"string",minLength:1},requirementsEvidence:{type:"object",required:["ref","contentHash"],properties:{ref:{type:"string",minLength:1},contentHash:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1},checks:Xu,checksReason:{type:"string",minLength:1}},additionalProperties:!1}}},...e==="full"?{}:{[`${e}.build.escalation-confirm`]:{type:"ask_user",proposalFrom:i,choices:["continue","upgrade"]}},...e==="full"?{"full.design.confirm":{type:"ask_user",proposalFrom:"full.design.handoff",choices:["approved","rejected"]},"full.design.document":{type:"invoke_skill",ref:"comet-design",outputSchema:{type:"object",required:["designDoc"],properties:{designDoc:{type:"string",minLength:1}}}},"full.design.evidence":{type:"await_evidence",kind:"classic-design-document",validator:{id:"comet-classic-design-document",version:"1"}},"full.build.configure":{type:"invoke_skill",ref:"comet-build",validator:{id:kg.id,version:kg.version},outputSchema:{type:"object",required:["buildMode","tddMode","reviewMode","isolation"],properties:{buildMode:{enum:["subagent-driven-development","executing-plans","direct","autonomous"]},tddMode:{enum:["tdd","direct"]},reviewMode:{enum:["off","standard","thorough"]},isolation:{enum:["current","branch","worktree"]},boundBranch:ln,subagentDispatch:{enum:["confirmed",null]},directOverride:{type:"boolean"}},additionalProperties:!1}},"full.build.confirm":{type:"ask_user",proposalFrom:"full.build.configure",choices:["approved","rejected"]},"full.build.plan":{type:"invoke_skill",ref:"comet-build",outputSchema:{type:"object",required:["plan"],properties:{plan:{type:"string",minLength:1},buildPause:{enum:["plan-ready"]}}}},"full.build.plan.evidence":{type:"await_evidence",kind:"classic-build-plan",validator:{id:"comet-classic-build-plan",version:"1"}},"full.build.execute":{type:"invoke_skill",ref:"comet-build",outputSchema:{type:"object",required:["event"],properties:{event:{enum:["build-complete"]},checks:Xu,checksReason:{type:"string",minLength:1}}}},"full.verify.run":{type:"invoke_skill",ref:"comet-verify",outputSchema:{type:"object",required:["event"],properties:{event:{enum:["verification-ready","verify-fail"]},verificationReport:{type:"string",minLength:1},reason:{type:"string",minLength:1},checks:Xu,checksReason:{type:"string",minLength:1}},additionalProperties:!1}},"full.verify.report.evidence":{type:"await_evidence",kind:"classic-verification-report",validator:{id:"comet-classic-verification-report",version:"1"}},"full.archive.prepare":{type:"invoke_skill",ref:"comet-archive",outputSchema:{type:"object",required:["targetBranch","summary"],properties:{targetBranch:{type:"string",minLength:1},remote:{type:"string",minLength:1},prBaseBranch:{type:"string",minLength:1},summary:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},"full.archive.confirm":{type:"ask_user",proposalFrom:"full.archive.prepare",choices:["local","push","pr","reverify","later"]},"full.archive.preflight":{type:"call_tool",ref:"classic-archive-preflight",outputSchema:{type:"object",required:["deliveryAction","targetBranch","verifiedBranch","baseCommit"],properties:{deliveryAction:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},verifiedBranch:{type:"string",minLength:1},baseCommit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},remoteIdentity:{type:"string",pattern:"^[0-9a-f]{64}$"},prBaseBranch:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},"full.archive.execute":{type:"call_tool",ref:"classic-archive",validator:{id:"comet-classic-archive-outcome",version:"1"},outputSchema:{type:"object",required:["archiveDirectory"],properties:{archiveDirectory:{type:"string",minLength:1}},additionalProperties:!1}},"full.archive.deliver":{type:"invoke_skill",ref:"comet-archive",validator:{id:"comet-classic-delivery-outcome",version:"1"},outputSchema:{type:"object",required:["action","targetBranch","commit"],properties:{action:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},commit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},prUrl:{type:"string",minLength:1}},additionalProperties:!1}},"full.build.plan-ready":{type:"ask_user",proposalFrom:"full.build.plan",choices:["continue"]}}:{[`${e}.verify.run`]:{type:"invoke_skill",ref:"comet-verify",outputSchema:{type:"object",required:["event"],properties:{event:{enum:["verification-ready","verify-fail"]},verificationReport:{type:"string",minLength:1},reason:{type:"string",minLength:1},checks:Xu,checksReason:{type:"string",minLength:1}},additionalProperties:!1}},[`${e}.verify.report.evidence`]:{type:"await_evidence",kind:"classic-verification-report",validator:{id:"comet-classic-verification-report",version:"1"}},[`${e}.archive.prepare`]:{type:"invoke_skill",ref:"comet-archive",outputSchema:{type:"object",required:["targetBranch","summary"],properties:{targetBranch:{type:"string",minLength:1},remote:{type:"string",minLength:1},prBaseBranch:{type:"string",minLength:1},summary:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},[`${e}.archive.confirm`]:{type:"ask_user",proposalFrom:`${e}.archive.prepare`,choices:["local","push","pr","reverify","later"]},[`${e}.archive.preflight`]:{type:"call_tool",ref:"classic-archive-preflight",outputSchema:{type:"object",required:["deliveryAction","targetBranch","verifiedBranch","baseCommit"],properties:{deliveryAction:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},verifiedBranch:{type:"string",minLength:1},baseCommit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},remoteIdentity:{type:"string",pattern:"^[0-9a-f]{64}$"},prBaseBranch:{type:"string",minLength:1},deliveryPaths:{type:"array",items:{type:"string",minLength:1}}},additionalProperties:!1}},[`${e}.archive.execute`]:{type:"call_tool",ref:"classic-archive",validator:{id:"comet-classic-archive-outcome",version:"1"},outputSchema:{type:"object",required:["archiveDirectory"],properties:{archiveDirectory:{type:"string",minLength:1}},additionalProperties:!1}},[`${e}.archive.deliver`]:{type:"invoke_skill",ref:"comet-archive",validator:{id:"comet-classic-delivery-outcome",version:"1"},outputSchema:{type:"object",required:["action","targetBranch","commit"],properties:{action:{enum:["local","push","pr"]},targetBranch:{type:"string",minLength:1},commit:{type:"string",pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$"},remote:{type:"string",minLength:1},prUrl:{type:"string",minLength:1}},additionalProperties:!1}}},...t?Object.fromEntries(Object.entries(t.workflow.steps).filter(([c])=>c.startsWith("full.")&&!c.startsWith("full.open"))):{}},transitions:[{from:r,to:n},{from:n,to:e==="full"?"full.open.confirm":i},...e==="full"?[{from:"full.open.confirm",to:"full.open.revalidate",on:"approved"},{from:"full.open.confirm",to:r,on:"rejected"},{from:"full.open.revalidate",to:i},{from:"full.open.revalidate",to:r}]:[{from:i,to:`${e}.build.escalation-confirm`},{from:`${e}.build.escalation-confirm`,to:i,on:"continue"},{from:`${e}.build.escalation-confirm`,to:"full.design.handoff",on:"upgrade"},{from:`${e}.verify.run`,to:`${e}.verify.report.evidence`},{from:`${e}.verify.run`,to:`${e}.build.execute`},{from:`${e}.archive.prepare`,to:`${e}.archive.confirm`},{from:`${e}.archive.confirm`,to:`${e}.archive.preflight`,on:"local"},{from:`${e}.archive.confirm`,to:`${e}.archive.preflight`,on:"push"},{from:`${e}.archive.confirm`,to:`${e}.archive.preflight`,on:"pr"},{from:`${e}.archive.confirm`,to:`${e}.verify.run`,on:"reverify"},{from:`${e}.archive.confirm`,to:`${e}.archive.confirm`,on:"later"},{from:`${e}.archive.preflight`,to:`${e}.archive.execute`},{from:`${e}.archive.execute`,to:`${e}.archive.deliver`}],...e==="full"?[{from:"full.design.handoff",to:"full.design.confirm"},{from:"full.design.confirm",to:"full.design.document",on:"approved"},{from:"full.design.confirm",to:"full.design.handoff",on:"rejected"},{from:"full.design.document",to:"full.design.evidence"},{from:"full.design.evidence",to:"full.build.configure"},{from:"full.build.configure",to:"full.build.confirm"},{from:"full.build.confirm",to:"full.build.plan",on:"approved"},{from:"full.build.confirm",to:"full.build.configure",on:"rejected"},{from:"full.build.plan",to:"full.build.plan.evidence"},{from:"full.build.plan.evidence",to:"full.build.execute"},{from:"full.build.plan.evidence",to:"full.build.plan-ready"},{from:"full.build.plan-ready",to:"full.build.plan.evidence",on:"continue"},{from:"full.verify.run",to:"full.verify.report.evidence"},{from:"full.verify.run",to:"full.build.plan"},{from:"full.archive.prepare",to:"full.archive.confirm"},{from:"full.archive.confirm",to:"full.archive.preflight",on:"local"},{from:"full.archive.confirm",to:"full.archive.preflight",on:"push"},{from:"full.archive.confirm",to:"full.archive.preflight",on:"pr"},{from:"full.archive.confirm",to:"full.verify.run",on:"reverify"},{from:"full.archive.confirm",to:"full.archive.confirm",on:"later"},{from:"full.archive.preflight",to:"full.archive.execute"},{from:"full.archive.execute",to:"full.archive.deliver"}]:[],...t?t.workflow.transitions?.filter(c=>c.from.startsWith("full.")&&!c.from.startsWith("full.open"))??[]:[],{from:`${e}.build.execute`,to:`${e}.verify.run`},{from:`${e}.verify.report.evidence`,to:`${e}.archive.prepare`}]},transitionHandler:{...o,apply({run:c,event:u}){if(u.kind==="action-outcome"&&u.outcome.status==="succeeded"&&(u.stepId.endsWith(".build.execute")||u.stepId.endsWith(".verify.run"))){let a=u.outcome.output;if(["build-complete","verification-ready"].includes(a.event??"")){let d=c.actions.find(p=>p.id===u.outcome.actionId);(d?.executionOrigin?.workflow.version!=="1"||d.status!=="succeeded"||c.outputs[u.stepId]?.sequence!==c.actionContexts[d.id]?.sequence||!Rg(c.outputs[u.stepId]?.value,d.outcome?.output)||!Rg(d.outcome,u.outcome))&&Eg(a)}}if(u.kind==="action-outcome"&&u.outcome.status==="failed"&&c.actions.find(d=>d.id===u.outcome.actionId)?.type==="invoke_skill")return{state:c.state,next:[]};if(t&&u.stepId.startsWith("full."))return t.transitionHandler.apply({run:c,event:u});if(e!=="full"&&u.kind==="wait-resolved"&&u.stepId===`${e}.build.escalation-confirm`){if(u.choice==="continue")return{state:c.state,next:[i]};if(u.choice!=="upgrade")throw new Error("Classic preset escalation choice is invalid");let a=c.state;return{state:{...Ct(a,"preset-escalate").classic,isolation:a.isolation,boundBranch:a.boundBranch},next:["full.design.handoff"]}}if(e!=="full"&&u.kind==="action-outcome"&&u.stepId===i){let a=u.outcome.output;if(u.outcome.status==="succeeded"&&a.event==="escalation-requested"&&typeof a.proposal=="string"&&a.proposal.trim())return{state:c.state,next:[`${e}.build.escalation-confirm`]};if(u.outcome.status!=="succeeded"||a.event!=="build-complete")throw new Error("Classic preset Build result does not match its declared transition");return{state:Ct(c.state,"build-complete").classic,next:[`${e}.verify.run`]}}if(e!=="full"&&u.kind==="action-outcome"&&u.stepId===`${e}.verify.run`){let a=u.outcome.output;if(u.outcome.status==="succeeded"&&a.event==="verify-fail"){if(typeof a.reason!="string"||!a.reason.trim())throw new Error("Classic preset Verify failure requires a reason");return{state:Ct(c.state,"verify-fail").classic,next:[`${e}.build.execute`]}}if(u.outcome.status!=="succeeded"||a.event!=="verification-ready"||typeof a.verificationReport!="string")throw new Error("Classic preset Verify report did not complete");return{state:{...c.state,verificationReport:a.verificationReport},next:[`${e}.verify.report.evidence`]}}if(e!=="full"&&u.kind==="evidence-recorded"&&u.stepId===`${e}.verify.report.evidence`){if(u.ref!==c.state.verificationReport)throw new Error("Classic preset Verify report evidence does not match");return{state:Ct(c.state,"verify-pass").classic,next:[`${e}.archive.prepare`]}}if(e!=="full"&&u.kind==="action-outcome"&&u.stepId===`${e}.archive.prepare`){if(u.outcome.status!=="succeeded")throw new Error("Classic preset Archive preparation did not complete");return{state:c.state,next:[`${e}.archive.confirm`]}}if(u.kind==="action-outcome"&&u.stepId===r){if(u.outcome.status!=="succeeded"||u.outcome.output?.event!=="open-complete")throw new Error("Classic Open result does not match its declared transition");return{state:c.state,next:[n]}}if(e==="full"&&u.kind==="wait-resolved"&&u.stepId==="full.open.confirm")return{state:c.state,next:[u.choice==="approved"?"full.open.revalidate":r]};if(e==="full"&&u.kind==="action-outcome"&&u.stepId==="full.open.revalidate"){if(u.outcome.status!=="succeeded")throw new Error("Classic Open revalidation did not complete");return{state:Ct(c.state,"open-complete").classic,next:[i]}}if(e==="full"&&u.kind==="action-outcome"&&u.stepId===i){if(u.outcome.status!=="succeeded")throw new Error("Classic Design handoff did not succeed");let a=u.outcome.output;return{state:{...c.state,...c.commands?.some(d=>d.name==="revise-design"&&d.actionId===u.outcome.actionId)?{phase:"design",verifyResult:"pending",verifiedAt:null,archiveConfirmation:null}:{},...a.handoffContext?{handoffContext:a.handoffContext,handoffHash:a.handoffHash??null}:{}},next:["full.design.confirm"]}}if(e==="full"&&u.kind==="wait-resolved"&&u.stepId==="full.design.confirm")return{state:c.state,next:[u.choice==="approved"?"full.design.document":"full.design.handoff"]};if(e==="full"&&u.kind==="action-outcome"&&u.stepId==="full.design.document"){if(u.outcome.status!=="succeeded")throw new Error("Classic Design document work did not succeed");let a=u.outcome.output.designDoc;return{state:{...c.state,designDoc:a},next:["full.design.evidence"]}}if(e==="full"&&u.kind==="evidence-recorded"&&u.stepId==="full.design.evidence"){if(u.ref!==c.state.designDoc)throw new Error("Classic Design evidence does not match the selected document");return{state:Ct(c.state,"design-complete").classic,next:[c.commands?.some(d=>d.name==="revise-design"&&["build","verify","archive"].includes(c.actions.find(p=>p.id===d.actionId)?.input?.activation?.fromPhase??""))?"full.build.plan":"full.build.configure"]}}if(e==="full"&&u.kind==="action-outcome"&&u.stepId==="full.build.configure"){if(u.outcome.status!=="succeeded")throw new Error("Classic Build configuration did not succeed");return{state:c.state,next:["full.build.confirm"]}}if(e==="full"&&u.kind==="wait-resolved"&&u.stepId==="full.build.confirm"){if(u.choice==="rejected")return{state:c.state,next:["full.build.configure"]};let d=c.waits.find(g=>g.stepId==="full.build.confirm"&&g.decision?.id===u.decisionId&&g.proposalHash===u.proposalHash)?.proposal?.outputs?.["full.build.configure"],p=c.outputs["full.build.configure"]?.value;if(u.choice!=="approved"||d===void 0||p===void 0||$(d)!==$(p))throw new Error("Classic Build confirmation no longer matches the proposed choices");let l=d,m={...c.state,...l},h=zs(m);if(m.isolation===null||h.missingFields.length>0||h.invalidFields.length>0)throw new Error("Classic Build configuration is incomplete or invalid");return{state:m,next:["full.build.plan"]}}if(e==="full"&&u.kind==="action-outcome"&&u.stepId==="full.build.plan"){if(u.outcome.status!=="succeeded")throw new Error("Classic Build plan work did not succeed");let{plan:a,buildPause:d}=u.outcome.output;return{state:{...c.state,plan:a,buildPause:d??null},next:["full.build.plan.evidence"]}}if(e==="full"&&u.kind==="evidence-recorded"&&u.stepId==="full.build.plan.evidence"){if(u.ref!==c.state.plan)throw new Error("Classic Build plan evidence does not match the selected plan");return{state:c.state,next:[c.state.buildPause==="plan-ready"?"full.build.plan-ready":"full.build.execute"]}}if(e==="full"&&u.kind==="wait-resolved"&&u.stepId==="full.build.plan-ready"){if(u.choice!=="continue")throw new Error("Classic Build continuation requires explicit user choice");return{state:{...c.state,buildPause:null},next:["full.build.plan.evidence"]}}if(e==="full"&&u.kind==="action-outcome"&&u.stepId==="full.build.execute"){if(u.outcome.status!=="succeeded"||u.outcome.output?.event!=="build-complete")throw new Error("Classic Build work did not complete");return{state:Ct(c.state,"build-complete").classic,next:[`${e}.verify.run`]}}if(e==="full"&&u.kind==="action-outcome"&&u.stepId==="full.verify.run"){if(u.outcome.status!=="succeeded")throw new Error("Classic Verify assessment did not complete");let a=u.outcome.output;if(a.event==="verify-fail"){if(!a.reason?.trim())throw new Error("Classic Verify failure requires a reason");return{state:Ct(c.state,"verify-fail").classic,next:["full.build.plan"]}}if(a.event!=="verification-ready"||!a.verificationReport)throw new Error("Classic Verify report path is missing");return{state:{...c.state,verificationReport:a.verificationReport},next:["full.verify.report.evidence"]}}if(e==="full"&&u.kind==="evidence-recorded"&&u.stepId==="full.verify.report.evidence"){if(u.ref!==c.state.verificationReport)throw new Error("Classic Verify evidence does not match the selected report");return{state:Ct(c.state,"verify-pass").classic,next:[`${e}.archive.prepare`]}}if(e==="full"&&u.kind==="action-outcome"&&u.stepId==="full.archive.prepare"){if(u.outcome.status!=="succeeded")throw new Error("Classic Archive preparation did not complete");return{state:c.state,next:["full.archive.confirm"]}}if(u.kind==="wait-resolved"&&u.stepId===`${e}.archive.confirm`){if(u.choice==="reverify")return{state:Ct(c.state,"archive-reopen").classic,next:[`${e}.verify.run`]};if(u.choice==="later")return{state:c.state,next:[`${e}.archive.confirm`]};let d=c.waits.find(g=>g.stepId===`${e}.archive.confirm`&&g.decision?.id===u.decisionId&&g.proposalHash===u.proposalHash)?.proposal?.outputs?.[`${e}.archive.prepare`],p=c.outputs[`${e}.archive.prepare`]?.value;if(d===void 0||p===void 0||$(d)!==$(p))throw new Error("Classic Archive choice no longer matches its proposal");let l=d,m=c.state;if(!["local","push","pr"].includes(u.choice)||!m.boundBranch||l.targetBranch!==m.boundBranch||u.choice!=="local"&&!l.remote||u.choice==="pr"&&!l.prBaseBranch)throw new Error("Classic Archive target does not match the bound branch or delivery");return{state:Ct(m,"archive-confirm").classic,next:[`${e}.archive.preflight`]}}if(u.kind==="action-outcome"&&u.stepId===`${e}.archive.preflight`){if(u.outcome.status!=="succeeded")throw new Error("Classic Archive preflight did not pass");let a=c.waits.slice().reverse().find(l=>l.stepId===`${e}.archive.confirm`&&l.status==="resolved"&&["local","push","pr"].includes(l.decision?.choice??"")),d=a?.proposal?.outputs?.[`${e}.archive.prepare`],p=u.outcome.output;if(!a||!d||a.decision?.choice!==p.deliveryAction||d.targetBranch!==p.targetBranch||a.decision?.choice==="pr"&&d.prBaseBranch!==p.prBaseBranch||p.targetBranch!==p.verifiedBranch||p.targetBranch!==c.state.boundBranch)throw new Error("Classic Archive preflight no longer matches the approved target");return{state:c.state,next:[`${e}.archive.execute`]}}if(u.kind==="action-outcome"&&u.stepId===`${e}.archive.execute`){if(u.outcome.status!=="succeeded")return{state:c.state,next:[]};let a=Ct(c.state,"archived"),d=c.input.changeDir.replaceAll("\\","/"),p=u.outcome.output.archiveDirectory.replaceAll("\\","/");return{state:{...a.classic,designDoc:mr(a.classic.designDoc,d,p),plan:mr(a.classic.plan,d,p),verificationReport:mr(a.classic.verificationReport,d,p),handoffContext:mr(a.classic.handoffContext,d,p)},next:[`${e}.archive.deliver`]}}if(u.kind==="action-outcome"&&u.stepId===`${e}.archive.deliver`)return u.outcome.status!=="succeeded"?{state:c.state,next:[]}:{state:{...c.state,branchStatus:"handled"},next:[]};if(u.kind!=="evidence-recorded"||u.stepId!==n||u.evidenceKind!=="classic-open-artifacts")throw new Error("Classic Open evidence does not match its declared transition");return e==="full"?{state:c.state,next:["full.open.confirm"]}:{state:Ct(c.state,"open-complete").classic,next:[i]}}}}}function Eg(e){if(!Array.isArray(e.checks)||!e.checks.length&&!e.checksReason?.trim()||e.checks.some(t=>!t.name?.trim()||!["passed","not-run"].includes(t.result)||t.result==="not-run"&&!t.note?.trim()))throw new Error("Classic completion requires actual check reports; explain checks not run and resolve failed checks before acceptance")}var Qo=v_;import{AsyncLocalStorage as VW}from"node:async_hooks";function Qu(e,t){let r=e.state;return(t==="hotfix"||t==="tweak")&&e.workflow.id===`comet-classic-${t}`&&r?.workflow==="full"&&r.classicProfile==="full"&&e.waits.some(n=>n.stepId===`${t}.build.escalation-confirm`&&n.status==="resolved"&&n.decision?.choice==="upgrade"&&n.decision.proposalHash===n.proposalHash)}function Zu(e){return e.ref==="classic-archive"&&(e.status==="running"||e.status==="unknown"||e.status==="cancelled"&&!!e.claim&&!e.outcome)}function ed(e){return e.status==="cancelled"&&e.children.length===0&&e.actions.every(t=>!["pending","running","unknown"].includes(t.status)&&!Zu(t))&&e.waits.every(t=>t.status!=="pending")&&(e.evidenceWaits??[]).every(t=>t.status!=="pending")&&e.ready.length===0}hl();import{AsyncLocalStorage as qW}from"node:async_hooks";import{createHash as LW,randomUUID as b_}from"node:crypto";import Ag from"node:path";import{promises as td}from"node:fs";import _g from"node:path";async function rd(e,t){let r=Np(e),n=_g.join(r.workspaceRoot,"observability"),i=r.dataRoot;for(let s of["","workspaces",r.workspaceId,"observability"]){i=_g.join(i,s);let c;try{c=await td.lstat(i)}catch(u){if(!t||u.code!=="ENOENT")throw u;await td.mkdir(i,{recursive:s===""}).catch(f=>{if(f.code!=="EEXIST")throw f}),c=await td.lstat(i)}if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let o=_g.join(n,"performance.sqlite");for(let s of["","-wal","-shm"])try{let c=await td.lstat(o+s);if(!c.isFile()||c.isSymbolicLink()||c.size>64*1024*1024)throw new Error("Runtime 统计文件无效")}catch(c){if(c.code!=="ENOENT")throw c}return o}import{stripVTControlCharacters as DW}from"node:util";function k_(e,t=process.env){let r=DW(e).replace(/(Bearer\s+)[^\s"']+/giu,"$1[redacted]").replace(/((?:api[_-]?key|auth[_-]?token|access[_-]?token|_authToken|password|secret)\s*[=:]\s*["']?)[^\s"',}]+/giu,"$1[redacted]").replace(/(https?:\/\/[^\s/:]+:)[^\s@]+@/giu,"$1[redacted]@");for(let[n,i]of Object.entries(t))i&&i.length>=6&&/key|token|password|secret|credential/iu.test(n)&&(r=r.split(i).join("[redacted]"));return r}var MW=864e5,WW=1e4,nd=new qW;function xg(e){let t=nd.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function Ba(e,t){return k_(e).slice(0,t)}async function id(e,t){if(!t.length)return;let r=nd.getStore();if(r){let i=o=>process.platform==="win32"?Ag.resolve(o).toLowerCase():Ag.resolve(o);if(i(e)===i(await r.projectRoot())){r.spans.push(...t);return}}let n=Uo(await rd(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
183
+ CREATE TABLE IF NOT EXISTS trace_spans (
184
+ id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
185
+ change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
186
+ parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
187
+ started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
188
+ revision INTEGER NOT NULL, data TEXT NOT NULL);
189
+ CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
190
+ CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
191
+ BEGIN IMMEDIATE;`);let i=n.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
192
+ ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
193
+ started_at=COALESCE(trace_spans.started_at,excluded.started_at),
194
+ ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
195
+ WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
196
+ ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
197
+ revision=MAX(trace_spans.revision,excluded.revision),
198
+ data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
199
+ WHERE excluded.revision >= trace_spans.revision OR (trace_spans.started_at IS NULL AND excluded.started_at IS NOT NULL)`),o=t.length>1e3?[...t.filter(s=>s.parentSpanId===null),...t.filter(s=>s.parentSpanId!==null).slice(-999)].slice(0,1e3):t;for(let s of o){if(!s.change||!s.runId||!s.traceId||!s.spanId||s.change.length>240||s.runId.length>240||s.traceId.length>512||s.spanId.length>512||(s.parentSpanId?.length??0)>512)continue;let c={...s,name:Ba(s.name,240),summary:s.summary?Ba(s.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(s.attributes??{}).slice(0,20).map(([a,d])=>[Ba(a,80),Array.isArray(d)?d.slice(0,30).map(p=>Ba(p,240)):typeof d=="string"?Ba(d,2e3):d]))};t.length>1e3&&s.parentSpanId===null&&(c.attributes.truncated=!0);let u=JSON.stringify(c);for(;Buffer.byteLength(u,"utf8")>4096;){let a=Object.keys(c.attributes).reverse().find(d=>d!=="truncated");if(a)delete c.attributes[a];else if(c.summary)c.summary=c.summary.slice(0,Math.floor(c.summary.length*.75));else break;u=JSON.stringify(c)}if(Buffer.byteLength(u,"utf8")>4096)continue;let f=LW("sha256").update(JSON.stringify([s.traceId,s.spanId])).digest("hex");i.run(f,s.traceId,s.workflow,s.change,s.runId,s.spanId,s.parentSpanId,s.kind,c.name,s.status,s.startedAt,s.endedAt,s.updatedAt,s.revision,u)}n.prepare("DELETE FROM trace_spans WHERE updated_at < ?").run(new Date(Date.now()-7*MW).toISOString()),n.prepare("DELETE FROM trace_spans WHERE id IN (SELECT id FROM trace_spans ORDER BY updated_at DESC, id DESC LIMIT -1 OFFSET ?)").run(WW),n.exec("COMMIT")}finally{n.close()}}async function R_(e,t){let r=nd.getStore(),n=r?.binding.workflow===e.workflow?r:void 0;if(n)try{let p=(await Promise.all([e.projectRoot(),n.projectRoot()])).map(l=>{let m=Ag.resolve(l);return process.platform==="win32"?m.toLowerCase():m});(p[0]!==p[1]||e.runId&&n.binding.runId&&e.runId!==n.binding.runId)&&(n=void 0)}catch{n=void 0}let i=new Date().toISOString(),o={traceId:n?.traceId??b_(),spanId:b_(),binding:n?.binding??{workflow:e.workflow,change:e.change,runId:e.runId},spans:n?.spans??[],startedAt:i,kind:e.kind,name:e.name,projectRoot:e.projectRoot,parent:n};if(o.binding.change&&o.binding.runId){let d=[];for(let p=o;p;p=p.parent)d.push({traceId:p.traceId,spanId:p.spanId,parentSpanId:p.parent?.spanId??null,workflow:o.binding.workflow,change:o.binding.change,runId:o.binding.runId,kind:p.kind,name:p.name,status:"running",startedAt:p.startedAt,endedAt:null,updatedAt:i,revision:0});try{await id(await e.projectRoot(),d)}catch{}}let s,c,u=!1;try{s=await nd.run(o,t)}catch(d){u=!0,c=d}let f=new Date().toISOString(),a=u?"failed":"succeeded";try{!u&&e.status&&(a=e.status(s))}catch{a="unknown"}if(o.binding.change&&o.binding.runId&&o.spans.push({traceId:o.traceId,spanId:o.spanId,parentSpanId:n?.spanId??null,workflow:o.binding.workflow,change:o.binding.change,runId:o.binding.runId,kind:e.kind,name:e.name,startedAt:i,endedAt:f,updatedAt:f,revision:1,status:a}),!n&&o.spans.length)try{await id(await e.projectRoot(),o.spans)}catch{}if(u)throw c;return s}var FW=(e,t)=>`workflow:${e}:${t}`,S_=(e,t)=>{let r=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(r[0])?r[1]??r[0]:r[0]},C_=e=>({runId:e.runId,revision:e.revision,status:e.status,actions:e.actions.map(t=>({id:t.id,attempt:t.attempt,status:t.status,reason:t.reason,...t.outcome?{outcome:{outcomeId:t.outcome.outcomeId,summary:t.outcome.summary}}:{}})),waits:e.waits.map(t=>({id:t.id,status:t.status})),evidenceWaits:e.evidenceWaits?.map(t=>({id:t.id,status:t.status}))}),E_=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function HW(e){let{workflow:t,previous:r,next:n,initial:i,observedAt:o}=e,s=FW(t,n.runId),c=`run:${n.runId}`,u={workflow:t,change:n.runId,runId:n.runId,traceId:s,updatedAt:o,revision:n.revision},f=["completed","failed","cancelled"].includes(n.status),a=new Map(r?.actions.map(p=>[`${p.id}:${p.attempt}`,p])),d=[{...u,spanId:c,parentSpanId:null,kind:"workflow",name:n.workflow.id,status:n.status==="completed"?"succeeded":n.status,startedAt:i?o:null,endedAt:f&&(i||r!==null&&r.status!==n.status)?o:null,summary:n.reason,attributes:{workflowVersion:n.workflow.version,sequence:n.sequence,parentRunIds:n.lineage,childRunIds:n.children.map(p=>p.runId)}}];for(let p of n.actions){let l=a.get(`${p.id}:${p.attempt}`);if(l&&l.status===p.status&&l.outcome?.outcomeId===p.outcome?.outcomeId&&l.reason===p.reason&&l.outcome?.summary===p.outcome?.summary)continue;let m=["succeeded","failed","cancelled"].includes(p.status);d.push({...u,spanId:`action:${p.id}:${p.attempt}`,parentSpanId:c,kind:"action",name:p.stepId,status:p.status,attempt:p.attempt,startedAt:p.status==="running"&&(l?.status==="pending"||i)?o:null,endedAt:m&&(i||r!==null)?o:null,summary:p.outcome?.summary??p.reason,attributes:{phase:S_(p.stepId,t),actionId:p.id,actionType:p.type,ref:p.ref??null,executor:p.claim?.executorId??null,inputFields:E_(p.input),outputFields:p.outcome?E_(p.outcome.output):[],artifacts:(p.outcome?.artifacts??[]).map(h=>h.uri)}})}for(let p of["wait","evidence"]){let l=p==="wait"?n.waits:n.evidenceWaits??[],m=p==="wait"?r?.waits:r?.evidenceWaits,h=new Map(m?.map(g=>[g.id,g]));for(let g of l){let w=h.get(g.id);w?.status!==g.status&&d.push({...u,spanId:`${p}:${g.id}`,parentSpanId:c,kind:p,name:g.stepId,status:g.status==="pending"?"waiting":g.status==="resolved"?"succeeded":g.status==="cancelled"?"cancelled":"unknown",startedAt:!w&&(r!==null||i)&&g.status==="pending"?o:null,endedAt:g.status!=="pending"&&(i||r!==null)?o:null,attributes:{phase:S_(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return d}function __(e,t,r){let n=null;return{...r,...r.restoreCheckpoint?{restoreCheckpoint:(i,o,s)=>r.restoreCheckpoint(i,o,s)}:{},async read(i){let o=await r.read(i);try{n=o?C_(o):null}catch{n=null}return o&&xg({workflow:t,change:o.runId,runId:o.runId}),o},async compareAndSwap(i,o,s){let c=n?.runId===i&&n.revision===o?n:null,u=await r.compareAndSwap(i,o,s);if(u){xg({workflow:t,change:i,runId:i});try{await id(e,HW({workflow:t,previous:c,next:s,initial:o===null,observedAt:new Date().toISOString()}))}catch{}try{n=C_(s)}catch{n=null}}return u}}}import{promises as BW}from"node:fs";var Ua=Tt(Gt(),1);import{createHash as UW}from"node:crypto";import Ki from"node:path";import{isDeepStrictEqual as KW}from"node:util";var A_=new Set(["language","contextCompression","autoTransition","reviewMode"]);var x_=new VW;function JW(e){return["completed","cancelled","failed"].includes(e.status)||e.waits.some(t=>t.status==="pending")||e.actions.some(t=>["pending","running","unknown"].includes(t.status)&&(t.type==="invoke_skill"||t.status==="unknown"||t.type==="call_tool"&&!["classic-open-revalidate","classic-archive-preflight"].includes(t.ref??"")))}function gr(e,t){return KW(e,t)}function P_(e,t){return Object.keys(e).filter(r=>!gr(e[r],t[r]))}function Pg(e){return e.actions.some(Zu)}function Yn(e,t={},r=!1){let n=Wt(e),i=!1,o=async(p=t.readOnly)=>{if(!p&&Wt(e)!==n)throw new Error("Classic SDK workspace identity changed; reload the store in the current workspace");return!p&&!i&&(await qr(e),i=!0),n},s=__(e,"classic",t.store??pr({singleWriter:!0,rootDir:Ki.join(n,"sdk-runs","classic")})),c=p=>JSON.stringify([n,p]);function u(p,l){if(t.identity){let h=["runtime","dispatch","--application-file",Ki.join(t.identity.packageRoot,"application.json"),"--project-root",e,"--request","<recovery-request.json>","--json"];throw new Error(`Classic SDK Run ${p} requires recovery: ${l}. Save the recovery request JSON to a file and replace <recovery-request.json> with its path. Run comet with the exact argument array below to restore the recorded state and advance only the Runtime, without executing host work.
200
+ Recovery argv: ${JSON.stringify(h)}
201
+ Recovery request: ${JSON.stringify({operation:"next",runId:p})}`)}let m=`Run comet state next ${p} --json`;throw new Error(`Classic SDK Run ${p} requires recovery: ${l}. ${m} in ${e} to restore or synchronize its recorded state.`)}async function f(p,l){let m=null;for(let Q of await kr(e,p)){let te;try{te=await Fe(e,Q,{label:"Classic state file"})}catch(Z){if(Z.code==="ENOENT")continue;throw Z}if(At(te)){if(m)throw new Error(`Classic change ${p} has multiple SDK state files`);m={file:Q,source:te}}}if(!m)return null;let h=(0,Ua.parseDocument)(m.source,{uniqueKeys:!0});if(h.errors.length>0)throw new Error(`Invalid Classic state file: ${h.errors[0].message}`);let g=h.toJS(),w=Ir(g[ht],p,{preserveSourceRevision:!0});if(!w)return null;if($(g.application_checkpoint??null)!==$(t.identity??null))throw new Error("Classic portable checkpoint requires its original fixed Application package");let k=Mt(g).classic,b=w.input,S=w.workflow.id.replace(/^comet-classic-/u,""),E=k?P_(w.state,k):[],O=typeof b?.changeDir=="string"?await Re(Ki.join(e,...b.changeDir.split("/"))):null,K=O!==null&&m.file!==O;if(!k||E.some(Q=>!A_.has(Q))||b?.change!==p||b.changeDir!==`openspec/changes/${p}`&&b.changeDir!==`docs/openspec/changes/${p}`||K&&!k.archived&&!Pg(w)||!["full","hotfix","tweak"].includes(S)||w.workflow.id!==`comet-classic-${S}`||k.workflow!==S&&!Qu(w,S)||!t.allowBranchRebind&&k.boundBranch!==null&&k.boundBranch!==Jr(e))throw new Error(`Classic portable Run checkpoint for ${p} does not match its state`);let D=w.revision,Y={...w,revision:D,...l?{state:k}:{}};if(l&&$(l)!==$({...Y,revision:1}))throw new Error(`Classic SDK Run ${p} differs from the interrupted checkpoint import; preserve the local records and restore matching Run history before continuing`);if((D>1||l)&&!s.restoreCheckpoint)throw new Error(`Classic RuntimeStore cannot restore checkpoint revision ${D}; use a store with restoreCheckpoint support or restore the original Run history`);return await ta(e,{schema:Si,workflow:"classic",change:p,format:"sdk",application:t.identity?.id??`classic-${S}`,runId:p}),D===1&&!l?await s.compareAndSwap(p,null,Y):await s.restoreCheckpoint(p,l?1:null,Y),s.read(p)}async function a(p){let l=p.input;if(l?.change!==p.runId||typeof l.changeDir!="string")throw new Error(`Classic SDK Run ${p.runId} has invalid change identity`);let m=l.changeDir.replaceAll("\\","/");if(m!==`openspec/changes/${p.runId}`&&m!==`docs/openspec/changes/${p.runId}`)throw new Error(`Classic SDK Run ${p.runId} has invalid change directory`);let h=Ki.join(e,...m.split("/"));try{if((await BW.stat(h)).isDirectory())return Re(h)}catch(b){if(b.code!=="ENOENT")throw b}if(!p.state.archived&&!Pg(p))return null;let g=Ki.join(Ki.dirname(h),"archive"),w=await xl(e,g,p.runId);if(w===null)return null;let k=w.filter(b=>b!==p.runId);if(k.length!==1)throw new Error(`Classic SDK Archive ${p.runId} is ambiguous`);return Re(Ki.join(g,k[0]))}async function d(p,l){return await kr(e,p),await o(),(async()=>{let h;if(r)try{h=(await xo(s,p)).record}catch(ee){if(ee.code!=="RUN_NOT_FOUND")throw ee;h=null}else h=await s.read(p);if(!h){t.readOnly&&u(p,"the recorded Run is missing or incomplete");let ee=await Ls(()=>f(p,h??void 0));if(h&&!ee)throw new Error(`Classic SDK Run ${p} requires its matching portable checkpoint or original Run history before completing recovery`);h=ee}if(!h)return null;let g=h,w=g.state,k=await a(g),b=g.revision===1&&g.actions.every(ee=>ee.status==="pending"&&!ee.claim);if(!k)return t.readOnly&&!b&&u(p,"the change directory is missing"),g;let S;try{S=await Fe(e,k,{label:"Classic state file"})}catch(ee){if(ee.code!=="ENOENT")throw ee;S=null}let E=S===null?new Ua.Document:(0,Ua.parseDocument)(S,{uniqueKeys:!0});if(E.errors.length>0)throw new Error(`Invalid Classic state file: ${E.errors[0].message}`);let O=E.toJS(),K=S===null?null:Mt(O).classic,D=Xo(O?.[ht],g,{projection:r});if(D)return(S===null||!At(S)||!gr(K,D.state)||t.identity&&!gr(O.application_checkpoint,t.identity))&&u(p,"the immutable archived delivery checkpoint has changed"),g;if(K){let ee=Ir(O?.[ht],p,{preserveSourceRevision:!0});if(g.revision===1&&ee&&ee.revision>g.revision){t.readOnly&&u(p,"the initial checkpoint import is incomplete");let I=await f(p,g);I||u(p,"the initial checkpoint import is incomplete"),g=I,w=g.state}let he=ee?.state??w,Xe=P_(he,K);if(Xe.some(I=>!A_.has(I))){let I=g.input?.recoverySourceHash,H=g.revision===1&&typeof I=="string"&&S!==null&&UW("sha256").update(S).digest("hex")===I;if(!gr(K,w)&&!H)throw new Error(`Classic state file ${k} changed a Runtime-owned field`)}else if(Xe.some(I=>!gr(w[I],K[I]))){if(!l)throw new Error(`Classic state file ${k} changed during an SDK transition`);for(let H of Xe)if(!gr(w[H],he[H])&&!gr(w[H],K[H]))throw new Error(`Classic state file ${k} conflicts with SDK field ${H}`);t.readOnly&&u(p,"state file settings have not been imported"),w={...w};for(let H of Xe)w[H]=K[H];let I={...g,revision:g.revision+1,state:w};if(await Ls(()=>kr(e,p)),!await s.compareAndSwap(p,g.revision,I))throw new Error(`Classic SDK Run ${p} changed while importing state file settings`);g=I}}if(K&&w.boundBranch===null&&ug(w.isolation)&&!w.archived&&["running","waiting"].includes(g.status)&&!g.actions.some(ee=>["running","unknown"].includes(ee.status))){let ee=Fa({isolation:w.isolation,boundBranch:w.boundBranch,currentBranch:Jr(e)});if(ee.status==="needs-heal"){t.readOnly&&u(p,"the Git branch binding has not been recorded"),w={...w,boundBranch:ee.branch};let he={...g,revision:g.revision+1,state:w};if(await Ls(()=>kr(e,p)),!await s.compareAndSwap(p,g.revision,he))throw new Error(`Classic SDK Run ${p} changed while binding its Git branch`);g=he}}if(t.readOnly){let ee=O?.[ht],he=ee===void 0;return ee!==void 0&&r?he=Hi(ee,g):ee!==void 0&&(he=Wa(ee,Ko(g))),(S===null||!At(S)||!K||!gr(K,w)||!he||t.identity&&O.application_checkpoint!==void 0&&!gr(O.application_checkpoint,t.identity))&&u(p,"the state projection or portable checkpoint is missing or stale"),g}let Y=kl(w),Q=O??{};for(let[ee,he]of Object.entries(Y))gr(Q[ee],he)||(he===void 0?E.delete(ee):E.set(ee,he));let te=Ku(Ko(g));gr(Q[ht],te)||E.set(ht,te),t.identity&&!gr(Q.application_checkpoint,t.identity)&&E.set("application_checkpoint",t.identity);let Z=E.toString(),Pe=At(Z)?Z:Ip+Z;return S!==Pe&&await go(e,k,Pe,{label:"Classic state file"}),ed(g)&&(t.identity||await Sp(e,"classic",g.runId)),g})()}return{queryScope:s.queryScope,async read(p){if(!t.identity&&x_.getStore()?.has(c(p)))return await o(!0),s.read(p);if(!t.readOnly){await o(!0);try{let l=await Yn(e,{...t,store:s,readOnly:!0}).read(p);if(l&&!ed(l))return l}catch{}}return d(p,!0)},async readProjection(p){await o(!0);let l=await Yn(e,{...t,store:s,readOnly:!0},!0).read(p);return await o(!0),l},async compareAndSwap(p,l,m){return Ls(async()=>{if(t.readOnly)throw new Error("Classic SDK read-only store cannot change a Run");if(m.status==="cancelled"&&l!==null){let g=await s.read(p);if(g&&Pg(g))throw new Error(`Classic Archive must finish or recover before cancelling this Run; preserve its original Action and use comet state check ${p} archive --recover --json to inspect the recovery path.`)}await kr(e,p),l!==null&&await a(m),await o();let h=await s.compareAndSwap(p,l,m);if(h&&l!==null){let g=x_.getStore(),w=c(p);g&&!t.identity&&m.workflow.version==="2"&&!JW(m)?g.set(w,()=>d(p,!1)):(g?.delete(w),await d(p,!1))}return h})}}}async function I_(e){let t={change:e.name,changeDir:zW.relative(e.projectRoot,e.changeDir).replaceAll("\\","/"),...e.recoverySourceHash?{recoverySourceHash:e.recoverySourceHash}:{},...e.recoverySource?{recoverySource:e.recoverySource}:{}},r=e.recoverySourceHash?t:await c_(e.projectRoot,t),n=Qo(e.profile),i=Yn(e.projectRoot);return Wi({store:{async read(c){let u=await i.read(c);if(u&&!await ea(e.projectRoot,"classic",c))throw new v("RUN_OWNER_MISSING",`Classic SDK Run ${c} 缺少归属记录`);return u},async compareAndSwap(c,u,f){if(u===null){if(c!==e.name)throw new Error("Classic SDK Run ID and change name differ");await ta(e.projectRoot,{schema:Si,workflow:"classic",change:e.name,format:"sdk",application:`classic-${e.profile}`,runId:c},{canonical:!0})}return i.compareAndSwap(c,u,f)}},workflows:[n.workflow],transitionHandlers:[n.transitionHandler],evidenceValidators:n.evidenceValidators,validators:n.validators}).start({runId:e.name,workflow:{id:n.workflow.id,version:n.workflow.version},input:r,initialState:e.initialState})}async function YW(e,t){if(!At(t))return null;let r=(0,Ig.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Classic state: ${r.errors[0].message}`);let n=Mt(r.toJS()).classic,i=await GW.readdir(e),o=[];for(let s of i)s===".comet-state.lock"&&await zk(O_.join(e,s))||o.push(s);return n?.phase==="open"&&n.designDoc===null&&n.plan===null&&n.verifyResult==="pending"&&n.verifyFailures===0&&!n.archived&&o.every(s=>dl(s)||s===".openspec.yaml")?n:null}async function XW(e,t,r){return await kr(e,t),r()}async function Og(e,t){await kr(e,t);let r=await $n(e,"classic",t);return r||XW(e,t,async()=>{let n=await $n(e,"classic",t);if(n)return n;let i=(await Il(t,e)).directory,o=O_.relative(e,await Re(i)),s=await U(e,o,{label:"Classic legacy change state",expected:"file"});if(!s.exists)return null;let c=await Fe(e,s.target,{label:"Classic change state"});if(At(c)){let u=(0,Ig.parseDocument)(c,{uniqueKeys:!0});if(u.errors.length>0)throw new Error(`Invalid Classic state: ${u.errors[0].message}`);let f=u.toJS(),a=Mt(f).classic;if(a?.archived&&a.isolation==="worktree"&&f.application_checkpoint==null&&a.boundBranch&&a.boundBranch!==Jr(e)&&Ir(f[ht],t,{preserveSourceRevision:!0}))throw new Error(`Classic archived change ${t} requires its original completed Run history. The portable checkpoint retains the pre-delivery baseline; restore the matching Run history from the original workspace or backup before querying completion. Do not rewrite the checkpoint or repeat Archive.`);if(await Yn(e).read(t)){let p=await $n(e,"classic",t);if(!p||p.format!=="sdk")throw new Error(`Recovered Classic change ${t} has no Run ownership`);return p}let d=await YW(i,c);if(d){await I_({projectRoot:e,name:t,profile:d.workflow,changeDir:i,initialState:d});let p=await $n(e,"classic",t);if(!p||p.format!=="sdk")throw new Error(`Recovered Classic change ${t} has no Run ownership`);return p}throw new Error(`Classic change ${t} has a state file but lost its local Run history; after confirming the original process stopped, use comet state restore ${t} --confirmed to restart at Open`)}return sR(e,{schema:Si,workflow:"classic",change:t,format:"compat"})})}Lt();ye();var QW="@rpamis/comet",D5=`https://registry.npmjs.org/${QW}/latest`;hl();function jg(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Gi=jg();function M_(e){Gi=e}var Ji={exec:()=>null};function Zo(e){let t=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=t[n];return i||(i=e(n),t[n]=i),i}}function me(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(Et.caret,"$1"),r=r.replace(i,s),n},getRegex:()=>new RegExp(r,t)};return n}var ZW=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Et={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Zo(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Zo(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Zo(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Zo(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Zo(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Zo(e=>new RegExp(`^ {0,${e}}>`))},eF=/^(?:[ \t]*(?:\n|$))+/,tF=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,rF=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,za=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,nF=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Dg=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,W_=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,F_=me(W_).replace(/bull/g,Dg).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),iF=me(W_).replace(/bull/g,Dg).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),qg=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,oF=/^[^\n]+/,Lg=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,sF=me(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Lg).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),aF=me(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Dg).getRegex(),ld="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Mg=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,cF=me("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Mg).replace("tag",ld).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),H_=e=>me(qg).replace("hr",za).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ld).getRegex(),lF=H_(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),uF=H_(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),dF=me(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",uF).getRegex(),Wg={blockquote:dF,code:tF,def:sF,fences:rF,heading:nF,hr:za,html:cF,lheading:F_,list:aF,newline:eF,paragraph:lF,table:Ji,text:oF},N_=me("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",za).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ld).getRegex(),fF={...Wg,lheading:iF,table:N_,paragraph:me(qg).replace("hr",za).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",N_).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ld).getRegex()},pF={...Wg,html:me(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Mg).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ji,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:me(qg).replace("hr",za).replace("heading",` *#{1,6} *[^
202
+ ]`).replace("lheading",F_).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},mF=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,hF=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,V_=/^( {2,}|\\)\n(?!\s*$)/,gF=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,un=/[\p{P}\p{S}]/u,es=/[\s\p{P}\p{S}]/u,Ga=/[^\s\p{P}\p{S}]/u,wF=me(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,es).getRegex(),yF=/[\p{Pi}\p{Ps}"']/u,B_=/(?!~)[\p{P}\p{S}]/u,vF=/(?!~)[\s\p{P}\p{S}]/u,kF=/(?:[^\s\p{P}\p{S}]|~)/u,bF=me(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",ZW?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),U_=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,RF=me(U_,"u").replace(/punct/g,un).getRegex(),SF=me(U_,"u").replace(/punct/g,B_).getRegex(),CF=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,EF=me(CF,"u").replace(/openQuote/g,yF).replace(/punct/g,un).getRegex(),K_="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",_F=me(K_,"gu").replace(/notPunctSpace/g,Ga).replace(/punctSpace/g,es).replace(/punct/g,un).getRegex(),AF=me(K_,"gu").replace(/notPunctSpace/g,kF).replace(/punctSpace/g,vF).replace(/punct/g,B_).getRegex(),xF="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",PF=me(xF,"gu").replace(/notPunctSpace/g,Ga).replace(/punctSpace/g,es).replace(/punct/g,un).getRegex(),IF=me("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ga).replace(/punctSpace/g,es).replace(/punct/g,un).getRegex(),OF="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",NF=me(OF,"gu").replace(/notPunctSpace/g,Ga).replace(/punctSpace/g,es).replace(/punct/g,un).getRegex(),TF=me(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,un).getRegex(),$F="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",jF=me($F,"gu").replace(/notPunctSpace/g,Ga).replace(/punctSpace/g,es).replace(/punct/g,un).getRegex(),DF=me(/\\(punct)/,"gu").replace(/punct/g,un).getRegex(),qF=me(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),LF=me(Mg).replace("(?:-->|$)","-->").getRegex(),MF=me("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",LF).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),sd=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,WF=me(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",sd).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),J_=me(/^!?\[(label)\]\[(ref)\]/).replace("label",sd).replace("ref",Lg).getRegex(),z_=me(/^!?\[(ref)\](?:\[\])?/).replace("ref",Lg).getRegex(),FF=me("reflink|nolink(?!\\()","g").replace("reflink",J_).replace("nolink",z_).getRegex(),T_=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Fg={_backpedal:Ji,anyPunctuation:DF,autolink:qF,blockSkip:bF,br:V_,code:hF,del:Ji,delLDelim:Ji,delRDelim:Ji,emStrongLDelim:RF,emStrongRDelimAst:_F,emStrongRDelimUnd:IF,escape:mF,link:WF,nolink:z_,punctuation:wF,reflink:J_,reflinkSearch:FF,tag:MF,text:gF,url:Ji},HF={...Fg,emStrongLDelim:EF,emStrongRDelimAst:PF,emStrongRDelimUnd:NF,link:me(/^!?\[(label)\]\((.*?)\)/).replace("label",sd).getRegex(),reflink:me(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",sd).getRegex()},Ng={...Fg,emStrongRDelimAst:AF,emStrongLDelim:SF,delLDelim:TF,delRDelim:jF,url:me(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",T_).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:me(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",T_).getRegex()},VF={...Ng,br:me(V_).replace("{2,}","*").getRegex(),text:me(Ng.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},od={normal:Wg,gfm:fF,pedantic:pF},Ka={normal:Fg,gfm:Ng,breaks:VF,pedantic:HF},BF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},$_=e=>BF[e];function zr(e,t){if(t){if(Et.escapeTest.test(e))return e.replace(Et.escapeReplace,$_)}else if(Et.escapeTestNoEncode.test(e))return e.replace(Et.escapeReplaceNoEncode,$_);return e}function j_(e){try{e=encodeURI(e).replace(Et.percentDecode,"%")}catch{return null}return e}function D_(e,t){let r=e.replace(Et.findPipe,(o,s,c)=>{let u=!1,f=s;for(;--f>=0&&c[f]==="\\";)u=!u;return u?"|":" |"}),n=r.split(Et.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(Et.slashPipe,"|");return n}function Xn(e,t,r){let n=e.length;if(n===0)return"";let i=0;for(;i<n;){let o=e.charAt(n-i-1);if(o===t&&!r)i++;else if(o!==t&&r)i++;else break}return e.slice(0,n-i)}function q_(e){let t=e.split(`
203
+ `),r=t.length-1;for(;r>=0&&Et.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
204
+ `)}function UF(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return r>0?-2:-1}function KF(e,t=0){let r=t,n="";for(let i of e)if(i===" "){let o=4-r%4;n+=" ".repeat(o),r+=o}else n+=i,r++;return n}function L_(e,t,r,n,i){let o=t.href,s=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1"),u=e[0].charAt(0)==="!";n.state.inLink=!0;let f=n.state.linkEmitted,a=n.state.inRawBlock;n.state.linkEmitted=!1;let d=n.inlineTokens(c),p=n.state.linkEmitted;if(n.state.linkEmitted=f,n.state.inLink=!1,!u){if(p){n.state.inRawBlock=a;return}n.state.linkEmitted=!0}return{type:u?"image":"link",raw:r,href:o,title:s,text:c,tokens:d}}function JF(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
205
+ `).map(o=>{let s=o.match(r.other.beginningSpace);if(s===null)return o;let[c]=s;return c.length>=i.length?o.slice(i.length):o}).join(`
206
+ `)}var ad=class{options;rules;lexer;constructor(e){this.options=e||Gi}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:q_(t[0]),n=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],n=JF(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let n=Xn(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:Xn(t[0],`
207
+ `),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Xn(t[0],`
208
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Xn(t[0],`
209
+ `).split(`
210
+ `),n="",i="",o=[];for(;r.length>0;){let s=!1,c=[],u;for(u=0;u<r.length;u++)if(this.rules.other.blockquoteStart.test(r[u]))c.push(r[u]),s=!0;else if(!s)c.push(r[u]);else break;r=r.slice(u);let f=c.join(`
211
+ `),a=f.replace(this.rules.other.blockquoteSetextReplace,`
212
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
213
+ ${f}`:f,i=i?`${i}
214
+ ${a}`:a;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(a,o,!0),this.lexer.state.top=d,r.length===0)break;let p=o.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let l=p,m=r.join(`
215
+ `),h=l.raw+`
216
+ `+m.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(h);o[o.length-1]=g,n=`${n}
217
+ ${m}`,i=i.substring(0,i.length-l.text.length)+g.text;break}else if(p?.type==="list"){let l=p,m=l.raw+`
218
+ `+r.join(`
219
+ `),h=this.list(m);o[o.length-1]=h,n=n.substring(0,n.length-p.raw.length)+h.raw,i=i.substring(0,i.length-l.raw.length)+h.raw,r=m.substring(o.at(-1).raw.length).split(`
220
+ `);continue}}return{type:"blockquote",raw:n,tokens:o,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let o=this.rules.other.listItemRegex(r),s=!1;for(;e;){let u=!1,f="",a="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;f=t[0],e=e.substring(f.length);let d=KF(t[2].split(`
221
+ `,1)[0],t[1].length),p=e.split(`
222
+ `,1)[0],l=!d.trim(),m=0;if(this.options.pedantic?(m=2,a=d.trimStart()):l?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,a=d.slice(m),m+=t[1].length),l&&this.rules.other.blankLine.test(p)&&(f+=p+`
223
+ `,e=e.substring(p.length+1),u=!0),!u){let h=this.rules.other.nextBulletRegex(m),g=this.rules.other.hrRegex(m),w=this.rules.other.fencesBeginRegex(m),k=this.rules.other.headingBeginRegex(m),b=this.rules.other.htmlBeginRegex(m),S=this.rules.other.blockquoteBeginRegex(m);for(;e;){let E=e.split(`
224
+ `,1)[0],O;if(p=E,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),O=p):O=p.replace(this.rules.other.tabCharGlobal," "),w.test(p)||k.test(p)||b.test(p)||S.test(p)||h.test(p)||g.test(p))break;if(O.search(this.rules.other.nonSpaceChar)>=m||!p.trim())a+=`
225
+ `+O.slice(m);else{if(l||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||k.test(d)||g.test(d))break;a+=`
226
+ `+p}l=!p.trim(),f+=E+`
227
+ `,e=e.substring(E.length+1),d=O.slice(m)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(f)&&(s=!0)),i.items.push({type:"list_item",raw:f,task:!!this.options.gfm&&this.rules.other.listIsTask.test(a),loose:!1,text:a,tokens:[]}),i.raw+=f}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let u of i.items)if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),!i.loose){let f=u.tokens.filter(d=>d.type==="space"),a=f.length>0&&f.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=a}for(let u of i.items){let f=u.tokens[0];if(u.task&&(f?.type==="text"||f?.type==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),f.raw=f.raw.replace(this.rules.other.listReplaceTask,""),f.text=f.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let a=this.rules.other.listTaskCheckbox.exec(u.raw);if(a){let d={type:"checkbox",raw:a[0]+" ",checked:a[0]!=="[ ]"};u.checked=d.checked,i.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=d.raw+u.tokens[0].raw,u.tokens[0].text=d.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(d)):u.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):u.tokens.unshift(d)}}else u.task&&(u.task=!1)}if(i.loose)for(let u of i.items){u.loose=!0;for(let f of u.tokens)f.type==="text"&&(f.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=q_(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:Xn(t[0],`
228
+ `),href:n,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=D_(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
229
+ `):[],o={type:"table",raw:Xn(t[0],`
230
+ `),header:[],align:[],rows:[]};if(r.length===n.length){for(let s of n)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<r.length;s++)o.header.push({text:r[s],tokens:this.lexer.inline(r[s]),header:!0,align:o.align[s]});for(let s of i)o.rows.push(D_(s,o.header.length).map((c,u)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:o.align[u]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Xn(t[0],`
231
+ `),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
232
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let o=Xn(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{let o=UF(t[2],"()");if(o===-2)return;if(o>-1){let s=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,s).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(n);o&&(n=o[1],i=o[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),L_(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[n.toLowerCase()];if(!i){let o=r[0].charAt(0);return{type:"text",raw:o,text:o}}return L_(r,i,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,o,s,c=i,u=0,f=n[0][0],a=r===f,d=f==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(n=d.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o)continue;if(s=[...o].length,n[3]||n[4]){c+=s;continue}else if(n[5]||n[6]){if(i%3&&!((i+s)%3)){u+=s;continue}if(a)break}if(c-=s,c>0)continue;s=Math.min(s,s+c+u);let p=[...n[0]][0].length,l=e.slice(0,i+n.index+p+s);if(Math.min(i,s)%2){let h=l.slice(1,-1);return{type:"em",raw:l,text:h,tokens:this.lexer.inlineTokens(h)}}let m=l.slice(2,-2);return{type:"strong",raw:l,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,o,s,c=i,u=this.rules.inline.delRDelim;for(u.lastIndex=0,t=t.slice(-1*e.length+i);(n=u.exec(t))!==null;){if(o=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!o||(s=[...o].length,s!==i))continue;if(n[3]||n[4]){c+=s;continue}if(c-=s,c>0)continue;s=Math.min(s,s+c);let f=[...n[0]][0].length,a=e.slice(0,i+n.index+f+s),d=a.slice(i,-i);return{type:"del",raw:a,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,n;return t[2]==="@"?(r=t[1],n="mailto:"+r):(r=t[1],n=r),{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},wr=class Tg{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Gi,this.options.tokenizer=this.options.tokenizer||new ad,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:Et,block:od.normal,inline:Ka.normal};this.options.pedantic?(r.block=od.pedantic,r.inline=Ka.pedantic):this.options.gfm&&(r.block=od.gfm,this.options.breaks?r.inline=Ka.breaks:r.inline=Ka.gfm),this.tokenizer.rules=r}static get rules(){return{block:od,inline:Ka}}static lex(t,r){return new Tg(r).lex(t)}static lexInline(t,r){return new Tg(r).inlineTokens(t)}lex(t){t=t.replace(Et.carriageReturn,`
233
+ `),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Et.tabCharGlobal," ").replace(Et.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(c=>(o=c.call({lexer:this},t,r))?(t=t.substring(o.raw.length),r.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let c=r.at(-1);o.raw.length===1&&c!==void 0?c.raw+=`
234
+ `:r.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let c=r.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
235
+ `)?"":`
236
+ `)+o.raw,c.text+=`
237
+ `+o.text,this.inlineQueue.at(-1).src=c.text):r.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let c=r.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
238
+ `)?"":`
239
+ `)+o.raw,c.text+=`
240
+ `+o.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},r.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),r.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),r.push(o);continue}let s=t;if(this.options.extensions?.startBlock){let c=1/0,u=t.slice(1),f;this.options.extensions.startBlock.forEach(a=>{f=a.call({lexer:this},u),typeof f=="number"&&f>=0&&(c=Math.min(c,f))}),c<1/0&&c>=0&&(s=t.substring(0,c+1))}if(this.state.top&&(o=this.tokenizer.paragraph(s))){let c=r.at(-1);n&&c?.type==="paragraph"?(c.raw+=(c.raw.endsWith(`
241
+ `)?"":`
242
+ `)+o.raw,c.text+=`
243
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):r.push(o),n=s.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let c=r.at(-1);c?.type==="text"?(c.raw+=(c.raw.endsWith(`
244
+ `)?"":`
245
+ `)+o.raw,c.text+=`
246
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):r.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],o=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(o+1,-1)))&&!(o>1&&this.linkInText(i.slice(1,o-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let n=t;if(this.tokens.links&&t.includes("[")){let c=this.tokenizer.rules.inline.reflinkSearch,u=f=>{let a=f.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,f.slice(a+1,-1)))return f;if(a>1&&f.charAt(0)!=="!"){let d=f.slice(1,a-1);if(this.linkInText(d))return"["+d.replace(c,u)+"]["+"a".repeat(f.length-a-2)+"]"}return"["+"a".repeat(f.length-2)+"]"};n=n.replace(c,u)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,c=>"+".repeat(c.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(c,u,f)=>{let a=f?f.length:0;return c.slice(0,a)+"["+"a".repeat(c.length-a-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,o="",s=1/0;for(;t;){if(t.length<s)s=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(o=""),i=!1;let c;if(this.options.extensions?.inline?.some(f=>(c=f.call({lexer:this},t,r))?(t=t.substring(c.raw.length),r.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let f=r.at(-1);c.type==="text"&&f?.type==="text"?(f.raw+=c.raw,f.text+=c.text):r.push(c);continue}if(c=this.tokenizer.emStrong(t,n,o)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.del(t,n,o)){t=t.substring(c.raw.length),r.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),r.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),r.push(c);continue}let u=t;if(this.options.extensions?.startInline){let f=1/0,a=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},a),typeof d=="number"&&d>=0&&(f=Math.min(f,d))}),f<1/0&&f>=0&&(u=t.substring(0,f+1))}if(c=this.tokenizer.inlineText(u)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(o=c.raw.slice(-1)),i=!0;let f=r.at(-1);f?.type==="text"?(f.raw+=c.raw,f.text+=c.text):r.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},cd=class{options;parser;constructor(e){this.options=e||Gi}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(Et.notSpaceStart)?.[0],i=e.replace(Et.endingNewline,"")+`
247
+ `;return n?'<pre><code class="language-'+zr(n)+'">'+(r?i:zr(i,!0))+`</code></pre>
248
+ `:"<pre><code>"+(r?i:zr(i,!0))+`</code></pre>
249
+ `}blockquote({tokens:e}){return`<blockquote>
250
+ ${this.parser.parse(e)}</blockquote>
251
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
252
+ `}hr(e){return`<hr>
253
+ `}list(e){let t=e.ordered,r=e.start,n="";for(let s=0;s<e.items.length;s++){let c=e.items[s];n+=this.listitem(c)}let i=t?"ol":"ul",o=t&&r!==1?' start="'+r+'"':"";return"<"+i+o+`>
254
+ `+n+"</"+i+`>
255
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
256
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
257
+ `}table(e){let t="",r="";for(let i=0;i<e.header.length;i++)r+=this.tablecell(e.header[i]);t+=this.tablerow({text:r});let n="";for(let i=0;i<e.rows.length;i++){let o=e.rows[i];r="";for(let s=0;s<o.length;s++)r+=this.tablecell(o[s]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
258
+ <thead>
259
+ `+t+`</thead>
260
+ `+n+`</table>
261
+ `}tablerow({text:e}){return`<tr>
262
+ ${e}</tr>
263
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
264
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${zr(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let n=this.parser.parseInline(r),i=j_(e);if(i===null)return n;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+zr(t)+'"'),o+=">"+n+"</a>",o}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=j_(e);if(i===null)return zr(r);e=i;let o=`<img src="${e}" alt="${zr(r)}"`;return t&&(o+=` title="${zr(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:zr(e.text)}},Hg=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Or=class $g{options;renderer;textRenderer;constructor(t){this.options=t||Gi,this.options.renderer=this.options.renderer||new cd,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Hg}static parse(t,r){return new $g(r).parse(t)}static parseInline(t,r){return new $g(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let n=0;n<t.length;n++){let i=t[n];if(this.options.extensions?.renderers?.[i.type]){let s=i,c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(s.type)){r+=c||"";continue}}let o=i;switch(o.type){case"space":{r+=this.renderer.space(o);break}case"hr":{r+=this.renderer.hr(o);break}case"heading":{r+=this.renderer.heading(o);break}case"code":{r+=this.renderer.code(o);break}case"table":{r+=this.renderer.table(o);break}case"blockquote":{r+=this.renderer.blockquote(o);break}case"list":{r+=this.renderer.list(o);break}case"checkbox":{r+=this.renderer.checkbox(o);break}case"html":{r+=this.renderer.html(o);break}case"def":{r+=this.renderer.def(o);break}case"paragraph":{r+=this.renderer.paragraph(o);break}case"text":{r+=this.renderer.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<t.length;i++){let o=t[i];if(this.options.extensions?.renderers?.[o.type]){let c=this.options.extensions.renderers[o.type].call({parser:this},o);if(c!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(o.type)){n+=c||"";continue}}let s=o;switch(s.type){case"escape":{n+=r.text(s);break}case"html":{n+=r.html(s);break}case"link":{n+=r.link(s);break}case"image":{n+=r.image(s);break}case"checkbox":{n+=r.checkbox(s);break}case"strong":{n+=r.strong(s);break}case"em":{n+=r.em(s);break}case"codespan":{n+=r.codespan(s);break}case"br":{n+=r.br(s);break}case"del":{n+=r.del(s);break}case"text":{n+=r.text(s);break}default:{let c='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return n}},Ja=class{options;block;constructor(e){this.options=e||Gi}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?wr.lex:wr.lexInline}provideParser(e=this.block){return e?Or.parse:Or.parseInline}},zF=class{defaults=jg();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Or;Renderer=cd;TextRenderer=Hg;Lexer=wr;Tokenizer=ad;Hooks=Ja;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let n of e)switch(r=r.concat(t.call(this,n)),n.type){case"table":{let i=n;for(let o of i.header)r=r.concat(this.walkTokens(o.tokens,t));for(let o of i.rows)for(let s of o)r=r.concat(this.walkTokens(s.tokens,t));break}case"list":{let i=n;r=r.concat(this.walkTokens(i.items,t));break}default:{let i=n;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);r=r.concat(this.walkTokens(s,t))}):i.tokens&&(r=r.concat(this.walkTokens(i.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=t.renderers[i.name];o?t.renderers[i.name]=function(...s){let c=i.renderer.apply(this,s);return c===!1&&(c=o.apply(this,s)),c}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[i.level];o?o.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),n.extensions=t),r.renderer){let i=this.defaults.renderer||new cd(this.defaults);for(let o in r.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,c=r.renderer[s],u=i[s];i[s]=(...f)=>{let a=c.apply(i,f);return a===!1&&(a=u.apply(i,f)),a||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new ad(this.defaults);for(let o in r.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,c=r.tokenizer[s],u=i[s];i[s]=(...f)=>{let a=c.apply(i,f);return a===!1&&(a=u.apply(i,f)),a}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new Ja;for(let o in r.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,c=r.hooks[s],u=i[s];Ja.passThroughHooks.has(o)?i[s]=f=>{if(this.defaults.async&&Ja.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await c.call(i,f);return u.call(i,d)})();let a=c.call(i,f);return u.call(i,a)}:i[s]=(...f)=>{if(this.defaults.async)return(async()=>{let d=await c.apply(i,f);return d===!1&&(d=await u.apply(i,f)),d})();let a=c.apply(i,f);return a===!1&&(a=u.apply(i,f)),a}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,o=r.walkTokens;n.walkTokens=function(s){let c=[];return c.push(o.call(this,s)),i&&(c=c.concat(i.call(this,s))),c}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return wr.lex(e,t??this.defaults)}parser(e,t){return Or.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},i={...this.defaults,...n},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(t):t,c=await(i.hooks?await i.hooks.provideLexer(e):e?wr.lex:wr.lexInline)(s,i),u=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(u,i.walkTokens));let f=await(i.hooks?await i.hooks.provideParser(e):e?Or.parse:Or.parseInline)(u,i);return i.hooks?await i.hooks.postprocess(f):f})().catch(o);try{i.hooks&&(t=i.hooks.preprocess(t));let s=(i.hooks?i.hooks.provideLexer(e):e?wr.lex:wr.lexInline)(t,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(e):e?Or.parse:Or.parseInline)(s,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(s){return o(s)}}}onError(e,t){return r=>{if(r.message+=`
265
+ Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+zr(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},zi=new zF;function Te(e,t){return zi.parse(e,t)}Te.options=Te.setOptions=function(e){return zi.setOptions(e),Te.defaults=zi.defaults,M_(Te.defaults),Te};Te.getDefaults=jg;Te.defaults=Gi;function GF(...e){return zi.use(...e),Te.defaults=zi.defaults,M_(Te.defaults),Te}Te.use=GF;Te.walkTokens=function(e,t){return zi.walkTokens(e,t)};Te.parseInline=zi.parseInline;Te.Parser=Or;Te.parser=Or.parse;Te.Renderer=cd;Te.TextRenderer=Hg;Te.Lexer=wr;Te.lexer=wr.lex;Te.Tokenizer=ad;Te.Hooks=Ja;Te.parse=Te;var L5=Te.options,M5=Te.setOptions,YF=Te.walkTokens,W5=Te.parseInline;var F5=Or.parse,H5=wr.lex;ye();Lt();ye();ye();ye();ye();import ts from"node:path";ye();import{isDeepStrictEqual as iH}from"node:util";var Y_=Tt(Gt(),1);import rH from"node:path";async function dd(e,t,r,n="delivery",i){let o=Bi(t,r),s=t.state,c=Fa({isolation:s.isolation,boundBranch:s.boundBranch,currentBranch:Jr(e),gitWorkTree:Jo(e)});if(!["ok","not-applicable"].includes(c.status))throw new Error("Classic delivery repair requires its approved branch");await Yo(e,t,o.archive,o.archiveRef);{if(!r.reports||r.command||r.excludedOutputPaths?.length)throw new Error("Classic v2 delivery repair requires platform reports and the approved paths");return{...o}}}async function X_(e,t,r){if(!YE(t))throw new Error("Classic delivery repair requires the original archived Run with no unresolved execution");let n=Bi(t);{if(!r)throw new Error("Classic v2 delivery repair requires --checks <checks-json-file>");Eg(r);let i={checkpointHash:await nH(e,t),archiveActionId:n.archive.id,checkActionId:n.check.id,reports:r};return await dd(e,t,i,"prepare"),i}}async function nH(e,t){let r=Bi(t),n=await Fe(e,await Re(rH.join(e,r.archiveRef)),{label:"Classic archived delivery checkpoint",maxBytes:Number.MAX_SAFE_INTEGER}),i=(0,Y_.parseDocument)(n,{uniqueKeys:!0});if(!At(n)||i.errors.length)throw new Error("Classic archived checkpoint is invalid");let o=Le(i.toJS()),s=o.run_checkpoint;if($(Mt(o).classic)!==$(t.state)||!Hi(s,t)&&Xo(s,t,{projection:!0})===null)throw new Error("Classic archived checkpoint changed after the authoritative Run was read");return $(s)}function Q_(e,t,r){let n=`${t}.delivery.check`,i=`${t}.delivery.confirm`,o={id:"comet-classic-delivery-repair-command",version:"1",async validate({run:u,name:f,input:a,context:d}){let p=Le(a);if(!d?.projectRoot||f!=="repair-delivery"||p.expectedRevision!==u.revision||p.fromPhase!=="archive"||Object.keys(p).length!==3)return{accepted:!1,reason:"Classic delivery repair requires its current revision"};if(r){let h=u.workflow.hash===r.workflow.hash?structuredClone(r):Vi(r);if(h.workflow.hash=u.workflow.hash,h.definitionHashes[JSON.stringify([u.workflow.id,u.workflow.version])]=u.workflow.hash,$(h)!==$(u))return{accepted:!1,reason:"Classic delivery repair no longer matches its authoritative source Run"}}let l=await X_(d.projectRoot,r??u,p.deliveryRepair.reports),m=$(l)===$(p.deliveryRepair);return{accepted:m,allowFailed:m&&u.status==="failed",reason:"Classic delivery repair scope changed"}}},s={id:"comet-classic-delivery-repair-check",version:"1",async validate({run:u,action:f,outcome:a,context:d}){if(!d?.projectRoot||!zo(u,f)||f.claim?.executorId!=="comet-classic-check")return{accepted:!1,reason:"Classic delivery repair check has the wrong execution owner"};{let p=Go(f);if(a.status!=="succeeded"||!iH(a.output,{...p.reports,deliveryPaths:dg(u,p)}))return{accepted:!1,reason:"Classic delivery repair reports differ from the submitted reports"}}return a.status==="succeeded"&&await dd(d.projectRoot,u,Go(f),"delivery"),{accepted:!0}}},c={id:"comet-classic-check",capabilities:[],supports:u=>u.type==="call_tool"&&u.ref==="classic-check"&&u.stepId===n,async preflight(u,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");await dd(f.projectRoot,a,Go(u),"prepare")},async execute(u,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");{let d=Go(u);return{status:"succeeded",output:{...d.reports,deliveryPaths:dg(a,d)}}}}};return{...e,workflow:{...e.workflow,steps:{...e.workflow.steps,[n]:{type:"call_tool",ref:"classic-check",validator:{id:s.id,version:s.version}},[i]:{type:"ask_user",proposalFrom:n,choices:["approved","later"]}},transitions:[...e.workflow.transitions??[],{from:n,to:i},{from:i,to:`${t}.archive.deliver`,on:"approved"},{from:i,to:i,on:"later"}],commands:{...e.workflow.commands,"repair-delivery":{stepId:n,validator:{id:o.id,version:o.version}}}},commandValidators:[...e.commandValidators,o],validators:[...e.validators,s],executors:[...e.executors,c],transitionHandler:{...e.transitionHandler,apply(u){if(u.event.kind==="action-outcome"&&u.event.stepId===n)return{state:u.run.state,next:u.event.outcome.status==="succeeded"?[i]:[]};if(u.event.kind==="wait-resolved"&&u.event.stepId===i){let f=u.run.actions.slice().reverse().find(a=>a.stepId===n&&a.status==="succeeded");return{state:u.run.state,next:u.event.choice==="approved"&&f?[{stepId:`${t}.archive.deliver`,input:{deliveryRepairCheckId:f.id}}]:[i]}}return e.transitionHandler.apply(u)}}}}function oH(e){let t=e.actions.at(-1);return e.status==="failed"&&t?.status==="failed"&&t.type==="invoke_skill"&&!e.actions.some(r=>["running","unknown","pending"].includes(r.status))&&!e.waits.some(r=>r.status==="pending")&&!e.evidenceWaits?.some(r=>r.status==="pending")?t:null}var Ya={id:"comet-classic-work-continuation-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=r,o=oH(e),s=t==="continue-work"&&o!==null&&i?.expectedRevision===e.revision&&i.fromPhase===e.state.phase&&i.interruptedActionId===o.id&&Object.keys(i).filter(c=>c!=="deliveryCheckpointHash").length===3;return{accepted:s,allowFailed:s,reason:"Classic continuation requires the original settled failed Skill and current revision"}}},Z_={id:"comet-classic-work-continuation",capabilities:[],supports:e=>e.ref==="classic-work-continuation",async execute(e,t,r){let n=e.input.activation?.interruptedActionId,i=r?.actions.find(o=>o.id===n);if(!i||i.status!=="failed"||i.type!=="invoke_skill")throw new Error("Classic original failed Skill is missing");return{status:"succeeded",output:{interruptedActionId:i.id,resumeStepId:i.stepId}}}},Vg={id:"comet-classic-work-continuation-outcome",version:"1",validate({run:e,action:t,outcome:r}){let n=t.input.activation?.interruptedActionId,i=e.actions.find(o=>o.id===n);return{accepted:t.claim?.executorId===Z_.id&&r.status==="succeeded"&&i?.status==="failed"&&i.type==="invoke_skill"&&$(r.output)===$({interruptedActionId:i.id,resumeStepId:i.stepId}),reason:"Classic continuation does not match its original failed Skill"}}};function sH(e){let t=e.state,r=e.actions.at(-1);return t.phase==="build"&&e.status==="failed"&&!t.archived&&r?.status==="failed"&&r.stepId===`${t.workflow}.build.execute`&&!e.actions.some(n=>["running","unknown","pending"].includes(n.status))?r:null}var Bg={id:"comet-classic-build-continuation-command",version:"1",validate({run:e,name:t,input:r}){let n=r,i=e.state,o=t==="continue-build"&&(sH(e)!==null||Kg(e))&&n?.expectedRevision===e.revision&&n.fromPhase===i.phase&&Object.keys(n).length===2;return{accepted:o,allowFailed:o,reason:"Classic Build continuation requires the current stopped failed Builder"}}};function aH(e){let t=e.state;return t.archived||t.phase!=="archive"||!["failed","running"].includes(e.status)||e.actions.some(r=>["running","unknown","pending"].includes(r.status))||e.waits.some(r=>r.status==="pending")||e.evidenceWaits?.some(r=>r.status==="pending")?null:e.actions.slice().reverse().find(r=>r.stepId===`${t.workflow}.archive.execute`&&r.status==="failed")??null}var Ug={id:"comet-classic-archive-repair-command",version:"1",async validate({run:e,name:t,input:r,context:n}){let i=r,o=aH(e);return t!=="repair-archive"||!o||!n?.projectRoot||i?.expectedRevision!==e.revision||i.fromPhase!=="archive"||Object.keys(i).length!==2?{accepted:!1,reason:"Classic Archive requires a stopped failed execution and the current revision"}:(await t_(n.projectRoot,e,o),{accepted:!0,allowFailed:!0})}},Xa={id:"comet-classic-revision-command",version:"1",validate({run:e,name:t,input:r}){let n=e.state,i=t==="revise-design"?"design":t==="revise-plan"?"build":null,o=r,s=[...e.actions.filter(f=>f.status==="pending"),...e.waits.filter(f=>f.status==="pending"),...(e.evidenceWaits??[]).filter(f=>f.status==="pending")],c=t==="revise-design"?["full.design.handoff","full.design.confirm","full.design.document","full.design.evidence"]:["full.build.plan","full.build.plan.evidence","full.build.plan-ready","full.build.execute","full.build.check","full.build.check.evidence"],u=["verify","archive"].includes(n.phase)&&Kg(e);return{accepted:n.workflow==="full"&&(n.phase===i||t==="revise-design"&&n.phase==="build"||u)&&!n.archived&&o?.expectedRevision===e.revision&&Object.keys(o).length===2&&o.fromPhase===n.phase&&s.length===1&&(u||c.includes(s[0].stepId)||t==="revise-design"&&n.phase==="build"&&["full.build.plan","full.build.plan.evidence","full.build.plan-ready","full.build.execute","full.build.check","full.build.check.evidence"].includes(s[0].stepId)),reason:"Classic revision is stale or does not match the pending Design or Build work"}}};function Kg(e){let t=e.state;if(t.archived||!["verify","archive"].includes(t.phase)||!["running","waiting"].includes(e.status)||e.actions.some(n=>["running","unknown"].includes(n.status)||n.stepId.endsWith(".archive.execute")&&(!["pending","cancelled"].includes(n.status)||n.attempt!==1||!!n.claim||n.receipts.length>0)))return!1;let r=[...e.actions.filter(n=>n.status==="pending"),...e.waits.filter(n=>n.status==="pending"),...(e.evidenceWaits??[]).filter(n=>n.status==="pending")];return r.length===1&&["verify.run","verify.report.evidence","verify.check","verify.check.evidence","archive.prepare","archive.confirm","archive.preflight","archive.execute"].some(n=>r[0].stepId===`${t.workflow}.${n}`)}var fd={id:"comet-classic-verification-revision-command",version:"1",validate({run:e,name:t,input:r}){let n=r;return{accepted:t==="reopen-verification"&&Kg(e)&&n?.expectedRevision===e.revision&&Object.keys(n).length===2&&n.fromPhase===e.state.phase,reason:"Classic verification cannot reopen after Archive execution or while work has an unresolved outcome"}}};function cH(e,t=!0,r=!0,n=!0,i=!0,o){let s=Qo(e),c={...Ya,async validate(f){if(!o)return Ya.validate(f);let a=f.run.workflow.hash===o.workflow.hash?structuredClone(o):Vi(o);return a.workflow.hash=f.run.workflow.hash,a.definitionHashes[JSON.stringify([f.run.workflow.id,f.run.workflow.version])]=f.run.workflow.hash,$(a)!==$(f.run)?{accepted:!1,reason:"Classic continuation no longer matches its authoritative source Run"}:Ya.validate({...f,run:o})}},u=r&&t==="full"&&e!=="full"?Qo("full").workflow:null;return{...s,workflow:{...s.workflow,steps:{...s.workflow.steps,...i?{"classic.resume-work":{type:"call_tool",ref:"classic-work-continuation",validator:{id:Vg.id,version:Vg.version}}}:{},...Object.fromEntries(Object.entries(u?.steps??{}).filter(([f])=>f.startsWith("full.open")))},transitions:[...s.workflow.transitions??[],...u?.transitions?.filter(f=>f.from.startsWith("full.open"))??[],{from:"full.design.evidence",to:"full.build.plan"},...i?Object.entries(s.workflow.steps).filter(([,f])=>f.type==="invoke_skill").map(([f])=>({from:"classic.resume-work",to:f})):[]],commands:{...i?{"continue-work":{stepId:"classic.resume-work",validator:{id:Ya.id,version:Ya.version}}}:{},...n?{"continue-build":{stepId:`${t==="full"?"full":e}.build.execute`,validator:{id:Bg.id,version:Bg.version}}}:{},...r?{"repair-archive":{stepId:`${t==="full"?"full":e}.open`,validator:{id:Ug.id,version:Ug.version}}}:{},...t?{"reopen-verification":{stepId:`${t==="full"?"full":e}.verify.run`,validator:{id:fd.id,version:fd.version}}}:{},"revise-design":{stepId:"full.design.handoff",validator:{id:Xa.id,version:Xa.version}},"revise-plan":{stepId:"full.build.plan",validator:{id:Xa.id,version:Xa.version}}}},commandValidators:[...i?[c]:[],...n?[Bg]:[],...r?[Ug]:[],Xa,...t?[{...fd,validate:f=>f.run.state.workflow!==(t==="full"?"full":e)?{accepted:!1,reason:"Classic verification command does not match the active workflow profile"}:fd.validate(f)}]:[]],executors:[...s.executors,...i?[Z_]:[]],validators:[...s.validators,...i?[Vg]:[]],transitionHandler:{...s.transitionHandler,apply(f){if(f.event.kind==="action-outcome"&&f.event.stepId==="classic.resume-work"&&f.event.outcome.status==="succeeded"){let a=f.event.outcome.output,d=f.run.actions.find(l=>l.id===a.interruptedActionId),p=d?.stepId.endsWith(".archive.deliver")?d.input.activation?.deliveryRepairCheckId:void 0;return{state:f.run.state,next:[{stepId:a.resumeStepId,input:{interruptedActionId:a.interruptedActionId,...p?{deliveryRepairCheckId:p}:{},summary:"Continue preserved partial work; do not repeat completed side effects."}}]}}return s.transitionHandler.apply(f)}}}}function eA(e,t,r={}){let n={...Qo(e),commandValidators:[]};if(!t||t.workflow.hash===$(Pr(n.workflow)))return n;let i=t.state.workflow,o=cH(e,i==="full"&&e!=="full"?"full":!0);if(t.workflow.hash===$(Pr(o.workflow)))return o;let s=Q_(o,i);if(t.workflow.hash===$(Pr(s.workflow)))return s;if(t.workflow.version!=="1")throw new Error("Classic 当前 Run 的 definition hash 不匹配,请保留原定义与业务记录。");return t.commands?.some(c=>c.name==="repair-delivery")?s:t.commands?.length||i!==e?o:n}async function tA(e,t,r={}){await kr(e,t);let n=(await Il(t,e)).directory,i=r.owner??await ea(e,"classic",t,{readOnly:r.readOnly});if(!i)throw new Error(`Classic change ${t} is not owned by an SDK Run`);if(!["classic-full","classic-hotfix","classic-tweak"].includes(i.application))throw new Error(`Classic change ${t} belongs to application ${i.application}; use comet runtime dispatch --application ${i.application} to continue its Run. Built-in commands cannot bypass composition checks.`);let o=i.application.slice(8),s=Yn(e,r),c=await s.read(i.runId),u=eA(o,c);if(c){let b=pg(c,u.workflow);b!==c&&(await Wi({...u,workflows:[u.workflow],transitionHandlers:[u.transitionHandler],store:{read:async()=>b,compareAndSwap:async()=>!1}}).inspect(i.runId),c=b)}let f=!0,a=Wi({store:{...s,async read(b){if(f&&b===i.runId)return f=!1,c;let S=await s.read(b);return S&&pg(S,u.workflow)}},workflows:[u.workflow],transitionHandlers:[u.transitionHandler],evidenceValidators:u.evidenceValidators,validators:u.validators,executors:u.executors,commandValidators:u.commandValidators}),d=await a.inspect(i.runId),p=d.state,l=d.input&&typeof d.input=="object"&&!Array.isArray(d.input)&&typeof d.input.changeDir=="string"?ts.resolve(e,d.input.changeDir):null,m=l?ts.join(ts.dirname(l),"archive"):null,h=Qu(d,o),g=h?"full":o,w=d.actions.some(b=>b.stepId===`${g}.archive.execute`&&(b.status==="running"||b.status==="unknown")),k=l!==null&&(n===l||(p?.archived===!0||w)&&ts.dirname(n)===m&&/^\d{4}-\d{2}-\d{2}-/u.test(ts.basename(n))&&ts.basename(n).slice(11)===t);if(d.workflow.id!==u.workflow.id||d.workflow.version!==u.workflow.version||!d.input||typeof d.input!="object"||Array.isArray(d.input)||d.input.change!==t||!k||!p||typeof p!="object"||Array.isArray(p)||p.workflow!==o&&!h)throw new Error(`Classic SDK Run ${t} does not match its change ownership`);return{run:d,state:p,runtime:a,profile:g,owner:i}}var Jg=cl(async(e,t)=>{let[r,n,i,o]=e;if(!(n==="design"&&i==="--write"&&(e.length===3||e.length===4&&o==="--full")))return Up(e,t);let c=Ks(r);if(c)return{exitCode:1,stderr:`ERROR: ${c}
266
+ `};let u=await fi(al()),f=await Pl(r,u.projectRoot);if((f.stateExists?await Og(u.projectRoot,r):null)?.format!=="sdk")return Up(e,t);let{run:d,state:p}=await tA(u.projectRoot,r);if(!["design","build"].includes(p.phase))return{exitCode:1,stderr:`ERROR: design handoff requires phase: design or build
267
+ `};if(!p.handoffContext)return{exitCode:1,stderr:`ERROR: SDK Design handoff is recorded by comet state propose-design ${r} --proposal <text>. The handoff command cannot replace sources already bound to an SDK approval; preserve the approved sources and Run state.
268
+ `};if(!await Ul({run:d,projectRoot:u.projectRoot,changeDir:f.directory,change:r,contextCompression:p.contextCompression,handoffContext:p.handoffContext,handoffHash:p.handoffHash}))return{exitCode:1,stderr:`ERROR: SDK handoff does not reference this change. Continue from its original Run and formal source files.
269
+ `};let l=Tl({name:r,locale:Nl(p.language)}),m=o==="--full"?await Bp({projectRoot:u.projectRoot,changeDir:f.directory,change:r}):null;return{exitCode:0,envelope:l,stderr:`${l.summary}
270
+ [HANDOFF] source ${p.handoffContext}${m?`
271
+ [HANDOFF] view `+m:""}
272
+ `}});import{realpathSync as gH}from"fs";import{pathToFileURL as cA}from"url";var lH=new Set([...Vs,"archive_confirmation","verify_failures","check_epoch","classic_profile","classic_migration","bound_branch"]),rA=new Set(xn.filter(e=>!lH.has(e))),zg={workflow:["full","hotfix","tweak"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct","autonomous"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]};var uH=`
273
+ Options: --json (machine-readable output), --compact (requires --json), --help
274
+ 精简视图用 outputView.references 的 JSON Pointer 定位重复字段;Request 模板保留完整;没有字节收益时返回原完整协议。去掉 --compact 获取完整协议。
275
+ JSON: one object with command and exitCode; data, stdout, stderr, summary and next are optional.
276
+ Use exitCode for success; do not parse human-readable stdout. Help text is in stdout in JSON mode.
277
+ `;function nA(e,t){let r=t.indexOf("--"),n=r<0?t:t.slice(0,r);if(!n.includes("--help")&&!n.includes("-h"))return;let i={check:["comet check run <change> <build|verify> -- <program> [args...]","comet check rerun <change> <build|verify>","These legacy commands return Agent platform guidance only; they do not execute or replay programs, create a claim, or record a passing result.","Run ordinary development and checks with the Agent platform tools. The platform owns timeout, cancellation and process cleanup.","Submit the actual results with --checks when completing SDK Build/Verify; use comet state record-check for Compat.","The Agent judges which checks apply. User choices, approvals, tasks and acceptance remain required.","Result: data.executed=false, data.nextAction and platform guidance; exitCode=0 means guidance was returned, not that a check passed."],state:["comet state <command> [args]","init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>] [--runtime <compat|sdk>]","state init defaults to sdk in Git roots and compat in non-Git roots for document-only archive; explicit sdk remains available but SDK Archive requires Git.","restore <change-name> --confirmed (recover a copied SDK Run; older states without a checkpoint restart at Open)","get <change-name> <field> [<field> ...]","set <change-name> <field> <value> [<field> <value> ...]","propose-design <change-name> --proposal <text> (SDK full workflow)","revise-design <change-name> --expected-revision <number> (SDK full workflow)","decide-design <change-name> --proposal-hash <sha256> --choice <approved|rejected> (SDK)","complete-design <change-name> --design-doc <repo-relative-ref> [--approval-hash <sha256>]","propose-build <change-name> --file <json> [--confirmed] (SDK full; --confirmed only for choices already explicitly approved)","decide-build <change-name> --proposal-hash <sha256> --choice <approved|rejected>","submit-plan <change-name> --plan <repo-relative-ref> [--pause]","revise-plan <change-name> --expected-revision <number> (SDK full workflow)","continue-build <change-name> --expected-revision <number> (SDK; resume a stopped failed Builder with preserved work)","continue-work <change-name> --expected-revision <number> (SDK; continue a settled failed Skill from preserved work)","continue-plan <change-name> --proposal-hash <sha256>","complete-build <change-name>","propose-escalation <change-name> --reason <text> (SDK hotfix/tweak)","decide-escalation <change-name> --proposal-hash <sha256> --choice <continue|upgrade> (SDK)","propose-archive <change-name> --summary <text> [--remote <name>] [--pr-base <branch>] [--delivery-path <file>]... (SDK)","decide-archive <change-name> --proposal-hash <sha256> --choice <local|push|pr|reverify|later> (SDK)","reopen-verification <change-name> --expected-revision <number> (SDK; before Archive execution)","repair-archive <change-name> --expected-revision <number> (SDK; stopped failure with unchanged Archive inputs)","repair-delivery <change-name> --expected-revision <number> [--checks <checks-json-file>] (SDK; repair delivery after Archive)","decide-delivery-repair <change-name> --proposal-hash <hash> --choice <approved|later>","complete-delivery <change-name> --commit <sha> [--pr-url <url>] (SDK)","transition <change-name> <event>","transition <change-name> verify-fail --reason <text> (SDK)","check <change-name> <phase> [--recover] [--details]","scale <change-name>","artifacts <change-name>","record-check <change-name> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","task-checkoff <file> <task-text>","tasks <change-name> [--assign-ids]","task-complete <change-name> <task-id> --expect <revision>","sync-plan <change-name>","checkpoint <change-name> [--file <json>]","delivery <change-name> [--file <json> | --verify]","select <change-name> [--details] | rebind <change-name> | next <change-name> [--details]","current | clear-selection","","Start with current or next <change-name> to inspect workflow guidance.","Advanced writes: init, set, transition, task-checkoff, select, rebind, clear-selection.","Use comet state <command> --help for details. --recover is for cold recovery, not normal progression.","A copied SDK change with a Run checkpoint in comet-state.yaml (or legacy .comet.yaml) resumes at its saved phase. If the checkpoint is absent, state restore requires confirmation and restarts at Open with fresh approvals and checks.","For SDK Design, propose-design records the exact proposal before asking the user; decide-design accepts only its current hash and may return a rejected proposal to Design. complete-design requires the approved hash and records the Design Doc in the same Run.","For SDK Build, propose-build reads build_mode, tdd_mode, review_mode and subagent_dispatch from a project-relative JSON file; optional direct_override is required for full direct execution. Workspace isolation remains the Open decision.","内置 Build 配置提案已拒绝时,修正 JSON 后用 propose-build --file 重提;保留原 claim 和拒绝记录,禁止 --confirmed,须使用新的 proposalHash 再执行 decide-build。未回传或非配置执行任务仍须核对原执行器。","decide-build resolves only the current proposal. Rejecting it returns to configuration; approving it stores the choices and advances to planning.","submit-plan validates the plan and its tasks.md authority before recording both the Action and evidence in the SDK Run. --pause requires an explicit continue-plan decision before execution.","continue-plan accepts only the current plan-ready proposal and rejects changes to the approved plan or tasks.","After source or plan changes, use the revision-bound revise-design or revise-plan command returned by recovery guidance; old approvals and accepted evidence cannot authorize changed content.","complete-build accepts finished full-workflow tasks and actual platform check reports through --checks before scheduling Verify.","For SDK hotfix/tweak, propose-escalation records why full Design is needed; decide-escalation applies only the current user choice. Upgrading continues the same Run and workspace through full Design.","For SDK Archive, propose-archive binds the current branch and verified change to a user decision; decide-archive accepts only its current proposal hash. A local, push, or PR choice is required before the Archive Guard can perform filesystem archiving.","Repeat --delivery-path for a complete explicit file list when this change includes pre-existing work. The original Archive proposal includes those paths for user approval. Without it, pre-existing dirty paths stay outside automatic delivery selection.","SDK 归档后,修复与归档可分成连续单父提交;从已批准 baseCommit 到交付 HEAD 的每个提交只能包含已验证实现和本次归档产物。complete-delivery 核对整个范围、最终内容和已批准的远端/PR;不执行 commit、push、建 PR 或改写历史。","For compat Design, complete-design registers the reference, refreshes handoff, and applies the guard; interrupted retries retain completed work.","Use data.artifactRefs for state references and task-authority markers; absolute paths are for file operations."],guard:["comet guard <change-name> <open|design|build|verify|archive> [--apply]","SDK-owned full Design: comet guard <change-name> design --design-doc <repo-relative-ref> [--apply --approval-hash <sha256>]","SDK Design preview reads the current proposal, handoff and document without advancing the Run; apply requires the matching user approval hash.","SDK-owned Build: comet guard <change-name> build [--apply --checks <checks-json-file> --session <builder-execution-ref>]","SDK Build preview is read-only; apply validates the actual platform reports and completed tasks before Verify. It does not infer or execute commands.","SDK-owned Verify: comet guard <change-name> verify --report <repo-relative-ref> [--apply --checks <checks-json-file>]","--session records the actual Builder session. Preserve any selected independent review and report the actual verification results.","SDK Verify preview checks the report and pending Run without advancing it; apply submits the report and actual platform checks before Archive. Failed or missing reports do not advance the Run.","SDK-owned Archive: comet guard <change-name> archive [--apply]","SDK Archive preview checks the approved delivery and current Verify evidence; apply runs preflight and OpenSpec Archive once. Commit, push, and PR delivery remain a separate pending SDK Action.","Compat Guard validates phase requirements; --apply advances the phase after all checks pass.","Compat Guard reads the latest Agent check report for this phase and Run; it never executes a detected build.","Preview does not advance the phase. Apply requires the current tasks, user approvals and accepted reports.","Repeated previews preserve the Run and reports. The Agent assesses whether changes require further checks.","Do not poll guard for status. Use comet state next <change-name> for guidance.","On failure follow the reported next action; do not blindly retry side-effecting checks.","","Examples:"," comet guard demo build --apply --json"," comet state next demo --json"],handoff:["comet handoff <change-name> design --write [--full]","References the original source files; --full explicitly generates one readable Markdown view without changing approvals."],archive:["comet archive <change-name> [--dry-run|--recover]","--recover reconciles one moved SDK Archive after the original executor has stopped; it never runs OpenSpec Archive again.","If interrupted specification synchronization has no original result receipt, review recoveryApproval.changes with the user, then use --recover --confirmed --proposal-hash <current-hash>. Changed outputs invalidate that decision; do not self-confirm."],validate:["comet classic validate <change-name>"],workspace:["comet classic workspace prepare <change-name> --isolation <current|branch|worktree> [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]","comet classic workspace resolve <change-name>"]},o={current:["comet state current","Reports the selected Classic change. Does not advance the phase."],next:["comet state next <change-name> [--details] [--continue]","Reports the next workflow action. --continue executes only recorded SDK commands and authorized internal steps, stopping for Agent work, user decisions, failures or unresolved executions.","SDK JSON includes recovery paths, configuration, compact task state and current Run handles. --details expands tasks, checkpoint content and full Run history."],select:["comet state select <change-name> [--details]","Writes the current change selection used by workflow routing.","SDK JSON includes recovery paths, configuration, compact task state and current Run handles. --details expands tasks, checkpoint content and full Run history."],rebind:["comet state rebind <change-name>","Updates the change branch binding to the current Git branch after validation."],"clear-selection":["comet state clear-selection","Clears the current change selection; does not delete change artifacts."],init:["comet state init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>]","Creates Classic workflow state. Follow the Open workflow for required user decisions."],scale:["comet state scale <change-name>","Reports a verification recommendation without changing verify_mode.","JSON: data.recommendation, data.selected and data.metrics. Scale is not a risk assessment.","Preserve an existing selection; record a new decision explicitly with state set when needed."],artifacts:["comet state artifacts <change-name>","Inspects the OpenSpec apply dependency closure, including dependencies of already-complete artifacts.","JSON: data.source, required, skipped, designRequired, files and problems. This does not execute implementation or verification.","Optional design is omitted only when the active schema excludes it from the required closure.","Skipped specs require explicit skip_specs: true, upstream support and no conflicting spec files.","Compat changes without .openspec.yaml retain the existing Classic artifact requirements."],"task-checkoff":["comet state task-checkoff <file> <task-text>","Checks that exactly one matching task is already checked. Does not write the task file or execute the task."],tasks:["comet state tasks <change-name> [--assign-ids]","Reads tasks.md as the task completion authority. Fenced examples are excluded.","--assign-ids persists IDs for legacy/new tasks in Open, Design or Build; existing IDs remain unchanged.","Assign IDs before generating the design handoff and plan. ID assignment changes task requirements.","JSON: data.authority, data.revision, data.needsIds, data.tasks and data.progress.","Each task has id, text, completed and line. Never use line/order as task identity.","Example: comet state tasks demo --assign-ids --json"],"task-complete":["comet state task-complete <change-name> <task-id> --expect <revision>","Records accepted task completion during Build; does not execute or independently verify work.","Use the revision returned by state tasks. Changed requirements reject the write; refresh and reassess the task.","Writes tasks.md under the state lock and synchronizes explicitly ID-mapped legacy plan checkboxes. Retries repair interrupted projection writes.","Reconcile code, checks and review evidence before recording completion; unchecked does not mean unimplemented.","Unmapped legacy items are preserved and reported as mapping-required; never match tasks by position or wording."],"sync-plan":["comet state sync-plan <change-name>","Synchronizes legacy plan checkboxes from tasks.md by explicit comet-task IDs; does not execute or accept work.","Rejects missing or unknown plan IDs. Reconcile extra requirements into tasks.md before mapping.","New plans should reference task IDs without a second completion checklist."],checkpoint:["comet state checkpoint <change-name> [--file <json>]","Reads a structured coordination checkpoint, or records an explicitly bounded work package during Build.","Input: taskIds, revision, stage, sessionId, evidence, unresolved, reviewRounds.","Include schemaVersion: 1. JSON state is .comet/coordination.json, separate from the Engine checkpoint.","Stages: implementing|task-review|checkoff|done|blocked. Evidence is a coordination record, not automatic acceptance.","Runtime checks task IDs and revision and renders subagent-progress.md. Do not maintain its projection manually."],delivery:["comet state delivery <change-name> [--file <json> | --verify]","Reads delivery authorization and observed progress, or records the user-authorized local|push|pr action.","Input: action, targetBranch, optional remote, commit and prUrl. Recording never performs remote writes.","First authorization requires Archive with passing verification before archival. Missing legacy authorization is never inferred.","Resume only authorized unfinished steps; supplied commit or PR text alone does not prove delivery.","compat 的 --verify 只做有界远端/PR 读取。SDK 的 --verify 使用当前 HEAD 转交 complete-delivery 校验并结束已批准的交付;已完成 Run 只核对历史回执和原提交对象,不将后续 HEAD、工作区或远端变化视为旧交付失败;普通读取不访问网络。","SDK 的 --file 仅接受与已批准 action、targetBranch、remote 一致的实际 commit 和可选 prUrl,不创建或覆盖授权。PR 首次交付使用 complete-delivery --commit <sha> --pr-url <url>,或 --file 提交完整记录。"],get:["comet state get <change-name> <field> [<field> ...]","Reads the requested fields from one state snapshot. JSON: data.change and data.fields (string values).","One field preserves the bare stdout value; multiple fields print field=value lines in request order.",`Fields: ${[...xn,...Vs].join(", ")}`,"Example: comet state get demo phase --json","Example: comet state get demo phase workflow build_mode tdd_mode review_mode --json"],set:["comet state set <change-name> <field> <value> [<field> <value> ...]","Advanced: validates all fields, then commits one atomic state update and reconciles Runtime state.","Invalid values or duplicate fields reject the whole update. Do not bypass workflow confirmations.","JSON: data.change and data.updated contain the committed field values.","Writable fields (enum values shown where applicable):",...[...rA].map(u=>` ${u}${zg[u]?`: ${zg[u].join("|")}`:u==="language"?": en|zh-CN":""}`),"Other Runtime-owned fields cannot be set manually. Artifact paths must stay within the project.","Example: comet state set demo verify_mode full","Example: comet state set demo build_mode executing-plans tdd_mode direct review_mode standard --json"],check:["comet state check <change-name> <open|design|build|verify|archive> [--recover] [--details]","Checks phase entry requirements; this is not a build/test execution command.","--recover is for cold recovery after context loss, not normal phase progression.","Recovery reads the original business state, reports and approvals; it does not replay commands or recover processes.","It preserves completed work. The Agent checks current implementation and acceptance, runs necessary checks with platform tools, and submits the actual results.","JSON entry data includes layout, configuration, configurationReadiness, nextAction, compact taskState, planMapping and checks.","--recover includes checkpoint references; --details expands tasks, checkpoint content and full SDK Run history.","Reconcile existing implementation and acceptance before dispatching work; unchecked tasks are not proof of missing implementation.","Read fresh state after changing configuration or advancing phases; do not reuse an earlier entry snapshot.","SDK entry, proposal, decision and completion results include nextAction from that Run revision, with Action, evidence or decision handles. User approval and fresh validation are still required for subsequent writes.","","Examples:"," comet state check demo build --json"," comet state check demo build --recover --json"],"revise-design":["comet state revise-design <change-name> --expected-revision <number>","Reopens SDK full Design from Design, Build, Verify, or Archive before side effects; retains implementation, configuration and decision history. Reconcile running or unknown work first.","Use the current Run revision from state next or state check --recover. A stale revision is rejected.","Then propose-design with the revised design and any agreed Spec Patch, obtain a new explicit user decision, and decide-design with the new proposal hash.","Revision does not approve the new design. Old approval hashes do not authorize changed requirements."],"reopen-verification":["comet state reopen-verification <change-name> --expected-revision <number>","保留当前修改和审计历史,取消未执行的归档或验收工作并重开 Verify;通过后必须重新批准 Archive。","仅支持尚未执行归档、活动目录仍存在且没有 running/unknown Action 的内置 SDK Run。旧 revision 不生效。"],"continue-build":["comet state continue-build <change-name> --expected-revision <number>","Resume a stopped failed Builder, or return Verify or pre-execution Archive to Build on the same SDK Run. Preserve partial work and task completion; invalidate verification and Archive authorization.","Changed full requirements still require revise-design; changed hotfix/tweak scope requires propose-escalation and a new scope decision. Never replay unknown executions."],"continue-work":["comet state continue-work <change-name> --expected-revision <number>","Create successor work for the original failed Skill on the same Run. Preserve completed stages, decisions, partial artifacts and the original failure receipt. Reject running, unknown, stale, or cancelled work."],"repair-archive":["comet state repair-archive <change-name> --expected-revision <number>","Verify that the failed Archive left its original inputs and specifications unchanged and created no archive directory, then reopen Open on the same Run. Correct the inputs and obtain fresh approval and verification. Unknown execution results must be reconciled first."],"repair-delivery":["comet state repair-delivery <change-name> --expected-revision <number> [--checks <checks-json-file>]","归档已完成、交付尚未完成时,在同一 SDK Run 补充检查输出声明并重新检查。保留原归档、业务批准和执行历史,不重放 OpenSpec。","v2:由 Agent 平台完成必要检查,通过 --checks 提交与 Build/Verify 相同格式的报告;保留原批准的路径范围,Runtime 不重跑命令。","旧 v1:在 .comet/check-policy.json 为原 Verify 命令声明 outputs,只排除原批准基线未追踪的生成物。移除这些生成物后沿原命令检查,保持原实现和归档。","随后沿 state next 的原检查请求推进,展示新的交付范围,并取得当前 proposalHash 的明确批准。旧批准不能直接完成本次修复后的交付。"],"decide-delivery-repair":["comet state decide-delivery-repair <change-name> --proposal-hash <hash> --choice <approved|later>","核对补声明的输出、原检查结果和保留的归档,再确认当前交付范围。approved 只恢复当前已核验范围的交付;later 保持等待,不提交或重做归档。"],"revise-plan":["comet state revise-plan <change-name> --expected-revision <number>","Reopens SDK full planning after accepted plan content changes, retaining completed implementation and prior evidence history.","Use the current Run revision from state next or state check --recover. A stale revision is rejected.","Then submit-plan with the revised plan and current task mapping. Use --pause when the user requested a planning pause; continue only with the new plan-ready proposal hash.","Revision does not accept the new plan or bypass task authority, design approval, or Runtime checks.","Changed requirements or task scope require revise-design and a fresh Design approval before resubmitting the plan."],restore:["comet state restore <change-name> --confirmed","Only for a copied SDK change whose state file survived but local Run history did not.","Confirm the original execution process stopped before using this command. A portable checkpoint restores the saved phase and decisions; an older state without one restarts at Open and requires fresh evidence and approvals.","Unknown external actions are not replayed. A branch binding mismatch or archived change is rejected."],"record-check":["comet state record-check <change> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","Records the actual Agent platform result for Compat; does not execute the command.","The latest report belongs to this Run and phase. A failed report cannot advance the phase or borrow an earlier success.","SDK Build/Verify accepts a checks JSON report through --checks; use the command returned by the current Run.","--cwd: relative to project root, defaults to .; must stay inside the project.","","Examples:",' comet state record-check demo verify --command "external test run" --exit-code 1'],transition:["comet state transition <change-name> <event>","SDK: comet state transition <change-name> verify-fail --reason <text>",`Events: ${i_.join(", ")}`,"Advanced: applies a state-machine event and writes workflow state. Required confirmations still apply.","This is not a substitute for the workflow Skill or phase guard. Use state next for the next action."]},s=n.find(u=>!u.startsWith("-")),c=e==="state"&&s&&o[s]||i[e];return c?`Usage: ${c.join(`
278
+ `)}
279
+ ${uH}Command placeholders must be replaced with actual values.
280
+ `:void 0}function iA(e,t){let r=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)?h:{},n=r(e),i=r(n.entry),o=r(n.run??i.run??(typeof n.runId=="string"?n:void 0)),s=r(n.state??i.state??n),c=r(n.preparation??n.workspace??i.workspace),u=r(n.continuation??i.continuation??n.nextAction??i.nextAction),f=typeof c.projectRoot=="string"&&c.projectRoot!=="."?c.projectRoot:typeof u.cwd=="string"?u.cwd:typeof n.projectRoot=="string"?n.projectRoot:typeof i.projectRoot=="string"?i.projectRoot:t??null,a=s.stateVersion??s.state_version,d=s.status??o.status,{current:p,...l}=u,m=p===void 0?u:{...l,currentRef:n.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof s.phase=="string"?s.phase:null,status:typeof d=="string"?d:null,stateVersion:typeof a=="number"?a:null,workspace:{cwd:f},continuation:Object.keys(u).length?{...m,cwd:f}:null,...Object.keys(o).length?{run:{id:typeof o.id=="string"?o.id:typeof o.runId=="string"?o.runId:null,revision:typeof o.revision=="number"?o.revision:null,status:typeof o.status=="string"?o.status:null}}:{}}}import{stripVTControlCharacters as dH}from"node:util";function oA(e,t={}){return{code:"CLASSIC_COMMAND_FAILED",message:dH(e instanceof Error?e.message:String(e)),...t}}import{randomUUID as fH}from"node:crypto";import{performance as sA}from"node:perf_hooks";var pH=7*864e5,mH=1e4;async function hH(e,t){let r=Uo(await rd(e,!0));try{r.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
281
+ CREATE TABLE IF NOT EXISTS samples (
282
+ id TEXT PRIMARY KEY, workflow TEXT NOT NULL, kind TEXT NOT NULL, command TEXT NOT NULL,
283
+ occurredAt TEXT NOT NULL, durationMs REAL NOT NULL, exitCode INTEGER NOT NULL,
284
+ gitCommands INTEGER NOT NULL, gitDurationMs REAL NOT NULL);
285
+ CREATE INDEX IF NOT EXISTS samples_time ON samples(occurredAt);
286
+ BEGIN IMMEDIATE;`),r.prepare("DELETE FROM samples WHERE occurredAt < ?").run(new Date(Date.now()-pH).toISOString()),r.prepare("INSERT INTO samples VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(fH(),t.workflow,t.kind,t.command,t.occurredAt,t.durationMs,t.exitCode,t.gitCommands,t.gitDurationMs),r.prepare("DELETE FROM samples WHERE id IN (SELECT id FROM samples ORDER BY occurredAt DESC, rowid DESC LIMIT -1 OFFSET ?)").run(mH),r.exec("COMMIT")}finally{r.close()}}async function aA(e,t){let r=sA.now(),n,i,o=!1,s=1,c=!0,{metrics:u}=await R_({projectRoot:e.projectRoot,workflow:e.workflow,kind:e.kind??"command",name:e.traceName??e.command,status:()=>{try{s=n?e.exitCode?.(n)??n.exitCode??1:e.errorExitCode?.(i)??1}catch{return c=!1,"unknown"}return s===0?"succeeded":"failed"}},()=>KE(async()=>{try{n=await t()}catch(a){o=!0,i=a}})),f=Math.max(0,sA.now()-r);try{if(!c)throw new Error("Runtime result classification unavailable");await hH(await e.projectRoot(),{workflow:e.workflow,kind:e.kind??"command",command:e.command,occurredAt:new Date().toISOString(),durationMs:f,exitCode:s,...u})}catch{}if(o)throw i;return n}function wH(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e,exitCode:t.exitCode,agent:iA(t.data),...t.data===void 0?{}:{data:t.data},...t.envelope===void 0?{}:{summary:t.envelope.summary,...t.envelope.next===void 0?{}:{next:t.envelope.next},...t.envelope.user_message===void 0?{}:{user_message:t.envelope.user_message}},...t.stdout===void 0?{}:{stdout:t.stdout},...t.stderr===void 0?{}:{stderr:t.stderr}})+`
287
+ `,...t.envelope===void 0?{}:{envelope:t.envelope}}}async function lA(e,t,r,n={}){let i=r.indexOf("--"),o=f=>i<0||f<i,s=r.some((f,a)=>o(a)&&f==="--json"),c=r.filter((f,a)=>!o(a)||f!=="--json"),u;try{let f=nA(e,c),a=()=>t(c,{json:s,invocationCwd:n.invocationCwd??process.cwd(),...n.projectRoot?{projectRoot:n.projectRoot}:{}});u=f?{exitCode:0,stdout:f}:e==="hook-guard"?await a():await UE(()=>aA({projectRoot:()=>n.projectRoot??at(n.invocationCwd??process.cwd()),workflow:"classic",command:e,errorExitCode:d=>d instanceof di?1:70},a))}catch(f){u={exitCode:f instanceof di?1:70,stderr:f instanceof Error?f.message:String(f),data:{issues:[oA(f)]}}}return s?wH(e,u):u}function uA(e,t){return async(r,n={})=>r[0]!==e?{exitCode:64,stderr:`Expected Classic command: ${e}`}:lA(e,t,r.slice(1),n)}function dA(e){let t=process.argv[1];if(!t)return!1;if(e===cA(t).href)return!0;try{return e===cA(gH(t)).href}catch{return!1}}async function fA(e,t,r=process.argv.slice(2)){let n=await lA(e,t,r);return n.stdout&&process.stdout.write(n.stdout),n.stderr&&process.stderr.write(n.stderr+(n.stderr.endsWith(`
288
+ `)?"":`
289
+ `)),n.exitCode}var qQ=uA("handoff",Jg);dA(import.meta.url)&&(process.exitCode=await fA("handoff",Jg));export{qQ as runClassicCli};