comet-dsh-plugin 0.0.0-stage → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +176 -0
- package/README.md +152 -2
- package/client.js +349 -0
- package/cordis.patch.yml +4 -0
- package/icon.png +0 -0
- package/index.js +183 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +57 -4
- package/rules/comet-workflow-guard.md +63 -0
- package/rules/migration-assets.json +218 -0
- package/server/comet-plugin-setup.mjs +192 -0
- package/skills/comet/SKILL.md +37 -0
- package/skills/comet/agents/openai.yaml +3 -0
- package/skills/comet/reference/change-walkthrough.md +77 -0
- package/skills/comet/reference/edit-review.md +26 -0
- package/skills/comet/reference/host-check.md +11 -0
- package/skills/comet/reference/platform-execution.md +34 -0
- package/skills/comet/reference/task-learning.md +39 -0
- package/skills/comet/runtime/classic/checks.yaml +6 -0
- package/skills/comet/runtime/classic/guardrails.yaml +13 -0
- package/skills/comet/runtime/classic/skill.yaml +122 -0
- package/skills/comet/scripts/comet-archive.mjs +310 -0
- package/skills/comet/scripts/comet-check.mjs +179 -0
- package/skills/comet/scripts/comet-entry-runtime.mjs +151 -0
- package/skills/comet/scripts/comet-env.mjs +15 -0
- package/skills/comet/scripts/comet-guard.mjs +335 -0
- package/skills/comet/scripts/comet-handoff.mjs +289 -0
- package/skills/comet/scripts/comet-hook-guard.mjs +294 -0
- package/skills/comet/scripts/comet-hook-router-guard.mjs +628 -0
- package/skills/comet/scripts/comet-hook-router.mjs +17 -0
- package/skills/comet/scripts/comet-intent.mjs +181 -0
- package/skills/comet/scripts/comet-plugin-hook.mjs +213 -0
- package/skills/comet/scripts/comet-resume-probe.mjs +205 -0
- package/skills/comet/scripts/comet-runtime.mjs +571 -0
- package/skills/comet/scripts/comet-state.mjs +381 -0
- package/skills/comet/scripts/comet-yaml-validate.mjs +182 -0
- package/skills/comet-any/SKILL.md +47 -0
- package/skills/comet-any/agents/openai.yaml +5 -0
- package/skills/comet-any/reference/sdk-creation.md +100 -0
- package/skills/comet-archive/SKILL.md +28 -0
- package/skills/comet-archive/agents/openai.yaml +5 -0
- package/skills/comet-archive/reference/compat.md +188 -0
- package/skills/comet-build/SKILL.md +35 -0
- package/skills/comet-build/agents/openai.yaml +5 -0
- package/skills/comet-build/reference/compat.md +191 -0
- package/skills/comet-classic/SKILL.md +98 -0
- package/skills/comet-classic/agents/openai.yaml +3 -0
- package/skills/comet-classic/reference/auto-transition.md +34 -0
- package/skills/comet-classic/reference/classic-layout.md +36 -0
- package/skills/comet-classic/reference/comet-yaml-fields.md +82 -0
- package/skills/comet-classic/reference/context-recovery.md +128 -0
- package/skills/comet-classic/reference/debug-gate.md +30 -0
- package/skills/comet-classic/reference/decision-point.md +109 -0
- package/skills/comet-classic/reference/dirty-worktree.md +59 -0
- package/skills/comet-classic/reference/file-structure.md +32 -0
- package/skills/comet-classic/reference/intent-frame.md +132 -0
- package/skills/comet-classic/reference/scripts.md +144 -0
- package/skills/comet-classic/reference/sdk-methods.md +136 -0
- package/skills/comet-classic/reference/subagent-dispatch.md +75 -0
- package/skills/comet-classic/reference/workspace.md +23 -0
- package/skills/comet-design/SKILL.md +25 -0
- package/skills/comet-design/agents/openai.yaml +5 -0
- package/skills/comet-design/reference/compat.md +191 -0
- package/skills/comet-hotfix/SKILL.md +46 -0
- package/skills/comet-hotfix/agents/openai.yaml +5 -0
- package/skills/comet-hotfix/reference/compat.md +240 -0
- package/skills/comet-memory/SKILL.md +68 -0
- package/skills/comet-memory/agents/openai.yaml +5 -0
- package/skills/comet-native/SKILL.md +139 -0
- package/skills/comet-native/agents/openai.yaml +3 -0
- package/skills/comet-native/reference/artifacts.md +118 -0
- package/skills/comet-native/reference/clarification.md +120 -0
- package/skills/comet-native/reference/commands.md +321 -0
- package/skills/comet-native/reference/edit-review.md +26 -0
- package/skills/comet-native/reference/recovery.md +64 -0
- package/skills/comet-native/reference/workspace.md +70 -0
- package/skills/comet-native/scripts/comet-native-archive.mjs +475 -0
- package/skills/comet-native/scripts/comet-native-cancel.mjs +461 -0
- package/skills/comet-native/scripts/comet-native-doctor.mjs +475 -0
- package/skills/comet-native/scripts/comet-native-hook-guard.mjs +470 -0
- package/skills/comet-native/scripts/comet-native-init.mjs +465 -0
- package/skills/comet-native/scripts/comet-native-new.mjs +478 -0
- package/skills/comet-native/scripts/comet-native-next.mjs +464 -0
- package/skills/comet-native/scripts/comet-native-root.mjs +472 -0
- package/skills/comet-native/scripts/comet-native-runtime.mjs +525 -0
- package/skills/comet-native/scripts/comet-native-select.mjs +468 -0
- package/skills/comet-native/scripts/comet-native-show.mjs +462 -0
- package/skills/comet-native/scripts/comet-native-spec.mjs +468 -0
- package/skills/comet-native/scripts/comet-native-status.mjs +467 -0
- package/skills/comet-native/scripts/comet-native-transfer.mjs +466 -0
- package/skills/comet-open/SKILL.md +265 -0
- package/skills/comet-open/agents/openai.yaml +5 -0
- package/skills/comet-open/reference/batch-changes.md +51 -0
- package/skills/comet-review/SKILL.md +121 -0
- package/skills/comet-review/agents/openai.yaml +5 -0
- package/skills/comet-tweak/SKILL.md +49 -0
- package/skills/comet-tweak/agents/openai.yaml +5 -0
- package/skills/comet-tweak/reference/compat.md +232 -0
- package/skills/comet-verify/SKILL.md +30 -0
- package/skills/comet-verify/agents/openai.yaml +5 -0
- package/skills/comet-verify/reference/compat.md +202 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var X_=Object.create;var zf=Object.defineProperty;var Q_=Object.getOwnPropertyDescriptor;var Z_=Object.getOwnPropertyNames;var eP=Object.getPrototypeOf,tP=Object.prototype.hasOwnProperty;var pl=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ie=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var _=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},nP=(e,t)=>{for(var n in t)zf(e,n,{get:t[n],enumerable:!0})},rP=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Z_(t))!tP.call(e,i)&&i!==n&&zf(e,i,{get:()=>t[i],enumerable:!(r=Q_(t,i))||r.enumerable});return e};var Rt=(e,t,n)=>(n=e!=null?X_(eP(e)):{},rP(t||!e||!e.__esModule?zf(n,"default",{value:e,enumerable:!0}):n,e));var Re=_(Ct=>{"use strict";var Gf=Symbol.for("yaml.alias"),Jy=Symbol.for("yaml.document"),ml=Symbol.for("yaml.map"),Gy=Symbol.for("yaml.pair"),Yf=Symbol.for("yaml.scalar"),hl=Symbol.for("yaml.seq"),Sr=Symbol.for("yaml.node.type"),iP=e=>!!e&&typeof e=="object"&&e[Sr]===Gf,sP=e=>!!e&&typeof e=="object"&&e[Sr]===Jy,oP=e=>!!e&&typeof e=="object"&&e[Sr]===ml,aP=e=>!!e&&typeof e=="object"&&e[Sr]===Gy,Yy=e=>!!e&&typeof e=="object"&&e[Sr]===Yf,cP=e=>!!e&&typeof e=="object"&&e[Sr]===hl;function Xy(e){if(e&&typeof e=="object")switch(e[Sr]){case ml:case hl:return!0}return!1}function lP(e){if(e&&typeof e=="object")switch(e[Sr]){case Gf:case ml:case Yf:case hl:return!0}return!1}var uP=e=>(Yy(e)||Xy(e))&&!!e.anchor;Ct.ALIAS=Gf;Ct.DOC=Jy;Ct.MAP=ml;Ct.NODE_TYPE=Sr;Ct.PAIR=Gy;Ct.SCALAR=Yf;Ct.SEQ=hl;Ct.hasAnchor=uP;Ct.isAlias=iP;Ct.isCollection=Xy;Ct.isDocument=sP;Ct.isMap=oP;Ct.isNode=lP;Ct.isPair=aP;Ct.isScalar=Yy;Ct.isSeq=cP});var na=_(Xf=>{"use strict";var gt=Re(),Yt=Symbol("break visit"),Qy=Symbol("skip children"),or=Symbol("remove node");function gl(e,t){let n=Zy(t);gt.isDocument(e)?Js(null,e.contents,n,Object.freeze([e]))===or&&(e.contents=null):Js(null,e,n,Object.freeze([]))}gl.BREAK=Yt;gl.SKIP=Qy;gl.REMOVE=or;function Js(e,t,n,r){let i=ev(e,t,n,r);if(gt.isNode(i)||gt.isPair(i))return tv(e,r,i),Js(e,i,n,r);if(typeof i!="symbol"){if(gt.isCollection(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let o=Js(s,t.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===Yt)return Yt;o===or&&(t.items.splice(s,1),s-=1)}}}else if(gt.isPair(t)){r=Object.freeze(r.concat(t));let s=Js("key",t.key,n,r);if(s===Yt)return Yt;s===or&&(t.key=null);let o=Js("value",t.value,n,r);if(o===Yt)return Yt;o===or&&(t.value=null)}}return i}async function wl(e,t){let n=Zy(t);gt.isDocument(e)?await Gs(null,e.contents,n,Object.freeze([e]))===or&&(e.contents=null):await Gs(null,e,n,Object.freeze([]))}wl.BREAK=Yt;wl.SKIP=Qy;wl.REMOVE=or;async function Gs(e,t,n,r){let i=await ev(e,t,n,r);if(gt.isNode(i)||gt.isPair(i))return tv(e,r,i),Gs(e,i,n,r);if(typeof i!="symbol"){if(gt.isCollection(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let o=await Gs(s,t.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===Yt)return Yt;o===or&&(t.items.splice(s,1),s-=1)}}}else if(gt.isPair(t)){r=Object.freeze(r.concat(t));let s=await Gs("key",t.key,n,r);if(s===Yt)return Yt;s===or&&(t.key=null);let o=await Gs("value",t.value,n,r);if(o===Yt)return Yt;o===or&&(t.value=null)}}return i}function Zy(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 ev(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(gt.isMap(t))return n.Map?.(e,t,r);if(gt.isSeq(t))return n.Seq?.(e,t,r);if(gt.isPair(t))return n.Pair?.(e,t,r);if(gt.isScalar(t))return n.Scalar?.(e,t,r);if(gt.isAlias(t))return n.Alias?.(e,t,r)}function tv(e,t,n){let r=t[t.length-1];if(gt.isCollection(r))r.items[e]=n;else if(gt.isPair(r))e==="key"?r.key=n:r.value=n;else if(gt.isDocument(r))r.contents=n;else{let i=gt.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Xf.visit=gl;Xf.visitAsync=wl});var Qf=_(rv=>{"use strict";var nv=Re(),dP=na(),fP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},pP=e=>e.replace(/[!,[\]{}]/g,t=>fP[t]),ra=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}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,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,o]=r;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,r,i]=t.match(/^(.*!)([^!]*)$/s);i||n(`The ${t} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(i)}catch(o){return n(String(o)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+pP(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),i;if(t&&r.length>0&&nv.isNode(t.contents)){let s={};dP.visit(t.contents,(o,c)=>{nv.isNode(c)&&c.tag&&(s[c.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of r)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(c=>c.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(`
|
|
5
|
+
`)}};ra.defaultYaml={explicit:!1,version:"1.2"};ra.defaultTags={"!!":"tag:yaml.org,2002:"};rv.Directives=ra});var yl=_(ia=>{"use strict";var iv=Re(),mP=na();function hP(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function sv(e){let t=new Set;return mP.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function ov(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function gP(e,t){let n=[],r=new Map,i=null;return{onAnchor:s=>{n.push(s),i??(i=sv(e));let o=ov(t,i);return i.add(o),o},setAnchors:()=>{for(let s of n){let o=r.get(s);if(typeof o=="object"&&o.anchor&&(iv.isScalar(o.node)||iv.isCollection(o.node)))o.node.anchor=o.anchor;else{let c=new Error("Failed to resolve repeated object (this should not happen)");throw c.source=s,c}}},sourceObjects:r}}ia.anchorIsValid=hP;ia.anchorNames=sv;ia.createNodeAnchors=gP;ia.findNewAnchor=ov});var Zf=_(av=>{"use strict";function sa(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,s=r.length;i<s;++i){let o=r[i],c=sa(e,r,String(i),o);c===void 0?delete r[i]:c!==o&&(r[i]=c)}else if(r instanceof Map)for(let i of Array.from(r.keys())){let s=r.get(i),o=sa(e,r,i,s);o===void 0?r.delete(i):o!==s&&r.set(i,o)}else if(r instanceof Set)for(let i of Array.from(r)){let s=sa(e,r,i,i);s===void 0?r.delete(i):s!==i&&(r.delete(i),r.add(s))}else for(let[i,s]of Object.entries(r)){let o=sa(e,r,i,s);o===void 0?delete r[i]:o!==s&&(r[i]=o)}return e.call(t,n,r)}av.applyReviver=sa});var Ur=_(lv=>{"use strict";var wP=Re();function cv(e,t,n){if(Array.isArray(e))return e.map((r,i)=>cv(r,String(i),n));if(e&&typeof e.toJSON=="function"){if(!n||!wP.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e=="bigint"&&!n?.keep?Number(e):e}lv.toJS=cv});var vl=_(dv=>{"use strict";var yP=Zf(),uv=Re(),vP=Ur(),ep=class{constructor(t){Object.defineProperty(this,uv.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:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){if(!uv.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=vP.toJS(this,"",o);if(typeof i=="function")for(let{count:l,res:f}of o.anchors.values())i(f,l);return typeof s=="function"?yP.applyReviver(s,{"":c},"",c):c}};dv.NodeBase=ep});var oa=_(fv=>{"use strict";var kP=yl(),bP=na(),Ys=Re(),RP=vl(),CP=Ur(),tp=class extends RP.NodeBase{constructor(t){super(Ys.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],bP.visit(t,{Node:(s,o)=>{(Ys.isAlias(o)||Ys.hasAnchor(o))&&r.push(o)}}),n&&(n.aliasResolveCache=r));let i;for(let s of r){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(t,n){if(!n)return{source:this.source};let{anchors:r,doc:i,maxAliasCount:s}=n,o=this.resolve(i,n);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let c=r.get(o);if(c||(CP.toJS(o,null,n),c=r.get(o)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(s>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=kl(i,o,r)),c.count*c.aliasCount>s)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return c.res}toString(t,n,r){let i=`*${this.source}`;if(t){if(kP.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${i} `}return i}};function kl(e,t,n){if(Ys.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(Ys.isCollection(t)){let r=0;for(let i of t.items){let s=kl(e,i,n);s>r&&(r=s)}return r}else if(Ys.isPair(t)){let r=kl(e,t.key,n),i=kl(e,t.value,n);return Math.max(r,i)}return 1}fv.Alias=tp});var ct=_(np=>{"use strict";var SP=Re(),EP=vl(),AP=Ur(),xP=e=>!e||typeof e!="function"&&typeof e!="object",Kr=class extends EP.NodeBase{constructor(t){super(SP.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:AP.toJS(this.value,t,n)}toString(){return String(this.value)}};Kr.BLOCK_FOLDED="BLOCK_FOLDED";Kr.BLOCK_LITERAL="BLOCK_LITERAL";Kr.PLAIN="PLAIN";Kr.QUOTE_DOUBLE="QUOTE_DOUBLE";Kr.QUOTE_SINGLE="QUOTE_SINGLE";np.Scalar=Kr;np.isScalarValue=xP});var aa=_(mv=>{"use strict";var IP=oa(),Bi=Re(),pv=ct(),_P="tag:yaml.org,2002:";function PP(e,t,n){if(t){let r=n.filter(s=>s.tag===t),i=r.find(s=>!s.format)??r[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return n.find(r=>r.identify?.(e)&&!r.format)}function OP(e,t,n){if(Bi.isDocument(e)&&(e=e.contents),Bi.isNode(e))return e;if(Bi.isPair(e)){let d=n.schema[Bi.MAP].createNode?.(n.schema,null,n);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:c}=n,l;if(r&&e&&typeof e=="object"){if(l=c.get(e),l)return l.anchor??(l.anchor=i(e)),new IP.Alias(l.anchor);l={anchor:null,node:null},c.set(e,l)}t?.startsWith("!!")&&(t=_P+t.slice(2));let f=PP(e,t,o.tags);if(!f){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new pv.Scalar(e);return l&&(l.node=d),d}f=e instanceof Map?o[Bi.MAP]:Symbol.iterator in Object(e)?o[Bi.SEQ]:o[Bi.MAP]}s&&(s(f),delete n.onTagObj);let a=f?.createNode?f.createNode(n.schema,e,n):typeof f?.nodeClass?.from=="function"?f.nodeClass.from(n.schema,e,n):new pv.Scalar(e);return t?a.tag=t:f.default||(a.tag=f.tag),l&&(l.node=a),a}mv.createNode=OP});var Rl=_(bl=>{"use strict";var TP=aa(),ar=Re(),NP=vl();function rp(e,t,n){let r=n;for(let i=t.length-1;i>=0;--i){let s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=r,r=o}else r=new Map([[s,r]])}return TP.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var hv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ip=class extends NP.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>ar.isNode(r)||ar.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(hv(t))this.add(n);else{let[r,...i]=t,s=this.get(r,!0);if(ar.isCollection(s))s.addIn(i,n);else if(s===void 0&&this.schema)this.set(r,rp(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let i=this.get(n,!0);if(ar.isCollection(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...i]=t,s=this.get(r,!0);return i.length===0?!n&&ar.isScalar(s)?s.value:s:ar.isCollection(s)?s.getIn(i,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!ar.isPair(n))return!1;let r=n.value;return r==null||t&&ar.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let i=this.get(n,!0);return ar.isCollection(i)?i.hasIn(r):!1}setIn(t,n){let[r,...i]=t;if(i.length===0)this.set(r,n);else{let s=this.get(r,!0);if(ar.isCollection(s))s.setIn(i,n);else if(s===void 0&&this.schema)this.set(r,rp(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};bl.Collection=ip;bl.collectionFromPath=rp;bl.isEmptyPath=hv});var ca=_(Cl=>{"use strict";var $P=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function sp(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var jP=(e,t,n)=>e.endsWith(`
|
|
6
|
+
`)?sp(n,t):n.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+sp(n,t):(e.endsWith(" ")?"":" ")+n;Cl.indentComment=sp;Cl.lineComment=jP;Cl.stringifyComment=$P});var wv=_(la=>{"use strict";var DP="flow",op="block",Sl="quoted";function qP(e,t,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:c}={}){if(!i||i<0)return e;i<s&&(s=0);let l=Math.max(1+s,1+i-t.length);if(e.length<=l)return e;let f=[],a={},d=i-t.length;typeof r=="number"&&(r>i-Math.max(2,s)?f.push(0):d=i-r);let p,u,m=!1,h=-1,g=-1,w=-1;n===op&&(h=gv(e,h,t.length),h!==-1&&(d=h+l));for(let y;y=e[h+=1];){if(n===Sl&&y==="\\"){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(y===`
|
|
9
|
+
`)n===op&&(h=gv(e,h,t.length)),d=h+t.length+l,p=void 0;else{if(y===" "&&u&&u!==" "&&u!==`
|
|
10
|
+
`&&u!==" "){let R=e[h+1];R&&R!==" "&&R!==`
|
|
11
|
+
`&&R!==" "&&(p=h)}if(h>=d)if(p)f.push(p),d=p+l,p=void 0;else if(n===Sl){for(;u===" "||u===" ";)u=y,y=e[h+=1],m=!0;let R=h>w+1?h-2:g-1;if(a[R])return e;f.push(R),a[R]=!0,d=R+l,p=void 0}else m=!0}u=y}if(m&&c&&c(),f.length===0)return e;o&&o();let k=e.slice(0,f[0]);for(let y=0;y<f.length;++y){let R=f[y],C=f[y+1]||e.length;R===0?k=`
|
|
12
|
+
${t}${e.slice(0,C)}`:(n===Sl&&a[R]&&(k+=`${e[R]}\\`),k+=`
|
|
13
|
+
${t}${e.slice(R+1,C)}`)}return k}function gv(e,t,n){let r=t,i=t+1,s=e[i];for(;s===" "||s===" ";)if(t<i+n)s=e[++t];else{do s=e[++t];while(s&&s!==`
|
|
14
|
+
`);r=t,i=t+1,s=e[i]}return r}la.FOLD_BLOCK=op;la.FOLD_FLOW=DP;la.FOLD_QUOTED=Sl;la.foldFlowLines=qP});var da=_(yv=>{"use strict";var Hn=ct(),zr=wv(),Al=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),xl=e=>/^(%|---|\.\.\.)/m.test(e);function LP(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let s=0,o=0;s<i;++s)if(e[s]===`
|
|
15
|
+
`){if(s-o>r)return!0;if(o=s+1,i-o<=r)return!1}return!0}function ua(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(xl(e)?" ":""),o="",c=0;for(let l=0,f=n[l];f;f=n[++l])if(f===" "&&n[l+1]==="\\"&&n[l+2]==="n"&&(o+=n.slice(c,l)+"\\ ",l+=1,c=l,f="\\"),f==="\\")switch(n[l+1]){case"u":{o+=n.slice(c,l);let a=n.substr(l+2,4);switch(a){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:a.substr(0,2)==="00"?o+="\\x"+a.substr(2):o+=n.substr(l,6)}l+=5,c=l+1}break;case"n":if(r||n[l+2]==='"'||n.length<i)l+=1;else{for(o+=n.slice(c,l)+`
|
|
16
|
+
|
|
17
|
+
`;n[l+2]==="\\"&&n[l+3]==="n"&&n[l+4]!=='"';)o+=`
|
|
18
|
+
`,l+=2;o+=s,n[l+2]===" "&&(o+="\\"),l+=1,c=l+1}break;default:l+=1}return o=c?o+n.slice(c):n,r?o:zr.foldFlowLines(o,s,zr.FOLD_QUOTED,Al(t,!1))}function ap(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return ua(e,t);let n=t.indent||(xl(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${n}`)+"'";return t.implicitKey?r:zr.foldFlowLines(r,n,zr.FOLD_FLOW,Al(t,!1))}function Xs(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=ua;else{let i=e.includes('"'),s=e.includes("'");i&&!s?r=ap:s&&!i?r=ua:r=n?ap:ua}return r(e,t)}var cp;try{cp=new RegExp(`(^|(?<!
|
|
21
|
+
))
|
|
22
|
+
+(?!
|
|
23
|
+
|$)`,"g")}catch{cp=/\n+(?!\n|$)/g}function El({comment:e,type:t,value:n},r,i,s){let{blockQuote:o,commentString:c,lineWidth:l}=r.options;if(!o||/\n[\t ]+$/.test(n))return Xs(n,r);let f=r.indent||(r.forceBlockIndent||xl(n)?" ":""),a=o==="literal"?!0:o==="folded"||t===Hn.Scalar.BLOCK_FOLDED?!1:t===Hn.Scalar.BLOCK_LITERAL?!0:!LP(n,l,f.length);if(!n)return a?`|
|
|
24
|
+
`:`>
|
|
25
|
+
`;let d,p;for(p=n.length;p>0;--p){let C=n[p-1];if(C!==`
|
|
26
|
+
`&&C!==" "&&C!==" ")break}let u=n.substring(p),m=u.indexOf(`
|
|
27
|
+
`);m===-1?d="-":n===u||m!==u.length-1?(d="+",s&&s()):d="",u&&(n=n.slice(0,-u.length),u[u.length-1]===`
|
|
28
|
+
`&&(u=u.slice(0,-1)),u=u.replace(cp,`$&${f}`));let h=!1,g,w=-1;for(g=0;g<n.length;++g){let C=n[g];if(C===" ")h=!0;else if(C===`
|
|
29
|
+
`)w=g;else break}let k=n.substring(0,w<g?w+1:g);k&&(n=n.substring(k.length),k=k.replace(/\n+/g,`$&${f}`));let R=(h?f?"2":"1":"")+d;if(e&&(R+=" "+c(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!a){let C=n.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${f}`),A=!1,q=Al(r,!0);o!=="folded"&&t!==Hn.Scalar.BLOCK_FOLDED&&(q.onOverflow=()=>{A=!0});let D=zr.foldFlowLines(`${k}${C}${u}`,f,zr.FOLD_BLOCK,q);if(!A)return`>${R}
|
|
31
|
+
${f}${D}`}return n=n.replace(/\n+/g,`$&${f}`),`|${R}
|
|
32
|
+
${f}${k}${n}${u}`}function WP(e,t,n,r){let{type:i,value:s}=e,{actualString:o,implicitKey:c,indent:l,indentStep:f,inFlow:a}=t;if(c&&s.includes(`
|
|
33
|
+
`)||a&&/[[\]{},]/.test(s))return Xs(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return c||a||!s.includes(`
|
|
34
|
+
`)?Xs(s,t):El(e,t,n,r);if(!c&&!a&&i!==Hn.Scalar.PLAIN&&s.includes(`
|
|
35
|
+
`))return El(e,t,n,r);if(xl(s)){if(l==="")return t.forceBlockIndent=!0,El(e,t,n,r);if(c&&l===f)return Xs(s,t)}let d=s.replace(/\n+/g,`$&
|
|
36
|
+
${l}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:u,tags:m}=t.doc.schema;if(m.some(p)||u?.some(p))return Xs(s,t)}return c?d:zr.foldFlowLines(d,l,zr.FOLD_FLOW,Al(t,!1))}function MP(e,t,n,r){let{implicitKey:i,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:c}=e;c!==Hn.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(c=Hn.Scalar.QUOTE_DOUBLE);let l=a=>{switch(a){case Hn.Scalar.BLOCK_FOLDED:case Hn.Scalar.BLOCK_LITERAL:return i||s?Xs(o.value,t):El(o,t,n,r);case Hn.Scalar.QUOTE_DOUBLE:return ua(o.value,t);case Hn.Scalar.QUOTE_SINGLE:return ap(o.value,t);case Hn.Scalar.PLAIN:return WP(o,t,n,r);default:return null}},f=l(c);if(f===null){let{defaultKeyType:a,defaultStringType:d}=t.options,p=i&&a||d;if(f=l(p),f===null)throw new Error(`Unsupported default string type ${p}`)}return f}yv.stringifyString=MP});var fa=_(lp=>{"use strict";var FP=yl(),Jr=Re(),HP=ca(),BP=da();function VP(e,t){let n=Object.assign({blockQuote:!0,commentString:HP.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function UP(e,t){if(t.tag){let i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let n,r;if(Jr.isScalar(t)){r=t.value;let i=e.filter(s=>s.identify?.(r));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}n=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else r=t,n=e.find(i=>i.nodeClass&&r instanceof i.nodeClass);if(!n){let i=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${i} value`)}return n}function KP(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],s=(Jr.isScalar(e)||Jr.isCollection(e))&&e.anchor;s&&FP.anchorIsValid(s)&&(n.add(s),i.push(`&${s}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(" ")}function zP(e,t,n,r){if(Jr.isPair(e))return e.toString(t,n,r);if(Jr.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,s=Jr.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>i=l});i??(i=UP(t.doc.schema.tags,s));let o=KP(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let c=typeof i.stringify=="function"?i.stringify(s,t,n,r):Jr.isScalar(s)?BP.stringifyString(s,t,n,r):s.toString(t,n,r);return o?Jr.isScalar(s)||c[0]==="{"||c[0]==="["?`${o} ${c}`:`${o}
|
|
37
|
+
${t.indent}${c}`:c}lp.createStringifyContext=VP;lp.stringify=zP});var Rv=_(bv=>{"use strict";var Er=Re(),vv=ct(),kv=fa(),pa=ca();function JP({key:e,value:t},n,r,i){let{allNullValues:s,doc:o,indent:c,indentStep:l,options:{commentString:f,indentSeq:a,simpleKeys:d}}=n,p=Er.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Er.isCollection(e)||!Er.isNode(e)&&typeof e=="object"){let q="With simple keys, collection cannot be used as a key value";throw new Error(q)}}let u=!d&&(!e||p&&t==null&&!n.inFlow||Er.isCollection(e)||(Er.isScalar(e)?e.type===vv.Scalar.BLOCK_FOLDED||e.type===vv.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!u&&(d||!s),indent:c+l});let m=!1,h=!1,g=kv.stringify(e,n,()=>m=!0,()=>h=!0);if(!u&&!n.inFlow&&g.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");u=!0}if(n.inFlow){if(s||t==null)return m&&r&&r(),g===""?"?":u?`? ${g}`:g}else if(s&&!d||t==null&&u)return g=`? ${g}`,p&&!m?g+=pa.lineComment(g,n.indent,f(p)):h&&i&&i(),g;m&&(p=null),u?(p&&(g+=pa.lineComment(g,n.indent,f(p))),g=`? ${g}
|
|
38
|
+
${c}:`):(g=`${g}:`,p&&(g+=pa.lineComment(g,n.indent,f(p))));let w,k,y;Er.isNode(t)?(w=!!t.spaceBefore,k=t.commentBefore,y=t.comment):(w=!1,k=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),n.implicitKey=!1,!u&&!p&&Er.isScalar(t)&&(n.indentAtStart=g.length+1),h=!1,!a&&l.length>=2&&!n.inFlow&&!u&&Er.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let R=!1,C=kv.stringify(t,n,()=>R=!0,()=>h=!0),A=" ";if(p||w||k){if(A=w?`
|
|
39
|
+
`:"",k){let q=f(k);A+=`
|
|
40
|
+
${pa.indentComment(q,n.indent)}`}C===""&&!n.inFlow?A===`
|
|
41
|
+
`&&y&&(A=`
|
|
42
|
+
|
|
43
|
+
`):A+=`
|
|
44
|
+
${n.indent}`}else if(!u&&Er.isCollection(t)){let q=C[0],D=C.indexOf(`
|
|
45
|
+
`),K=D!==-1,L=n.inFlow??t.flow??t.items.length===0;if(K||!L){let Z=!1;if(K&&(q==="&"||q==="!")){let Y=C.indexOf(" ");q==="&"&&Y!==-1&&Y<D&&C[Y+1]==="!"&&(Y=C.indexOf(" ",Y+1)),(Y===-1||D<Y)&&(Z=!0)}Z||(A=`
|
|
46
|
+
${n.indent}`)}}else(C===""||C[0]===`
|
|
47
|
+
`)&&(A="");return g+=A+C,n.inFlow?R&&r&&r():y&&!R?g+=pa.lineComment(g,n.indent,f(y)):h&&i&&i(),g}bv.stringifyPair=JP});var dp=_(up=>{"use strict";var Cv=pl("process");function GP(e,...t){e==="debug"&&console.log(...t)}function YP(e,t){(e==="debug"||e==="warn")&&(typeof Cv.emitWarning=="function"?Cv.emitWarning(t):console.warn(t))}up.debug=GP;up.warn=YP});var Tl=_(Ol=>{"use strict";var Pl=Re(),Sv=ct(),Il="<<",_l={identify:e=>e===Il||typeof e=="symbol"&&e.description===Il,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Sv.Scalar(Symbol(Il)),{addToJSMap:Ev}),stringify:()=>Il},XP=(e,t)=>(_l.identify(t)||Pl.isScalar(t)&&(!t.type||t.type===Sv.Scalar.PLAIN)&&_l.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===_l.tag&&n.default);function Ev(e,t,n){let r=Av(e,n);if(Pl.isSeq(r))for(let i of r.items)fp(e,t,i);else if(Array.isArray(r))for(let i of r)fp(e,t,i);else fp(e,t,r)}function fp(e,t,n){let r=Av(e,n);if(!Pl.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,e,Map);for(let[s,o]of i)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Av(e,t){return e&&Pl.isAlias(t)?t.resolve(e.doc,e):t}Ol.addMergeToJSMap=Ev;Ol.isMergeKey=XP;Ol.merge=_l});var mp=_(_v=>{"use strict";var QP=dp(),xv=Tl(),ZP=fa(),Iv=Re(),pp=Ur();function eO(e,t,{key:n,value:r}){if(Iv.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(xv.isMergeKey(e,n))xv.addMergeToJSMap(e,t,r);else{let i=pp.toJS(n,"",e);if(t instanceof Map)t.set(i,pp.toJS(r,i,e));else if(t instanceof Set)t.add(i);else{let s=tO(n,i,e),o=pp.toJS(r,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function tO(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Iv.isNode(e)&&n?.doc){let r=ZP.createStringifyContext(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=e.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),QP.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(t)}_v.addPairToJSMap=eO});var Gr=_(hp=>{"use strict";var Pv=aa(),nO=Rv(),rO=mp(),Nl=Re();function iO(e,t,n){let r=Pv.createNode(e,void 0,n),i=Pv.createNode(t,void 0,n);return new $l(r,i)}var $l=class e{constructor(t,n=null){Object.defineProperty(this,Nl.NODE_TYPE,{value:Nl.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return Nl.isNode(n)&&(n=n.clone(t)),Nl.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return rO.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?nO.stringifyPair(this,t,n,r):JSON.stringify(this)}};hp.Pair=$l;hp.createPair=iO});var gp=_(Tv=>{"use strict";var Vi=Re(),Ov=fa(),jl=ca();function sO(e,t,n){return(t.inFlow??e.flow?aO:oO)(e,t,n)}function oO({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:c}){let{indent:l,options:{commentString:f}}=n,a=Object.assign({},n,{indent:s,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(Vi.isNode(h))!d&&h.spaceBefore&&p.push(""),Dl(n,p,h.commentBefore,d),h.comment&&(g=h.comment);else if(Vi.isPair(h)){let k=Vi.isNode(h.key)?h.key:null;k&&(!d&&k.spaceBefore&&p.push(""),Dl(n,p,k.commentBefore,d))}d=!1;let w=Ov.stringify(h,a,()=>g=null,()=>d=!0);g&&(w+=jl.lineComment(w,s,f(g))),d&&g&&(d=!1),p.push(r+w)}let u;if(p.length===0)u=i.start+i.end;else{u=p[0];for(let m=1;m<p.length;++m){let h=p[m];u+=h?`
|
|
48
|
+
${l}${h}`:`
|
|
49
|
+
`}}return e?(u+=`
|
|
50
|
+
`+jl.indentComment(f(e),l),c&&c()):d&&o&&o(),u}function aO({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:c}}=t;r+=s;let l=Object.assign({},t,{indent:r,inFlow:!0,type:null}),f=!1,a=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(Vi.isNode(h))h.spaceBefore&&d.push(""),Dl(t,d,h.commentBefore,!1),h.comment&&(g=h.comment);else if(Vi.isPair(h)){let k=Vi.isNode(h.key)?h.key:null;k&&(k.spaceBefore&&d.push(""),Dl(t,d,k.commentBefore,!1),k.comment&&(f=!0));let y=Vi.isNode(h.value)?h.value:null;y?(y.comment&&(g=y.comment),y.commentBefore&&(f=!0)):h.value==null&&k?.comment&&(g=k.comment)}g&&(f=!0);let w=Ov.stringify(h,l,()=>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,y)=>k+y.length+2,2)+(w.length+2)>t.options.lineWidth)),f&&(w+=",")),g&&(w+=jl.lineComment(w,r,c(g))),d.push(w),a=d.length}let{start:p,end:u}=n;if(d.length===0)return p+u;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
|
+
${s}${i}${h}`:`
|
|
53
|
+
`;return`${m}
|
|
54
|
+
${i}${u}`}else return`${p}${o}${d.join(" ")}${o}${u}`}function Dl({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let s=jl.indentComment(t(r),e);n.push(s.trimStart())}}Tv.stringifyCollection=sO});var Xr=_(yp=>{"use strict";var cO=gp(),lO=mp(),uO=Rl(),Yr=Re(),ql=Gr(),dO=ct();function ma(e,t){let n=Yr.isScalar(t)?t.value:t;for(let r of e)if(Yr.isPair(r)&&(r.key===t||r.key===n||Yr.isScalar(r.key)&&r.key.value===n))return r}var wp=class extends uO.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Yr.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:i,replacer:s}=r,o=new this(t),c=(l,f)=>{if(typeof s=="function")f=s.call(n,l,f);else if(Array.isArray(s)&&!s.includes(l))return;(f!==void 0||i)&&o.items.push(ql.createPair(l,f,r))};if(n instanceof Map)for(let[l,f]of n)c(l,f);else if(n&&typeof n=="object")for(let l of Object.keys(n))c(l,n[l]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,n){let r;Yr.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new ql.Pair(t,t?.value):r=new ql.Pair(t.key,t.value);let i=ma(this.items,r.key),s=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${r.key} already set`);Yr.isScalar(i.value)&&dO.isScalarValue(r.value)?i.value.value=r.value:i.value=r.value}else if(s){let o=this.items.findIndex(c=>s(r,c)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let n=ma(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let i=ma(this.items,t)?.value;return(!n&&Yr.isScalar(i)?i.value:i)??void 0}has(t){return!!ma(this.items,t)}set(t,n){this.add(new ql.Pair(t,n),!0)}toJSON(t,n,r){let i=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(i);for(let s of this.items)lO.addPairToJSMap(n,i,s);return i}toString(t,n,r){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Yr.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})),cO.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};yp.YAMLMap=wp;yp.findPair=ma});var Qs=_($v=>{"use strict";var fO=Re(),Nv=Xr(),pO={collection:"map",default:!0,nodeClass:Nv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return fO.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>Nv.YAMLMap.from(e,t,n)};$v.map=pO});var Qr=_(jv=>{"use strict";var mO=aa(),hO=gp(),gO=Rl(),Wl=Re(),wO=ct(),yO=Ur(),vp=class extends gO.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Wl.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Ll(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Ll(t);if(typeof r!="number")return;let i=this.items[r];return!n&&Wl.isScalar(i)?i.value:i}has(t){let n=Ll(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Ll(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[r];Wl.isScalar(i)&&wO.isScalarValue(n)?i.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let i=0;for(let s of this.items)r.push(yO.toJS(s,String(i++),n));return r}toString(t,n,r){return t?hO.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:i}=r,s=new this(t);if(n&&Symbol.iterator in Object(n)){let o=0;for(let c of n){if(typeof i=="function"){let l=n instanceof Set?c:String(o++);c=i.call(n,l,c)}s.items.push(mO.createNode(c,void 0,r))}}return s}};function Ll(e){let t=Wl.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}jv.YAMLSeq=vp});var Zs=_(qv=>{"use strict";var vO=Re(),Dv=Qr(),kO={collection:"seq",default:!0,nodeClass:Dv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return vO.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>Dv.YAMLSeq.from(e,t,n)};qv.seq=kO});var ha=_(Lv=>{"use strict";var bO=da(),RO={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),bO.stringifyString(e,t,n,r)}};Lv.string=RO});var Ml=_(Fv=>{"use strict";var Wv=ct(),Mv={identify:e=>e==null,createNode:()=>new Wv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Wv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Mv.test.test(e)?e:t.options.nullStr};Fv.nullTag=Mv});var kp=_(Bv=>{"use strict";var CO=ct(),Hv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new CO.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&Hv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};Bv.boolTag=Hv});var eo=_(Vv=>{"use strict";function SO({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let i=typeof r=="number"?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let c=t-(s.length-o-1);for(;c-- >0;)s+="0"}return s}Vv.stringifyNumber=SO});var Rp=_(Fl=>{"use strict";var EO=ct(),bp=eo(),AO={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:bp.stringifyNumber},xO={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():bp.stringifyNumber(e)}},IO={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 EO.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:bp.stringifyNumber};Fl.float=IO;Fl.floatExp=xO;Fl.floatNaN=AO});var Sp=_(Bl=>{"use strict";var Uv=eo(),Hl=e=>typeof e=="bigint"||Number.isInteger(e),Cp=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Kv(e,t,n){let{value:r}=e;return Hl(r)&&r>=0?n+r.toString(t):Uv.stringifyNumber(e)}var _O={identify:e=>Hl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Cp(e,2,8,n),stringify:e=>Kv(e,8,"0o")},PO={identify:Hl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Cp(e,0,10,n),stringify:Uv.stringifyNumber},OO={identify:e=>Hl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Cp(e,2,16,n),stringify:e=>Kv(e,16,"0x")};Bl.int=PO;Bl.intHex=OO;Bl.intOct=_O});var Jv=_(zv=>{"use strict";var TO=Qs(),NO=Ml(),$O=Zs(),jO=ha(),DO=kp(),Ep=Rp(),Ap=Sp(),qO=[TO.map,$O.seq,jO.string,NO.nullTag,DO.boolTag,Ap.intOct,Ap.int,Ap.intHex,Ep.floatNaN,Ep.floatExp,Ep.float];zv.schema=qO});var Xv=_(Yv=>{"use strict";var LO=ct(),WO=Qs(),MO=Zs();function Gv(e){return typeof e=="bigint"||Number.isInteger(e)}var Vl=({value:e})=>JSON.stringify(e),FO=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Vl},{identify:e=>e==null,createNode:()=>new LO.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Vl},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Vl},{identify:Gv,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Gv(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:Vl}],HO={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},BO=[WO.map,MO.seq].concat(FO,HO);Yv.schema=BO});var Ip=_(Qv=>{"use strict";var ga=pl("buffer"),xp=ct(),VO=da(),UO={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ga.Buffer=="function")return ga.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,i,s){if(!n)return"";let o=n,c;if(typeof ga.Buffer=="function")c=o instanceof ga.Buffer?o.toString("base64"):ga.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let f=0;f<o.length;++f)l+=String.fromCharCode(o[f]);c=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=xp.Scalar.BLOCK_LITERAL),t!==xp.Scalar.QUOTE_DOUBLE){let l=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),f=Math.ceil(c.length/l),a=new Array(f);for(let d=0,p=0;d<f;++d,p+=l)a[d]=c.substr(p,l);c=a.join(t===xp.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return VO.stringifyString({comment:e,type:t,value:c},r,i,s)}};Qv.binary=UO});var zl=_(Kl=>{"use strict";var Ul=Re(),_p=Gr(),KO=ct(),zO=Qr();function Zv(e,t){if(Ul.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Ul.isPair(r)){if(Ul.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let i=r.items[0]||new _p.Pair(new KO.Scalar(null));if(r.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${r.commentBefore}
|
|
56
|
+
${i.key.commentBefore}`:r.commentBefore),r.comment){let s=i.value??i.key;s.comment=s.comment?`${r.comment}
|
|
57
|
+
${s.comment}`:r.comment}r=i}e.items[n]=Ul.isPair(r)?r:new _p.Pair(r)}}else t("Expected a sequence for this tag");return e}function ek(e,t,n){let{replacer:r}=n,i=new zO.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(s++),o));let c,l;if(Array.isArray(o))if(o.length===2)c=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let f=Object.keys(o);if(f.length===1)c=f[0],l=o[c];else throw new TypeError(`Expected tuple with one key, not ${f.length} keys`)}else c=o;i.items.push(_p.createPair(c,l,n))}return i}var JO={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zv,createNode:ek};Kl.createPairs=ek;Kl.pairs=JO;Kl.resolvePairs=Zv});var Tp=_(Op=>{"use strict";var tk=Re(),Pp=Ur(),wa=Xr(),GO=Qr(),nk=zl(),Ui=class e extends GO.YAMLSeq{constructor(){super(),this.add=wa.YAMLMap.prototype.add.bind(this),this.delete=wa.YAMLMap.prototype.delete.bind(this),this.get=wa.YAMLMap.prototype.get.bind(this),this.has=wa.YAMLMap.prototype.has.bind(this),this.set=wa.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let i of this.items){let s,o;if(tk.isPair(i)?(s=Pp.toJS(i.key,"",n),o=Pp.toJS(i.value,s,n)):s=Pp.toJS(i,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,o)}return r}static from(t,n,r){let i=nk.createPairs(t,n,r),s=new this;return s.items=i.items,s}};Ui.tag="tag:yaml.org,2002:omap";var YO={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ui,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=nk.resolvePairs(e,t),r=[];for(let{key:i}of n.items)tk.isScalar(i)&&(r.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new Ui,n)},createNode:(e,t,n)=>Ui.from(e,t,n)};Op.YAMLOMap=Ui;Op.omap=YO});var ak=_(Np=>{"use strict";var rk=ct();function ik({value:e,source:t},n){return t&&(e?sk:ok).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var sk={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 rk.Scalar(!0),stringify:ik},ok={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 rk.Scalar(!1),stringify:ik};Np.falseTag=ok;Np.trueTag=sk});var ck=_(Jl=>{"use strict";var XO=ct(),$p=eo(),QO={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:$p.stringifyNumber},ZO={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():$p.stringifyNumber(e)}},e0={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 XO.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:$p.stringifyNumber};Jl.float=e0;Jl.floatExp=ZO;Jl.floatNaN=QO});var uk=_(va=>{"use strict";var lk=eo(),ya=e=>typeof e=="bigint"||Number.isInteger(e);function Gl(e,t,n,{intAsBigInt:r}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return i==="-"?BigInt(-1)*o:o}let s=parseInt(e,n);return i==="-"?-1*s:s}function jp(e,t,n){let{value:r}=e;if(ya(r)){let i=r.toString(t);return r<0?"-"+n+i.substr(1):n+i}return lk.stringifyNumber(e)}var t0={identify:ya,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Gl(e,2,2,n),stringify:e=>jp(e,2,"0b")},n0={identify:ya,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Gl(e,1,8,n),stringify:e=>jp(e,8,"0")},r0={identify:ya,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Gl(e,0,10,n),stringify:lk.stringifyNumber},i0={identify:ya,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Gl(e,2,16,n),stringify:e=>jp(e,16,"0x")};va.int=r0;va.intBin=t0;va.intHex=i0;va.intOct=n0});var qp=_(Dp=>{"use strict";var Ql=Re(),Yl=Gr(),Xl=Xr(),Ki=class e extends Xl.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;Ql.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Yl.Pair(t.key,null):n=new Yl.Pair(t,null),Xl.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=Xl.findPair(this.items,t);return!n&&Ql.isPair(r)?Ql.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=Xl.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Yl.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:i}=r,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof i=="function"&&(o=i.call(n,o,o)),s.items.push(Yl.createPair(o,null,r));return s}};Ki.tag="tag:yaml.org,2002:set";var s0={collection:"map",identify:e=>e instanceof Set,nodeClass:Ki,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Ki.from(e,t,n),resolve(e,t){if(Ql.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ki,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Dp.YAMLSet=Ki;Dp.set=s0});var Wp=_(Zl=>{"use strict";var o0=eo();function Lp(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,i=o=>t?BigInt(o):Number(o),s=r.replace(/_/g,"").split(":").reduce((o,c)=>o*i(60)+i(c),i(0));return n==="-"?i(-1)*s:s}function dk(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return o0.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let i=n(60),s=[t%i];return t<60?s.unshift(0):(t=(t-s[0])/i,s.unshift(t%i),t>=60&&(t=(t-s[0])/i,s.unshift(t))),r+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var a0={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:n})=>Lp(e,n),stringify:dk},c0={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=>Lp(e,!1),stringify:dk},fk={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(fk.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,i,s,o,c]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,f=Date.UTC(n,r-1,i,s||0,o||0,c||0,l),a=t[8];if(a&&a!=="Z"){let d=Lp(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$/,"")??""};Zl.floatTime=c0;Zl.intTime=a0;Zl.timestamp=fk});var hk=_(mk=>{"use strict";var l0=Qs(),u0=Ml(),d0=Zs(),f0=ha(),p0=Ip(),pk=ak(),Mp=ck(),eu=uk(),m0=Tl(),h0=Tp(),g0=zl(),w0=qp(),Fp=Wp(),y0=[l0.map,d0.seq,f0.string,u0.nullTag,pk.trueTag,pk.falseTag,eu.intBin,eu.intOct,eu.int,eu.intHex,Mp.floatNaN,Mp.floatExp,Mp.float,p0.binary,m0.merge,h0.omap,g0.pairs,w0.set,Fp.intTime,Fp.floatTime,Fp.timestamp];mk.schema=y0});var Ek=_(Vp=>{"use strict";var vk=Qs(),v0=Ml(),kk=Zs(),k0=ha(),b0=kp(),Hp=Rp(),Bp=Sp(),R0=Jv(),C0=Xv(),bk=Ip(),ka=Tl(),Rk=Tp(),Ck=zl(),gk=hk(),Sk=qp(),tu=Wp(),wk=new Map([["core",R0.schema],["failsafe",[vk.map,kk.seq,k0.string]],["json",C0.schema],["yaml11",gk.schema],["yaml-1.1",gk.schema]]),yk={binary:bk.binary,bool:b0.boolTag,float:Hp.float,floatExp:Hp.floatExp,floatNaN:Hp.floatNaN,floatTime:tu.floatTime,int:Bp.int,intHex:Bp.intHex,intOct:Bp.intOct,intTime:tu.intTime,map:vk.map,merge:ka.merge,null:v0.nullTag,omap:Rk.omap,pairs:Ck.pairs,seq:kk.seq,set:Sk.set,timestamp:tu.timestamp},S0={"tag:yaml.org,2002:binary":bk.binary,"tag:yaml.org,2002:merge":ka.merge,"tag:yaml.org,2002:omap":Rk.omap,"tag:yaml.org,2002:pairs":Ck.pairs,"tag:yaml.org,2002:set":Sk.set,"tag:yaml.org,2002:timestamp":tu.timestamp};function E0(e,t,n){let r=wk.get(t);if(r&&!e)return n&&!r.includes(ka.merge)?r.concat(ka.merge):r.slice();let i=r;if(!i)if(Array.isArray(e))i=[];else{let s=Array.from(wk.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)i=i.concat(s);else typeof e=="function"&&(i=e(i.slice()));return n&&(i=i.concat(ka.merge)),i.reduce((s,o)=>{let c=typeof o=="string"?yk[o]:o;if(!c){let l=JSON.stringify(o),f=Object.keys(yk).map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${f}`)}return s.includes(c)||s.push(c),s},[])}Vp.coreKnownTags=S0;Vp.getTags=E0});var zp=_(Ak=>{"use strict";var Up=Re(),A0=Qs(),x0=Zs(),I0=ha(),nu=Ek(),_0=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Kp=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:c}){this.compat=Array.isArray(t)?nu.getTags(t,"compat"):t?nu.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?nu.coreKnownTags:{},this.tags=nu.getTags(n,this.name,r),this.toStringOptions=c??null,Object.defineProperty(this,Up.MAP,{value:A0.map}),Object.defineProperty(this,Up.SCALAR,{value:I0.string}),Object.defineProperty(this,Up.SEQ,{value:x0.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?_0:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ak.Schema=Kp});var Ik=_(xk=>{"use strict";var P0=Re(),Jp=fa(),ba=ca();function O0(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(n.push(l),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let i=Jp.createStringifyContext(e,t),{commentString:s}=i.options;if(e.commentBefore){n.length!==1&&n.unshift("");let l=s(e.commentBefore);n.unshift(ba.indentComment(l,""))}let o=!1,c=null;if(e.contents){if(P0.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let a=s(e.contents.commentBefore);n.push(ba.indentComment(a,""))}i.forceBlockIndent=!!e.comment,c=e.contents.comment}let l=c?void 0:()=>o=!0,f=Jp.stringify(e.contents,i,()=>c=null,l);c&&(f+=ba.lineComment(f,"",s(c))),(f[0]==="|"||f[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${f}`:n.push(f)}else n.push(Jp.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let l=s(e.comment);l.includes(`
|
|
58
|
+
`)?(n.push("..."),n.push(ba.indentComment(l,""))):n.push(`... ${l}`)}else n.push("...");else{let l=e.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||c)&&n[n.length-1]!==""&&n.push(""),n.push(ba.indentComment(s(l),"")))}return n.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}xk.stringifyDocument=O0});var Ra=_(_k=>{"use strict";var T0=oa(),to=Rl(),kn=Re(),N0=Gr(),$0=Ur(),j0=zp(),D0=Ik(),Gp=yl(),q0=Zf(),L0=aa(),Yp=Qf(),Xp=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,kn.NODE_TYPE,{value:kn.DOC});let i=null;typeof n=="function"||Array.isArray(n)?i=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:o}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Yp.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,i,r)}clone(){let t=Object.create(e.prototype,{[kn.NODE_TYPE]:{value:kn.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=kn.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){no(this.contents)&&this.contents.add(t)}addIn(t,n){no(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Gp.anchorNames(this);t.anchor=!n||r.has(n)?Gp.findNewAnchor(n||"a",r):n}return new T0.Alias(t.anchor)}createNode(t,n,r){let i;if(typeof n=="function")t=n.call({"":t},"",t),i=n;else if(Array.isArray(n)){let g=k=>typeof k=="number"||k instanceof String||k instanceof Number,w=n.filter(g).map(String);w.length>0&&(n=n.concat(w)),i=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:c,keepUndefined:l,onTagObj:f,tag:a}=r??{},{onAnchor:d,setAnchors:p,sourceObjects:u}=Gp.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:s??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:f,replacer:i,schema:this.schema,sourceObjects:u},h=L0.createNode(t,a,m);return c&&kn.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,n,r={}){let i=this.createNode(t,null,r),s=this.createNode(n,null,r);return new N0.Pair(i,s)}delete(t){return no(this.contents)?this.contents.delete(t):!1}deleteIn(t){return to.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):no(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return kn.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return to.isEmptyPath(t)?!n&&kn.isScalar(this.contents)?this.contents.value:this.contents:kn.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return kn.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return to.isEmptyPath(t)?this.contents!==void 0:kn.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=to.collectionFromPath(this.schema,[t],n):no(this.contents)&&this.contents.set(t,n)}setIn(t,n){to.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=to.collectionFromPath(this.schema,Array.from(t),n):no(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Yp.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Yp.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=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(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new j0.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:i,onAnchor:s,reviver:o}={}){let c={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},l=$0.toJS(this.contents,n??"",c);if(typeof s=="function")for(let{count:f,res:a}of c.anchors.values())s(a,f);return typeof o=="function"?q0.applyReviver(o,{"":l},"",l):l}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}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 n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return D0.stringifyDocument(this,t)}};function no(e){if(kn.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}_k.Document=Xp});var Ea=_(Sa=>{"use strict";var Ca=class extends Error{constructor(t,n,r,i){super(),this.name=t,this.code=r,this.message=i,this.pos=n}},Qp=class extends Ca{constructor(t,n,r){super("YAMLParseError",t,n,r)}},Zp=class extends Ca{constructor(t,n,r){super("YAMLWarning",t,n,r)}},W0=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(c=>t.linePos(c));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let c=Math.min(s-39,o.length-79);o="…"+o.substring(c),s-=c-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let c=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);c.length>80&&(c=c.substring(0,79)+`…
|
|
61
|
+
`),o=c+o}if(/[^ ]/.test(o)){let c=1,l=n.linePos[1];l?.line===r&&l.col>i&&(c=Math.max(1,Math.min(l.col-i,80-s)));let f=" ".repeat(s)+"^".repeat(c);n.message+=`:
|
|
62
|
+
|
|
63
|
+
${o}
|
|
64
|
+
${f}
|
|
65
|
+
`}};Sa.YAMLError=Ca;Sa.YAMLParseError=Qp;Sa.YAMLWarning=Zp;Sa.prettifyError=W0});var Aa=_(Pk=>{"use strict";function M0(e,{flow:t,indicator:n,next:r,offset:i,onError:s,parentIndent:o,startOnNewline:c}){let l=!1,f=c,a=c,d="",p="",u=!1,m=!1,h=null,g=null,w=null,k=null,y=null,R=null,C=null;for(let D of e)switch(m&&(D.type!=="space"&&D.type!=="newline"&&D.type!=="comma"&&s(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"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),D.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&D.source.includes(" ")&&(h=D),a=!0;break;case"comment":{a||s(D,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let K=D.source.substring(1)||" ";d?d+=p+K:d=K,p="",f=!1;break}case"newline":f?d?d+=D.source:(!R||n!=="seq-item-ind")&&(l=!0):p+=D.source,f=!0,u=!0,(g||w)&&(k=D),a=!0;break;case"anchor":g&&s(D,"MULTIPLE_ANCHORS","A node can have at most one anchor"),D.source.endsWith(":")&&s(D.offset+D.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=D,C??(C=D.offset),f=!1,a=!1,m=!0;break;case"tag":{w&&s(D,"MULTIPLE_TAGS","A node can have at most one tag"),w=D,C??(C=D.offset),f=!1,a=!1,m=!0;break}case n:(g||w)&&s(D,"BAD_PROP_ORDER",`Anchors and tags must be after the ${D.source} indicator`),R&&s(D,"UNEXPECTED_TOKEN",`Unexpected ${D.source} in ${t??"collection"}`),R=D,f=n==="seq-item-ind"||n==="explicit-key-ind",a=!1;break;case"comma":if(t){y&&s(D,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=D,f=!1,a=!1;break}default:s(D,"UNEXPECTED_TOKEN",`Unexpected ${D.type} token`),f=!1,a=!1}let A=e[e.length-1],q=A?A.offset+A.source.length:i;return m&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(f&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:R,spaceBefore:l,comment:d,hasNewline:u,anchor:g,tag:w,newlineAfterProp:k,end:q,start:C??q}}Pk.resolveProps=M0});var ru=_(Ok=>{"use strict";function em(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 n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(em(t.key)||em(t.value))return!0}return!1;default:return!0}}Ok.containsNewline=em});var tm=_(Tk=>{"use strict";var F0=ru();function H0(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&F0.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Tk.flowIndentCheck=H0});var nm=_($k=>{"use strict";var Nk=Re();function B0(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r=="function"?r:(s,o)=>s===o||Nk.isScalar(s)&&Nk.isScalar(o)&&s.value===o.value;return t.some(s=>i(s.key,n))}$k.mapIncludes=B0});var Mk=_(Wk=>{"use strict";var jk=Gr(),V0=Xr(),Dk=Aa(),U0=ru(),qk=tm(),K0=nm(),Lk="All mapping items must start at the same column";function z0({composeNode:e,composeEmptyNode:t},n,r,i,s){let o=s?.nodeClass??V0.YAMLMap,c=new o(n.schema);n.atRoot&&(n.atRoot=!1);let l=r.offset,f=null;for(let a of r.items){let{start:d,key:p,sep:u,value:m}=a,h=Dk.resolveProps(d,{indicator:"explicit-key-ind",next:p??u?.[0],offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0}),g=!h.found;if(g){if(p&&(p.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==r.indent&&i(l,"BAD_INDENT",Lk)),!h.anchor&&!h.tag&&!u){f=h.end,h.comment&&(c.comment?c.comment+=`
|
|
67
|
+
`+h.comment:c.comment=h.comment);continue}(h.newlineAfterProp||U0.containsNewline(p))&&i(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&i(l,"BAD_INDENT",Lk);n.atKey=!0;let w=h.end,k=p?e(n,p,h,i):t(n,w,d,null,h,i);n.schema.compat&&qk.flowIndentCheck(r.indent,p,i),n.atKey=!1,K0.mapIncludes(n,c.items,k)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let y=Dk.resolveProps(u??[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:i,parentIndent:r.indent,startOnNewline:!p||p.type==="block-scalar"});if(l=y.end,y.found){g&&(m?.type==="block-map"&&!y.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<y.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 R=m?e(n,m,y,i):t(n,l,u,null,y,i);n.schema.compat&&qk.flowIndentCheck(r.indent,m,i),l=R.range[2];let C=new jk.Pair(k,R);n.options.keepSourceTokens&&(C.srcToken=a),c.items.push(C)}else{g&&i(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(k.comment?k.comment+=`
|
|
68
|
+
`+y.comment:k.comment=y.comment);let R=new jk.Pair(k);n.options.keepSourceTokens&&(R.srcToken=a),c.items.push(R)}}return f&&f<l&&i(f,"IMPOSSIBLE","Map comment with trailing content"),c.range=[r.offset,l,f??l],c}Wk.resolveBlockMap=z0});var Hk=_(Fk=>{"use strict";var J0=Qr(),G0=Aa(),Y0=tm();function X0({composeNode:e,composeEmptyNode:t},n,r,i,s){let o=s?.nodeClass??J0.YAMLSeq,c=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset,f=null;for(let{start:a,value:d}of r.items){let p=G0.resolveProps(a,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:r.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(l,"MISSING_CHAR","Sequence item without - indicator");else{f=p.end,p.comment&&(c.comment=p.comment);continue}let u=d?e(n,d,p,i):t(n,p.end,a,null,p,i);n.schema.compat&&Y0.flowIndentCheck(r.indent,d,i),l=u.range[2],c.items.push(u)}return c.range=[r.offset,l,f??l],c}Fk.resolveBlockSeq=X0});var ro=_(Bk=>{"use strict";function Q0(e,t,n,r){let i="";if(e){let s=!1,o="";for(let c of e){let{source:l,type:f}=c;switch(f){case"space":s=!0;break;case"comment":{n&&!s&&r(c,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let a=l.substring(1)||" ";i?i+=o+a:i=a,o="";break}case"newline":i&&(o+=l),s=!0;break;default:r(c,"UNEXPECTED_TOKEN",`Unexpected ${f} at node end`)}t+=l.length}}return{comment:i,offset:t}}Bk.resolveEnd=Q0});var zk=_(Kk=>{"use strict";var Z0=Re(),eT=Gr(),Vk=Xr(),tT=Qr(),nT=ro(),Uk=Aa(),rT=ru(),iT=nm(),rm="Block collections are not allowed within flow collections",im=e=>e&&(e.type==="block-map"||e.type==="block-seq");function sT({composeNode:e,composeEmptyNode:t},n,r,i,s){let o=r.start.source==="{",c=o?"flow map":"flow sequence",l=s?.nodeClass??(o?Vk.YAMLMap:tT.YAMLSeq),f=new l(n.schema);f.flow=!0;let a=n.atRoot;a&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let g=0;g<r.items.length;++g){let w=r.items[g],{start:k,key:y,sep:R,value:C}=w,A=Uk.resolveProps(k,{flow:c,indicator:"explicit-key-ind",next:y??R?.[0],offset:d,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!R&&!C){g===0&&A.comma?i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`):g<r.items.length-1&&i(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${c}`),A.comment&&(f.comment?f.comment+=`
|
|
69
|
+
`+A.comment:f.comment=A.comment),d=A.end;continue}!o&&n.options.strict&&rT.containsNewline(y)&&i(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)A.comma&&i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`);else if(A.comma||i(A.start,"MISSING_CHAR",`Missing , between ${c} items`),A.comment){let q="";e:for(let D of k)switch(D.type){case"comma":case"space":break;case"comment":q=D.source.substring(1);break e;default:break e}if(q){let D=f.items[f.items.length-1];Z0.isPair(D)&&(D=D.value??D.key),D.comment?D.comment+=`
|
|
70
|
+
`+q:D.comment=q,A.comment=A.comment.substring(q.length+1)}}if(!o&&!R&&!A.found){let q=C?e(n,C,A,i):t(n,A.end,R,null,A,i);f.items.push(q),d=q.range[2],im(C)&&i(q.range,"BLOCK_IN_FLOW",rm)}else{n.atKey=!0;let q=A.end,D=y?e(n,y,A,i):t(n,q,k,null,A,i);im(y)&&i(D.range,"BLOCK_IN_FLOW",rm),n.atKey=!1;let K=Uk.resolveProps(R??[],{flow:c,indicator:"map-value-ind",next:C,offset:D.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(K.found){if(!o&&!A.found&&n.options.strict){if(R)for(let Y of R){if(Y===K.found)break;if(Y.type==="newline"){i(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}A.start<K.found.offset-1024&&i(K.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?i(C,"MISSING_CHAR",`Missing space after : in ${c}`):i(K.start,"MISSING_CHAR",`Missing , or : between ${c} items`));let L=C?e(n,C,K,i):K.found?t(n,K.end,R,null,K,i):null;L?im(C)&&i(L.range,"BLOCK_IN_FLOW",rm):K.comment&&(D.comment?D.comment+=`
|
|
71
|
+
`+K.comment:D.comment=K.comment);let Z=new eT.Pair(D,L);if(n.options.keepSourceTokens&&(Z.srcToken=w),o){let Y=f;iT.mapIncludes(n,Y.items,D)&&i(q,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(Z)}else{let Y=new Vk.YAMLMap(n.schema);Y.flow=!0,Y.items.push(Z);let fe=(L??D).range;Y.range=[D.range[0],fe[1],fe[2]],f.items.push(Y)}d=L?L.range[2]:K.end}}let p=o?"}":"]",[u,...m]=r.end,h=d;if(u?.source===p)h=u.offset+u.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),u&&u.source.length!==1&&m.unshift(u)}if(m.length>0){let g=nT.resolveEnd(m,h,n.options.strict,i);g.comment&&(f.comment?f.comment+=`
|
|
72
|
+
`+g.comment:f.comment=g.comment),f.range=[r.offset,h,g.offset]}else f.range=[r.offset,h,h];return f}Kk.resolveFlowCollection=sT});var Gk=_(Jk=>{"use strict";var oT=Re(),aT=ct(),cT=Xr(),lT=Qr(),uT=Mk(),dT=Hk(),fT=zk();function sm(e,t,n,r,i,s){let o=n.type==="block-map"?uT.resolveBlockMap(e,t,n,r,s):n.type==="block-seq"?dT.resolveBlockSeq(e,t,n,r,s):fT.resolveFlowCollection(e,t,n,r,s),c=o.constructor;return i==="!"||i===c.tagName?(o.tag=c.tagName,o):(i&&(o.tag=i),o)}function pT(e,t,n,r,i){let s=r.tag,o=s?t.directives.tagName(s.source,p=>i(s,"TAG_RESOLVE_FAILED",p)):null;if(n.type==="block-seq"){let{anchor:p,newlineAfterProp:u}=r,m=p&&s?p.offset>s.offset?p:s:p??s;m&&(!u||u.offset<m.offset)&&i(m,"MISSING_CHAR","Missing newline after block sequence props")}let c=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!o||o==="!"||o===cT.YAMLMap.tagName&&c==="map"||o===lT.YAMLSeq.tagName&&c==="seq")return sm(e,t,n,i,o);let l=t.schema.tags.find(p=>p.tag===o&&p.collection===c);if(!l){let p=t.schema.knownTags[o];if(p?.collection===c)t.schema.tags.push(Object.assign({},p,{default:!1})),l=p;else return p?i(s,"BAD_COLLECTION_TYPE",`${p.tag} used for ${c} collection, but expects ${p.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),sm(e,t,n,i,o)}let f=sm(e,t,n,i,o,l),a=l.resolve?.(f,p=>i(s,"TAG_RESOLVE_FAILED",p),t.options)??f,d=oT.isNode(a)?a:new aT.Scalar(a);return d.range=f.range,d.tag=o,l?.format&&(d.format=l.format),d}Jk.composeCollection=pT});var am=_(Yk=>{"use strict";var om=ct();function mT(e,t,n){let r=t.offset,i=hT(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let s=i.mode===">"?om.Scalar.BLOCK_FOLDED:om.Scalar.BLOCK_LITERAL,o=t.source?gT(t.source):[],c=o.length;for(let h=o.length-1;h>=0;--h){let g=o[h][1];if(g===""||g==="\r")c=h;else break}if(c===0){let h=i.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",g=r+i.length;return t.source&&(g+=t.source.length),{value:h,type:s,comment:i.comment,range:[r,g,g]}}let l=t.indent+i.indent,f=t.offset+i.length,a=0;for(let h=0;h<c;++h){let[g,w]=o[h];if(w===""||w==="\r")i.indent===0&&g.length>l&&(l=g.length);else{g.length<l&&n(f+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(l=g.length),a=h,l===0&&!e.atRoot&&n(f,"BAD_INDENT","Block scalar values in collections must be indented");break}f+=g.length+w.length+1}for(let h=o.length-1;h>=c;--h)o[h][0].length>l&&(c=h+1);let d="",p="",u=!1;for(let h=0;h<a;++h)d+=o[h][0].slice(l)+`
|
|
74
|
+
`;for(let h=a;h<c;++h){let[g,w]=o[h];f+=g.length+w.length+1;let k=w[w.length-1]==="\r";if(k&&(w=w.slice(0,-1)),w&&g.length<l){let R=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;n(f-w.length-(k?2:1),"BAD_INDENT",R),g=""}s===om.Scalar.BLOCK_LITERAL?(d+=p+g.slice(l)+w,p=`
|
|
75
|
+
`):g.length>l||w[0]===" "?(p===" "?p=`
|
|
76
|
+
`:!u&&p===`
|
|
77
|
+
`&&(p=`
|
|
78
|
+
|
|
79
|
+
`),d+=p+g.slice(l)+w,p=`
|
|
80
|
+
`,u=!0):w===""?p===`
|
|
81
|
+
`?d+=`
|
|
82
|
+
`:p=`
|
|
83
|
+
`:(d+=p+w,p=" ",u=!1)}switch(i.chomp){case"-":break;case"+":for(let h=c;h<o.length;++h)d+=`
|
|
84
|
+
`+o[h][0].slice(l);d[d.length-1]!==`
|
|
85
|
+
`&&(d+=`
|
|
86
|
+
`);break;default:d+=`
|
|
87
|
+
`}let m=r+i.length+t.source.length;return{value:d,type:s,comment:i.comment,range:[r,m,m]}}function hT({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],s=i[0],o=0,c="",l=-1;for(let p=1;p<i.length;++p){let u=i[p];if(!c&&(u==="-"||u==="+"))c=u;else{let m=Number(u);!o&&m?o=m:l===-1&&(l=e+p)}}l!==-1&&r(l,"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 u=t[p];switch(u.type){case"space":f=!0;case"newline":d+=u.source.length;break;case"comment":n&&!f&&r(u,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=u.source.length,a=u.source.substring(1);break;case"error":r(u,"UNEXPECTED_TOKEN",u.message),d+=u.source.length;break;default:{let m=`Unexpected token in block scalar header: ${u.type}`;r(u,"UNEXPECTED_TOKEN",m);let h=u.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:s,indent:o,chomp:c,comment:a,length:d}}function gT(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let o=1;o<t.length;o+=2)s.push([t[o],t[o+1]]);return s}Yk.resolveBlockScalar=mT});var lm=_(Qk=>{"use strict";var cm=ct(),wT=ro();function yT(e,t,n){let{offset:r,type:i,source:s,end:o}=e,c,l,f=(p,u,m)=>n(r+p,u,m);switch(i){case"scalar":c=cm.Scalar.PLAIN,l=vT(s,f);break;case"single-quoted-scalar":c=cm.Scalar.QUOTE_SINGLE,l=kT(s,f);break;case"double-quoted-scalar":c=cm.Scalar.QUOTE_DOUBLE,l=bT(s,f);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let a=r+s.length,d=wT.resolveEnd(o,a,t,n);return{value:l,type:c,comment:d.comment,range:[r,a,d.offset]}}function vT(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),Xk(e)}function kT(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Xk(e.slice(1,-1)).replace(/''/g,"'")}function Xk(e){let t,n;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
|
+
`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],s=" ",o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)r[1]===""?s===`
|
|
90
|
+
`?i+=s:s=`
|
|
91
|
+
`:(i+=s+r[1],s=" "),o=n.lastIndex;let c=/[ \t]*(.*)/sy;return c.lastIndex=o,r=c.exec(e),i+s+(r?.[1]??"")}function bT(e,t){let n="";for(let r=1;r<e.length-1;++r){let i=e[r];if(!(i==="\r"&&e[r+1]===`
|
|
92
|
+
`))if(i===`
|
|
93
|
+
`){let{fold:s,offset:o}=RT(e,r);n+=s,r=o}else if(i==="\\"){let s=e[++r],o=CT[s];if(o)n+=o;else if(s===`
|
|
94
|
+
`)for(s=e[r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="\r"&&e[r+1]===`
|
|
95
|
+
`)for(s=e[++r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="x"||s==="u"||s==="U"){let c=s==="x"?2:s==="u"?4:8;n+=ST(e,r+1,c,t),r+=c}else{let c=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),n+=c}}else if(i===" "||i===" "){let s=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&e[r+2]===`
|
|
97
|
+
`)&&(n+=r>s?e.slice(s,r+1):i)}else n+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function RT(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
98
|
+
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
99
|
+
`);)r===`
|
|
100
|
+
`&&(n+=`
|
|
101
|
+
`),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var CT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ST(e,t,n,r){let i=e.substr(t,n),o=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let c=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}Qk.resolveFlowScalar=yT});var tb=_(eb=>{"use strict";var zi=Re(),Zk=ct(),ET=am(),AT=lm();function xT(e,t,n,r){let{value:i,type:s,comment:o,range:c}=t.type==="block-scalar"?ET.resolveBlockScalar(e,t,r):AT.resolveFlowScalar(t,e.options.strict,r),l=n?e.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,f;e.options.stringKeys&&e.atKey?f=e.schema[zi.SCALAR]:l?f=IT(e.schema,i,l,n,r):t.type==="scalar"?f=_T(e,i,t,r):f=e.schema[zi.SCALAR];let a;try{let d=f.resolve(i,p=>r(n??t,"TAG_RESOLVE_FAILED",p),e.options);a=zi.isScalar(d)?d:new Zk.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);r(n??t,"TAG_RESOLVE_FAILED",p),a=new Zk.Scalar(i)}return a.range=c,a.source=i,s&&(a.type=s),l&&(a.tag=l),f.format&&(a.format=f.format),o&&(a.comment=o),a}function IT(e,t,n,r,i){if(n==="!")return e[zi.SCALAR];let s=[];for(let c of e.tags)if(!c.collection&&c.tag===n)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if(c.test?.test(t))return c;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[zi.SCALAR])}function _T({atKey:e,directives:t,schema:n},r,i,s){let o=n.tags.find(c=>(c.default===!0||e&&c.default==="key")&&c.test?.test(r))||n[zi.SCALAR];if(n.compat){let c=n.compat.find(l=>l.default&&l.test?.test(r))??n[zi.SCALAR];if(o.tag!==c.tag){let l=t.tagString(o.tag),f=t.tagString(c.tag),a=`Value may be parsed as either ${l} or ${f}`;s(i,"TAG_RESOLVE_FAILED",a,!0)}}return o}eb.composeScalar=xT});var rb=_(nb=>{"use strict";function PT(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let i=t[r];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++r];i?.type==="space";)e+=i.source.length,i=t[++r];break}}return e}nb.emptyScalarPosition=PT});var ob=_(dm=>{"use strict";var OT=oa(),TT=Re(),NT=Gk(),ib=tb(),$T=ro(),jT=rb(),DT={composeNode:sb,composeEmptyNode:um};function sb(e,t,n,r){let i=e.atKey,{spaceBefore:s,comment:o,anchor:c,tag:l}=n,f,a=!0;switch(t.type){case"alias":f=qT(e,t,r),(c||l)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":f=ib.composeScalar(e,t,l,r),c&&(f.anchor=c.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{f=NT.composeCollection(DT,e,t,n,r),c&&(f.anchor=c.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),a=!1}}return f??(f=um(e,t.offset,void 0,null,n,r)),c&&f.anchor===""&&r(c,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!TT.isScalar(f)||typeof f.value!="string"||f.tag&&f.tag!=="tag:yaml.org,2002:str")&&r(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(f.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?f.comment=o:f.commentBefore=o),e.options.keepSourceTokens&&a&&(f.srcToken=t),f}function um(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:c,end:l},f){let a={type:"scalar",offset:jT.emptyScalarPosition(t,n,r),indent:-1,source:""},d=ib.composeScalar(e,a,c,f);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&f(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=l),d}function qT({options:e},{offset:t,source:n,end:r},i){let s=new OT.Alias(n.substring(1));s.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+n.length,c=$T.resolveEnd(r,o,e.strict,i);return s.range=[t,o,c.offset],c.comment&&(s.comment=c.comment),s}dm.composeEmptyNode=um;dm.composeNode=sb});var lb=_(cb=>{"use strict";var LT=Ra(),ab=ob(),WT=ro(),MT=Aa();function FT(e,t,{offset:n,start:r,value:i,end:s},o){let c=Object.assign({_directives:t},e),l=new LT.Document(void 0,c),f={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},a=MT.resolveProps(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});a.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!a.hasNewline&&o(a.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?ab.composeNode(f,i,a,o):ab.composeEmptyNode(f,a.end,r,null,a,o);let d=l.contents.range[2],p=WT.resolveEnd(s,d,!1,o);return p.comment&&(l.comment=p.comment),l.range=[n,d,p.offset],l}cb.composeDoc=FT});var pm=_(fb=>{"use strict";var HT=pl("process"),BT=Qf(),VT=Ra(),xa=Ea(),ub=Re(),UT=lb(),KT=ro();function Ia(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:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function db(e){let t="",n=!1,r=!1;for(let i=0;i<e.length;++i){let s=e[i];switch(s[0]){case"#":t+=(t===""?"":r?`
|
|
103
|
+
|
|
104
|
+
`:`
|
|
105
|
+
`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var fm=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,i,s)=>{let o=Ia(n);s?this.warnings.push(new xa.YAMLWarning(o,r,i)):this.errors.push(new xa.YAMLParseError(o,r,i))},this.directives=new BT.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:i}=db(this.prelude);if(r){let s=t.contents;if(n)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(i||t.directives.docStart||!s)t.commentBefore=r;else if(ub.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];ub.isPair(o)&&(o=o.key);let c=o.commentBefore;o.commentBefore=c?`${r}
|
|
107
|
+
${c}`:r}else{let o=s.commentBefore;s.commentBefore=o?`${r}
|
|
108
|
+
${o}`:r}}if(n){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:db(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let i of t)yield*this.next(i);yield*this.end(n,r)}*next(t){switch(HT.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,i)=>{let s=Ia(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=UT.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new xa.YAMLParseError(Ia(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new xa.YAMLParseError(Ia(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=KT.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new xa.YAMLParseError(Ia(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),i=new VT.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,n,n],this.decorate(i,!1),yield i}}};fb.Composer=fm});var hb=_(iu=>{"use strict";var zT=am(),JT=lm(),GT=Ea(),pb=da();function YT(e,t=!0,n){if(e){let r=(i,s,o)=>{let c=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(n)n(c,s,o);else throw new GT.YAMLParseError([c,c+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return JT.resolveFlowScalar(e,t,r);case"block-scalar":return zT.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function XT(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,c=pb.stringifyString({type:o,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:r,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:s,indent:r,source:a}];return mb(p,l)||p.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:s,indent:r,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:s,indent:r,source:c,end:l};case"'":return{type:"single-quoted-scalar",offset:s,indent:r,source:c,end:l};default:return{type:"scalar",offset:s,indent:r,source:c,end:l}}}function QT(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:s=!1,type:o}=n,c="indent"in e?e.indent:null;if(r&&typeof c=="number"&&(c+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let f=e.props[0];if(f.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=f.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=pb.stringifyString({type:o,value:t},{implicitKey:i||c===null,indent:c!==null&&c>0?" ".repeat(c):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":ZT(e,l);break;case'"':mm(e,l,"double-quoted-scalar");break;case"'":mm(e,l,"single-quoted-scalar");break;default:mm(e,l,"scalar")}}function ZT(e,t){let n=t.indexOf(`
|
|
114
|
+
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let s=e.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=r,e.source=i}else{let{offset:s}=e,o="indent"in e?e.indent:-1,c=[{type:"block-scalar-header",offset:s,indent:o,source:r}];mb(c,"end"in e?e.end:void 0)||c.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:c,source:i})}}function mb(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function mm(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let s of r)s.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});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:n,source:t,end:[i]});break}default:{let r="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}iu.createScalarToken=XT;iu.resolveAsScalar=YT;iu.setScalarValue=QT});var wb=_(gb=>{"use strict";var eN=e=>"type"in e?ou(e):su(e);function ou(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=ou(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=su(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=su(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=su(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function su({start:e,key:t,sep:n,value:r}){let i="";for(let s of e)i+=s.source;if(t&&(i+=ou(t)),n)for(let s of n)i+=s.source;return r&&(i+=ou(r)),i}gb.stringify=eN});var bb=_(kb=>{"use strict";var hm=Symbol("break visit"),tN=Symbol("skip children"),yb=Symbol("remove item");function Ji(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),vb(Object.freeze([]),e,t)}Ji.BREAK=hm;Ji.SKIP=tN;Ji.REMOVE=yb;Ji.itemAtPath=(e,t)=>{let n=e;for(let[r,i]of t){let s=n?.[r];if(s&&"items"in s)n=s.items[i];else return}return n};Ji.parentCollection=(e,t)=>{let n=Ji.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function vb(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let i of["key","value"]){let s=t[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let c=vb(Object.freeze(e.concat([[i,o]])),s.items[o],n);if(typeof c=="number")o=c-1;else{if(c===hm)return hm;c===yb&&(s.items.splice(o,1),o-=1)}}typeof r=="function"&&i==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}kb.visit=Ji});var au=_(Xt=>{"use strict";var gm=hb(),nN=wb(),rN=bb(),wm="\uFEFF",ym="",vm="",km="",iN=e=>!!e&&"items"in e,sN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function oN(e){switch(e){case wm:return"<BOM>";case ym:return"<DOC>";case vm:return"<FLOW_END>";case km:return"<SCALAR>";default:return JSON.stringify(e)}}function aN(e){switch(e){case wm:return"byte-order-mark";case ym:return"doc-mode";case vm:return"flow-error-end";case km: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}Xt.createScalarToken=gm.createScalarToken;Xt.resolveAsScalar=gm.resolveAsScalar;Xt.setScalarValue=gm.setScalarValue;Xt.stringify=nN.stringify;Xt.visit=rN.visit;Xt.BOM=wm;Xt.DOCUMENT=ym;Xt.FLOW_END=vm;Xt.SCALAR=km;Xt.isCollection=iN;Xt.isScalar=sN;Xt.prettyToken=oN;Xt.tokenType=aN});var Cm=_(Cb=>{"use strict";var _a=au();function Bn(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Rb=new Set("0123456789ABCDEFabcdef"),cN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),cu=new Set(",[]{}"),lN=new Set(` ,[]{}
|
|
121
|
+
\r `),bm=e=>!e||lN.has(e),Rm=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,n=!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=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
|
|
122
|
+
`?!0:n==="\r"?this.buffer[t+1]===`
|
|
123
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let i=this.buffer[r+t+1];if(i===`
|
|
124
|
+
`||!i&&!this.atEnd)return t+r+1}return n===`
|
|
125
|
+
`||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Bn(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]===_a.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let s=t[r-1];if(s===" "||s===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let s=t[n-1];if(s===" "||s===" ")n-=1;else break}let i=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield _a.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 n=this.peek(3);if((n==="---"||n==="...")&&Bn(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Bn(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Bn(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);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(bm),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&i[0]!=="#"||r===0&&(i.startsWith("---")||i.startsWith("..."))&&Bn(i[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield _a.FLOW_END,yield*this.parseLineStart();let s=0;for(;i[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),i[s]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-s),"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(bm),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Bn(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),i=r.indexOf(`
|
|
127
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){let s=this.continueScalar(i+1);if(s===-1)break;i=r.indexOf(`
|
|
128
|
+
`,s)}i!==-1&&(n=i-(r[i-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Bn(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`
|
|
129
|
+
`:t=s,n=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
|
+
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(t+1);if(s===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,s)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(r=this.buffer[i];r===" ";)r=this.buffer[++i];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
|
+
`;)r=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let s=t-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let c=s;for(;o===" ";)o=this.buffer[--s];if(o===`
|
|
133
|
+
`&&s>=this.pos&&s+1+n>c)t=s;else break}while(!0);return yield _a.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,i;for(;i=this.buffer[++r];)if(i===":"){let s=this.buffer[r+1];if(Bn(s)||t&&cu.has(s))break;n=r}else if(Bn(i)){let s=this.buffer[r+1];if(i==="\r"&&(s===`
|
|
134
|
+
`?(r+=1,i=`
|
|
135
|
+
`,s=this.buffer[r+1]):n=r),s==="#"||t&&cu.has(s))break;if(i===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&cu.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield _a.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(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(bm),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Bn(r)||n&&cu.has(r)){n?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,n=this.buffer[t];for(;!Bn(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(cN.has(n))n=this.buffer[++t];else if(n==="%"&&Rb.has(this.buffer[t+1])&&Rb.has(this.buffer[t+2]))n=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 n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let i=n-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=n),i}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Cb.Lexer=Rm});var Em=_(Sb=>{"use strict";var Sm=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<t?n=s+1:r=s}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let i=this.lineStarts[n-1];return{line:n,col:t-i+1}}}};Sb.LineCounter=Sm});var xm=_(_b=>{"use strict";var uN=pl("process"),Eb=au(),dN=Cm();function Zr(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Ab(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 Ib(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 lu(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 io(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 uu(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function xb(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Zr(t.start,"explicit-key-ind")&&!Zr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Ib(t.value)?t.value.end?uu(t.value.end,t.sep):t.value.end=t.sep:uu(t.start,t.sep),delete t.sep)}var Am=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 dN.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,uN.env.LOG_TOKENS&&console.log("|",Eb.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=Eb.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&xb(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let i=r.items[r.items.length-1];if(i.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=n;else{Object.assign(i,{key:n,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=r.items[r.items.length-1];i.value?r.items.push({start:[],value:n}):i.value=n;break}case"flow-collection":{let i=r.items[r.items.length-1];!i||i.value?r.items.push({start:[],key:n,sep:[]}):i.sep?i.value=n:Object.assign(i,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let i=n.items[n.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&Ab(i.start)===-1&&(n.indent===0||i.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=i.start:r.items.push({start:i.start}),n.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":{Ab(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 n=this.startBlockValue(t);n?this.stack.push(n):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 n=lu(this.peek(2)),r=io(n),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}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 n=this.source.indexOf(`
|
|
139
|
+
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
140
|
+
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){uu(i,n.start),i.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,i=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&n.sep&&!n.value){let o=[];for(let c=0;c<n.sep.length;++c){let l=n.sep[c];switch(l.type){case"newline":o.push(c);break;case"space":break;case"comment":l.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||n.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):i||n.value?(s.push(this.sourceToken),t.items.push({start:s,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(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Zr(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Ib(n.key)&&!Zr(n.sep,"newline")){let o=io(n.start),c=n.key,l=n.sep;l.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:c,sep:l}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(Zr(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=io(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||i?t.items.push({start:s,key:null,sep:[this.sourceToken]}):Zr(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||n.value?(t.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!Zr(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){uu(i,n.start),i.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||Zr(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:i,sep:[]}):n.sep?this.stack.push(i):Object.assign(n,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let i=lu(r),s=io(i);xb(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let c={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=c}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
|
|
141
|
+
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
142
|
+
`,n)+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 n=lu(t),r=io(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=lu(t),r=io(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};_b.Parser=Am});var $b=_(Oa=>{"use strict";var Pb=pm(),fN=Ra(),Pa=Ea(),pN=dp(),mN=Re(),hN=Em(),Ob=xm();function Tb(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new hN.LineCounter||null,prettyErrors:t}}function gN(e,t={}){let{lineCounter:n,prettyErrors:r}=Tb(t),i=new Ob.Parser(n?.addNewLine),s=new Pb.Composer(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(let c of o)c.errors.forEach(Pa.prettifyError(e,n)),c.warnings.forEach(Pa.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Nb(e,t={}){let{lineCounter:n,prettyErrors:r}=Tb(t),i=new Ob.Parser(n?.addNewLine),s=new Pb.Composer(t),o=null;for(let c of s.compose(i.parse(e),!0,e.length))if(!o)o=c;else if(o.options.logLevel!=="silent"){o.errors.push(new Pa.YAMLParseError(c.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(Pa.prettifyError(e,n)),o.warnings.forEach(Pa.prettifyError(e,n))),o}function wN(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let i=Nb(e,n);if(!i)return null;if(i.warnings.forEach(s=>pN.warn(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function yN(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=n??t??{};if(!i)return}return mN.isDocument(e)&&!r?e.toString(n):new fN.Document(e,r,n).toString(n)}Oa.parse=wN;Oa.parseAllDocuments=gN;Oa.parseDocument=Nb;Oa.stringify=yN});var Pt=_(_e=>{"use strict";var vN=pm(),kN=Ra(),bN=zp(),Im=Ea(),RN=oa(),ei=Re(),CN=Gr(),SN=ct(),EN=Xr(),AN=Qr(),xN=au(),IN=Cm(),_N=Em(),PN=xm(),du=$b(),jb=na();_e.Composer=vN.Composer;_e.Document=kN.Document;_e.Schema=bN.Schema;_e.YAMLError=Im.YAMLError;_e.YAMLParseError=Im.YAMLParseError;_e.YAMLWarning=Im.YAMLWarning;_e.Alias=RN.Alias;_e.isAlias=ei.isAlias;_e.isCollection=ei.isCollection;_e.isDocument=ei.isDocument;_e.isMap=ei.isMap;_e.isNode=ei.isNode;_e.isPair=ei.isPair;_e.isScalar=ei.isScalar;_e.isSeq=ei.isSeq;_e.Pair=CN.Pair;_e.Scalar=SN.Scalar;_e.YAMLMap=EN.YAMLMap;_e.YAMLSeq=AN.YAMLSeq;_e.CST=xN;_e.Lexer=IN.Lexer;_e.LineCounter=_N.LineCounter;_e.Parser=PN.Parser;_e.parse=du.parse;_e.parseAllDocuments=du.parseAllDocuments;_e.parseDocument=du.parseDocument;_e.stringify=du.stringify;_e.visit=jb.visit;_e.visitAsync=jb.visitAsync});import{existsSync as _m,readFileSync as ON}from"node:fs";import bn from"node:path";function Db(e,t){let n=t.toLowerCase();return Object.entries(e).find(([r,i])=>r.toLowerCase()===n&&i!==void 0)?.[1]}function NN(e){let t=(Db(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(n=>n.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function $N(e,t,n){let i=bn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Db(t,"PATH")??"").split(bn.delimiter).map(c=>c.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=bn.win32.extname(e)?[e]:NN(t).map(c=>`${e}${c}`);return i.flatMap(c=>o.map(l=>c?bn.join(c,l):bn.resolve(n,l)))}function so(e,t,n){return $N(e,t,n).find(r=>_m(r))??e}function jN(e){let t=e.replaceAll(`\r
|
|
143
|
+
`,`
|
|
144
|
+
`).trim(),n=/^@"([^"%\r\n]+)" "%~dp0([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(t);if(n&&bn.win32.isAbsolute(n[1])&&bn.win32.basename(n[1]).toLowerCase()==="node.exe")return{target:n[2],nodeCommand:n[1]};let r=/^@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(r)return{target:r[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 qb(e,t,n,r=process.execPath){let i=jN(ON(e,"utf8"));if(!i)return null;let s=i.target.replace(/^[/\\]+/u,"");if(bn.win32.parse(s).root)return null;let o=bn.resolve(bn.dirname(e),s);if(!_m(o))throw new Error("Node CLI entry is missing: "+o);let c=bn.join(bn.dirname(e),"node.exe"),l={...n},f=Object.keys(l).find(d=>d.toUpperCase()==="NODE_PATH"),a=f?l[f]:void 0;return i.nodePath&&(f&&delete l[f],l.NODE_PATH=i.nodePath+(a?";"+a:"")),{command:i.nodeCommand??(_m(c)?c:r),args:[o,...t],...i.nodePath?{env:l}:{}}}function Lb(e){if(e.some(t=>TN.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var TN,wK,fu=ie(()=>{"use strict";TN=/[&|<>()^%"!\r\n]/u,wK=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{accessSync as Wb,constants as Pm,statSync as Mb,existsSync as kK,readFileSync as bK}from"node:fs";import oo from"node:path";function Om(e,t,n){if((n.platform??process.platform)!=="win32")return{command:e,args:[...t]};let r=so(e,n.env??process.env,n.cwd),i=oo.extname(r).toLowerCase();if([".mjs",".cjs",".js"].includes(i))return{command:process.execPath,args:[oo.resolve(n.cwd,r),...t]};if(i===".cmd"){let s=qb(r,t,n.env??process.env);if(s)return s}if([".cmd",".bat",".ps1"].includes(i))throw new Error(`Unsupported Node CLI shim: ${r}. Use a standard npm/pnpm .cmd launcher or the Node CLI .js/.mjs/.cjs entry; no shell fallback is allowed.`);return{command:r,args:[...t]}}function pu(e,t,n){let r=Om(e,t,n),i=n.platform??process.platform,s=r.env??n.env??process.env,o=r.command;if(!(i==="win32"?[so(o,s,n.cwd)]:o.includes("/")?[oo.resolve(n.cwd,o)]:(s.PATH??"/usr/bin:/bin").split(oo.delimiter).map(f=>oo.resolve(n.cwd,f,o))).some(f=>{try{let a=oo.resolve(n.cwd,f);return Mb(a).isFile()?(Wb(a,i==="win32"?Pm.F_OK:Pm.X_OK),!0):!1}catch{return!1}}))throw new Error(`Executable not found or not executable: ${e}`);if(r.command!==e&&r.args.length>t.length){let f=r.args[0];if(!Mb(f).isFile())throw new Error(`Node CLI entry is not a file: ${f}`);Wb(f,Pm.R_OK)}}var Tm=ie(()=>{"use strict";fu()});import{promises as DN}from"fs";async function mu(e){try{return await DN.access(e),!0}catch(t){if(qN(t))return!1;throw t}}function qN(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}var Fb=ie(()=>{"use strict"});import ti from"path";function HN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim();if(n.length===0||ti.posix.isAbsolute(n)||ti.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be a project-relative path`);if(n===".")return[];let r=n.replaceAll("\\","/").split("/");if(r.some(i=>i===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(i=>i===""||i==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function hu(e){let t=HN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Jb(e,t="docs"){let n=e??t;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function nt(e,t,n=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||ti.posix.isAbsolute(r)||ti.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let i=r.split("/");if(i.some(s=>s===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(s=>s===""||s==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Gb(e,t,n){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return r}function BN(e,t,n){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${n} must be a positive integer`);return r}function zb(e,t,n){let r=BN(e,t,n);if(r>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${n} is too large to convert to bytes safely`);return r}function VN(e){if(e===void 0)return;let t=ni(e,"native.pending_root_move"),n=t.id,r=t.from_artifact_root,i=t.to_artifact_root,s=t.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let c=ni(t.cleanup,"native.pending_root_move.cleanup"),l=c.kind,f=c.state,a=c.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="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");o={kind:l,state:f,manifestHash:a}}return{id:n,fromArtifactRoot:hu(r),toArtifactRoot:hu(i),stage:s,...o?{cleanup:o}:{}}}function UN(e){if(e===void 0)return;let t=ni(e,"native.finish");if(t.pull_request===void 0)return{};let n=ni(t.pull_request,"native.finish.pull_request");if(n.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(n.command)||n.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(n.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=n.command.map((s,o)=>{if(typeof s!="string"||s.trim().length===0||s.length>4096||/[\0\r\n]/u.test(s))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return s});if(ti.posix.isAbsolute(r[0])||ti.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=n.timeout_ms??FN;if(!Number.isSafeInteger(i)||i<1||i>Kb)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Kb}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:i}}}function KN(e,t={}){let n=ni(e,"native"),r=n.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let i=n.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??LN;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let c=n.max_parallel_children===void 0?WN:n.max_parallel_children;if(!Number.isSafeInteger(c)||c<1)throw new Error("native.max_parallel_children must be a positive integer");let l=n.document_writes??"allow";if(l!=="allow"&&l!=="revert")throw new Error("native.document_writes must be allow or revert");let f=VN(n.pending_root_move),a=UN(n.finish);return{artifact_root:hu(r),language:Gb(n.language,"en","native.language"),clarification_mode:i,archive_confirmation:s,max_verify_failures:o,max_parallel_children:c,...l==="revert"?{document_writes:l}:{},...a?{finish:a}:{},...f?{pending_root_move:f}:{}}}function zN(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>Ub)throw new Error(`${t} must be an integer between 1 and ${Ub} milliseconds`);return e}function JN(e){let t=ni(e,"classic"),n=t.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let 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&&zN(t.check_timeout_ms,"classic.check_timeout_ms");let s=t.document_evidence??"neutral";if(s!=="neutral"&&s!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Jb(t.artifact_layout),language:Gb(t.language,"zh-CN","classic.language"),context_compression:n,review_mode:r,auto_transition:i,...s==="strict"?{document_evidence:s}:{},...t.check_timeout_ms!==void 0?{check_timeout_ms:t.check_timeout_ms}:{}}}function GN(e){let n=ni(e,"hook").allow_paths??[];if(!Array.isArray(n))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(n.map((r,i)=>nt(r,`hook.allow_paths[${i}]`)))]}}function YN(e){if(e===void 0)return{...Nm};let t=ni(e,"memory"),n=t.learning??Nm.learning,r=t.retrieval??Nm.retrieval;if(typeof n!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:n,retrieval:r}}function $m(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function XN(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim();if(n.length===0||n.includes("\\")||n.includes("\0")||ti.posix.isAbsolute(n)||ti.win32.isAbsolute(n)||n.startsWith("~")||n.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!n.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(n.length>Hb)throw new Error(`${t} exceeds ${Hb} characters`);let r=0;for(let i=0;i<n.length;i+=1)n[i]==="?"?r+=1:n[i]==="*"&&(r+=1,n[i+1]==="*"&&(i+=1));if(r>Bb)throw new Error(`${t} contains more than ${Bb} wildcard tokens`);return n}function QN(e){let t=$m(e,"knowledge.local"),n=t.include??[];if(!Array.isArray(n))throw new Error("knowledge.local.include must be an array");let r={include:[...new Set(n.map((i,s)=>XN(i,`knowledge.local.include[${s}]`)))],max_file_mb:zb(t.max_file_mb,Vb.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:zb(t.max_total_mb,Vb.max_total_mb,"knowledge.local.max_total_mb")};if(r.max_file_mb>r.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return r}function ZN(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 n=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=n==="localhost"||n==="127.0.0.1"||n==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function e$(e){let t=$m(e,"knowledge.remote"),n=ZN(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))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 s=t.timeout_ms??5e3;if(typeof s!="number"||!Number.isSafeInteger(s)||s<100||s>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:n,...r===void 0?{}:{token_env:r},...i===void 0?{}:{scope:i},timeout_ms:s}}function t$(e){if(e===void 0)return{...MN};let t=$m(e,"knowledge"),n=t.provider??"local";if(n!=="local"&&n!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:QN(t.local);if(n==="local")return{provider:n,...r?{local:r}:{}};let i=t.remote===void 0?void 0:e$(t.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:n,...r?{local:r}:{},remote:i}}function Yb(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function n$(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function r$(e,t,n,r,i,s,o,c){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!c.allowPartialProject&&e.native!==void 0)||c.allowPartialProject&&!l)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:o,change_walkthrough:Yb(e.change_walkthrough),...t?{hook:t}:{},memory:n,knowledge:r,...i?{native:i}:{},...s?{classic:s}:{}}}function Xb(e){let t=(0,Rn.parseDocument)(e),n=r=>{let i=(0,Rn.isAlias)(r)?r.resolve(t):r;return(0,Rn.isScalar)(i)?i.value:void 0};return(0,Rn.isMap)(t.contents)&&t.contents.items.some(({key:r,value:i})=>n(r)==="schema"&&n(i)==="comet.project.v1")}function Gi(e,t={}){let n=(0,Rn.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let r=n.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0,change_walkthrough:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=r,s=n$(i.ambient_resume),o=Yb(i.change_walkthrough),c=i.hook===void 0?void 0:GN(i.hook),l=YN(i.memory),f=t$(i.knowledge),a=i.native===void 0?void 0:KN(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),d=i.classic===void 0?void 0:JN(i.classic),p=r$(i,c,l,f,a,d,s,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:p,ambient_resume:s,change_walkthrough:o,memory:l,knowledge:f,...c?{hook:c}:{},...a?{native:a}:{},...d?{classic:d}:{}}}var Rn,ri,Hb,Bb,LN,WN,Nm,Vb,MN,Ub,FN,Kb,Qt=ie(()=>{"use strict";Rn=Rt(Pt(),1),ri=Number.MAX_SAFE_INTEGER,Hb=1024,Bb=64,LN=5,WN=2,Nm={learning:!0,retrieval:!0},Vb={include:[],max_file_mb:1,max_total_mb:32},MN={provider:"local"},Ub=36e5,FN=12e4,Kb=6e5});function ii(e){return e!==0&&e!==0n&&e!=="0"}function gu(e,t){return ii(e.dev)&&ii(t.dev)&&ii(e.ino)&&ii(t.ino)}function Cn(e,t){let n=ii(e.dev)&&ii(t.dev);if(n&&e.dev!==t.dev)return!1;let r=ii(e.ino)&&ii(t.ino);return r&&e.ino!==t.ino?!1:n&&r?!0:e.birthtime===t.birthtime}var Ta=ie(()=>{"use strict"});import{constants as si,promises as Zt}from"fs";import{createHash as i$}from"node:crypto";function jm(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function wu(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ai(e){return{dev:e.dev,ino:e.ino,birthtime:jm(e)}}function s$(e,t){let n=ai(e),r=ai(t);return gu(n,r)?Cn(n,r):Cn(n,r)&&jm(e)===jm(t)&&wu(e)===wu(t)&&e.size===t.size}function oi(e,t){let n=r=>"mtimeNs"in r?r.mtimeNs:r.mtimeMs;return s$(e,t)&&e.size===t.size&&e.mode===t.mode&&n(e)===n(t)&&wu(e)===wu(t)}async function Yi(e,t,n={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=n.label??"file",i=n.bigint===!0,s=await Zt.lstat(e,{bigint:i});if(!s.isFile()||s.isSymbolicLink())throw new Ot("not-regular-file",`${r} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new Ot("too-large",`${r} exceeds ${t} bytes`);let o=await Zt.realpath(e);await n.verify?.("pre-open",{realPath:o,identity:ai(s)});let c=process.platform==="win32"?si.O_RDONLY:si.O_RDONLY|si.O_NOFOLLOW|si.O_NONBLOCK,l;try{l=await Zt.open(e,c)}catch(f){throw f.code==="ELOOP"?new Ot("not-regular-file",`${r} must be a regular file`,{cause:f}):f}try{let[f,a,d]=await Promise.all([l.stat({bigint:i}),Zt.lstat(e,{bigint:i}),Zt.realpath(e)]);if(!f.isFile()||!a.isFile()||a.isSymbolicLink()||d!==o||!oi(s,f)||!oi(s,a))throw new Ot("changed",`${r} changed while opening`);await n.verify?.("post-open",{realPath:d,identity:ai(f)}),await n.hooks?.afterOpen?.();let p=[],u=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let k=t+1-u,{bytesRead:y}=await l.read(m,0,Math.min(m.length,k),null);if(y===0)break;if(u+=y,u>t)throw new Ot("too-large",`${r} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,y)))}await n.hooks?.beforeFinalCheck?.();let[h,g,w]=await Promise.all([l.stat({bigint:i}),Zt.lstat(e,{bigint:i}),Zt.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||w!==o||!oi(s,h)||!oi(s,g))throw new Ot("changed",`${r} changed while reading`);return await n.verify?.("post-read",{realPath:w,identity:ai(h)}),{bytes:Buffer.concat(p,u),stat:h,realPath:w}}finally{await l.close()}}async function Qb(e,t={}){let n=t.label??"file",r=t.bigint===!0,i=await Zt.lstat(e,{bigint:r});if(!i.isFile()||i.isSymbolicLink())throw new Ot("not-regular-file",`${n} must be a regular file`);let s=await Zt.realpath(e);await t.verify?.("pre-open",{realPath:s,identity:ai(i)});let o=process.platform==="win32"?si.O_RDONLY:si.O_RDONLY|si.O_NOFOLLOW|si.O_NONBLOCK,c;try{c=await Zt.open(e,o)}catch(l){throw l.code==="ELOOP"?new Ot("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,f,a]=await Promise.all([c.stat({bigint:r}),Zt.lstat(e,{bigint:r}),Zt.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||a!==s||!oi(i,l)||!oi(i,f))throw new Ot("changed",`${n} changed while opening`);await t.verify?.("post-open",{realPath:a,identity:ai(l)}),await t.hooks?.afterOpen?.();let d=i$(t.algorithm??"sha256"),p=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:g}=await c.read(p,0,p.length,null);if(g===0)break;d.update(p.subarray(0,g))}await t.hooks?.beforeFinalCheck?.();let[u,m,h]=await Promise.all([c.stat({bigint:r}),Zt.lstat(e,{bigint:r}),Zt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||h!==s||!oi(i,u)||!oi(i,m))throw new Ot("changed",`${n} changed while reading`);return await t.verify?.("post-read",{realPath:h,identity:ai(u)}),{digest:d.digest("hex"),stat:u,realPath:h}}finally{await c.close()}}var Ot,Xi=ie(()=>{"use strict";Ta();Ot=class extends Error{reason;constructor(t,n,r){super(n,r),this.name="RaceSafeReadError",this.reason=t}}});import{AsyncLocalStorage as o$}from"node:async_hooks";function yu(){let e=Dm.getStore();return e?.active?e:null}function Zb(){yu()?.entries.clear()}async function eR(e){if(yu()!==null)return e();let t={entries:new Map,active:!0};return Dm.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function ci(e){return Dm.run({entries:new Map,active:!1},e)}function tR(e,t){let n=e;for(let r of t)n+="\0"+(typeof r=="string"?r:JSON.stringify(r));return n}function rt(e,t){return(...n)=>{let r=yu();if(r===null)return t(...n);let i=tR(`async:${e}`,n),s=r.entries.get(i);if(s)return s.value;let o=t(...n).catch(c=>{throw r.entries.get(i)?.value===o&&r.entries.delete(i),c});return r.entries.set(i,{value:o}),o}}function cr(e,t){return(...n)=>{let r=yu();if(r===null)return t(...n);let i=tR(`sync:${e}`,n),s=r.entries.get(i);if(s)return s.value;let o=t(...n);return r.entries.set(i,{value:o}),o}}var Dm,Sn=ie(()=>{"use strict";Dm=new o$});import{promises as en}from"fs";import Pe from"path";import{AsyncLocalStorage as a$}from"node:async_hooks";async function Na(e,t,n={}){let r=Pe.resolve(e),i=await Lm(r,t),s=new Map,o=!1,c=p=>[p.dev,p.ino,p.mode,p.birthtimeNs,p.mtimeNs,p.ctimeNs].join(":"),l=p=>[p.dev,p.ino,p.mode,p.birthtimeNs].join(":"),f=async(p,u)=>JSON.stringify((await en.readdir(p,{withFileTypes:!0})).filter(m=>!u(m)).map(m=>[m.name,m.isDirectory(),m.isSymbolicLink()]).sort((m,h)=>String(m[0]).localeCompare(String(h[0]),"en"))),a=p=>{let u=s.get(p);return u||(u=(async()=>{let m=await en.lstat(p,{bigint:!0});if(!m.isDirectory()||m.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Pe.relative(r,p)||"."}`);let h=await en.realpath(p);if(!ao(i,h))throw new Error(`${t} resolves outside the project root`);let g=n.ignoredDirectoryEntries?.(Pe.relative(r,p).replaceAll("\\","/")||".");return{stat:m,real:h,...g?{ignoreEntry:g,namespace:await f(p,g)}:{}}})(),u=u.catch(m=>{throw s.delete(p),m}),s.set(p,u)),u};await a(r);let d=async p=>{if(o)throw new Error(`${t} read session is already finished`);let u=nt(p,t),m=r;for(let h of u.split("/").slice(0,-1))m=Pe.join(m,h),await a(m);return Pe.resolve(r,...u.split("/"))};return{observePath:d,async observeDirectory(p){let u=await d(p);return await a(u),u},async stat(p){let u=await d(p),m=await en.lstat(u,{bigint:!0});if(!m.isFile()||m.isSymbolicLink())throw new Error(`${t} must be a real file: ${p}`);return{target:u,stat:m}},async hash(p){let u=await d(p);return Qb(u,{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=r,w=[r];for(let k of Pe.relative(r,Pe.dirname(u)).split(Pe.sep).filter(Boolean))g=Pe.join(g,k),w.push(g);for(let k of w){let y=await s.get(k),R=await en.lstat(k,{bigint:!0});if(!R.isDirectory()||R.isSymbolicLink()||l(R)!==l(y.stat))throw new Error(`${t} directory changed while reading: ${Pe.relative(r,k)||"."}`)}}})},async read(p,u,m={}){let h=await d(p);return Yi(h,u,{...m,label:`${t} ${p}`,verify:async(g,w)=>{if(!ao(i,w.realPath))throw new Error(`${t} resolves outside the project root`);if(n.deferDirectoryChecks)return;let k=r,y=[r];for(let R of Pe.relative(r,Pe.dirname(h)).split(Pe.sep).filter(Boolean))k=Pe.join(k,R),y.push(k);for(let R of y){let C=await s.get(R),A=await en.lstat(R,{bigint:!0});if(!A.isDirectory()||A.isSymbolicLink()||l(A)!==l(C.stat))throw new Error(`${t} directory changed while reading: ${Pe.relative(r,R)||"."}`)}}})},async finish(p={}){if(o)throw new Error(`${t} read session is already finished`);o=!0;let u=[];for(let[m,h]of s){let g=await h,w=await en.lstat(m,{bigint:!0});if(!w.isDirectory()||w.isSymbolicLink()||l(g.stat)!==l(w)||!p.allowDirectoryContentChanges&&c(g.stat)!==c(w)&&(!g.ignoreEntry||await f(m,g.ignoreEntry)!==g.namespace)||await en.realpath(m)!==g.real)throw new Error(`${t} directory changed while observing: ${Pe.relative(r,m)||"."}`);c(g.stat)!==c(w)&&u.push(Pe.relative(r,m).replaceAll("\\","/")||".")}return{changedDirectories:u}}}}function nR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ao(e,t){let n=Pe.relative(e,t);return n===""||!Pe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Pe.sep}`)}async function Lm(e,t){let n=Pe.resolve(e),r=await rR(n);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return iR(n)}async function sR(e,t,n,r){let i=e;for(let s=0;s<n.length;s++){i=Pe.join(i,n[s]);let o;try{o=await rR(i)}catch(f){if(nR(f))return{exists:!1,kind:"missing"};throw f}if(o.isSymbolicLink()){let f=Pe.relative(e,i).replaceAll("\\","/");throw new Error(`${r.label} crosses a symbolic link or junction at ${f}`)}let c=s===n.length-1;if(!c&&!o.isDirectory()){let f=Pe.relative(e,i).replaceAll("\\","/");throw new Error(`${r.label} ancestor ${f} must be a real directory`)}if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await iR(i);if(!l$(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function oR(e,t,n){let r=nt(t,n.label),i=Pe.resolve(e),s=await Lm(i,n.label),o=r.split("/"),c=Pe.resolve(i,...o);if(!ao(i,c))throw new Error(`${n.label} must stay inside the project root`);let l=await sR(i,s,o,n);return{projectRoot:i,target:c,relative:r,exists:l.exists,kind:l.kind}}async function M(e,t,n){if(n.expected===void 0)return oR(e,t,n);try{return await u$(e,t,n.expected)}catch(r){throw r instanceof Error&&r.message.includes("Protected project path")&&(r.message=r.message.replaceAll("Protected project path",n.label)),r}}async function St(e,t,n){let r=nt(t,n.label),i=Pe.resolve(e),s=await Lm(i,n.label),o=r.split("/"),c=i;for(let l of o){c=Pe.join(c,l);let f;try{f=await en.lstat(c)}catch(p){if(!nR(p))throw p;try{await en.mkdir(c)}catch(u){if(u.code!=="EEXIST")throw u}f=await en.lstat(c)}let a=Pe.relative(i,c).replaceAll("\\","/");if(f.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${a}`);if(!f.isDirectory())throw new Error(`${n.label} directory ${a} must be a real directory`);let d=await en.realpath(c);if(!ao(s,d))throw new Error(`${n.label} resolves outside the project root`)}return await sR(i,s,o,{label:n.label,expected:"directory"}),c}async function Wm(e,t,n){return(await M(e,t,{...n,expected:"file"})).exists}async function aR(e,t,n,r){let i=!r.hooks&&!r.bigint?c$.getStore():void 0;if(i){let c=Pe.resolve(e),l=i.get(c);return l||(l=Na(c,r.label,{deferDirectoryChecks:!0}).catch(f=>{throw i.delete(c),f}),i.set(c,l)),(await l).read(t,n,r)}let s=await Na(e,r.label),o=await s.read(t,n,r);return await s.finish({allowDirectoryContentChanges:!0}),o}async function ce(e,t,n,r){if(r.hooks||r.bigint)return aR(e,t,n,r);try{return await d$(e,t,n)}catch(i){throw i instanceof Error&&i.message.includes(qm)&&(i.message=i.message.replaceAll(qm,r.label)),i}}var c$,rR,iR,l$,u$,qm,d$,ve=ie(()=>{"use strict";Xi();Qt();Sn();c$=new a$;rR=rt("protectedChainLstat",e=>en.lstat(e)),iR=rt("protectedChainRealpath",e=>en.realpath(e)),l$=cr("protectedChainInside",ao);u$=rt("protectedInspectPath",(e,t,n)=>oR(e,t,{label:"Protected project path",expected:n}));qm="Cached protected project read",d$=rt("protectedReadFile",(e,t,n)=>aR(e,t,n,{label:qm}))});import{createHash as f$}from"crypto";function p$(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Qi(e,t={}){return(await vu(e,t)).document}async function m$(e){try{return(await ce(e,$a,ri,{label:$a})).bytes}catch(t){if(p$(t))return null;throw t}}function h$(e){return e?{exists:!0,sha256:f$("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function vu(e,t={}){let n=await m$(e);return{source:n?.toString("utf8")??null,document:n?Gi(n.toString("utf8"),t):null,identity:h$(n)}}async function Mm(e){return(await Qi(e))?.config??null}var $a,li=ie(()=>{"use strict";Qt();ve();$a=".comet/config.yaml"});import{promises as Hm}from"node:fs";async function Bm(e,t){let n;for(let r=0;r<=Fm.length;r+=1)try{return await e()}catch(i){n=i;let s=i.code;if(r===Fm.length||!g$.has(s??""))throw i;await new Promise(o=>setTimeout(o,Fm[r]))}throw n}async function Vm(e,t){await Bm(()=>Hm.rename(e,t),`rename ${t}`)}async function Um(e){await Bm(()=>Hm.unlink(e),`unlink ${e}`)}async function ku(e,t){await Bm(()=>Hm.link(e,t),`link ${t}`)}var g$,Fm,cR=ie(()=>{"use strict";g$=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Fm=[50,100,200]});import{randomUUID as lR}from"crypto";import{constants as w$,promises as Ve}from"fs";import Je from"path";async function Km(e,t){try{return await ku(e,t),{linked:!0}}catch(n){let r=n.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw n}return await Ve.copyFile(e,t,w$.COPYFILE_EXCL),{linked:!1}}function es(e,t){let n=Je.relative(e,t);return n===""||!Je.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Je.sep}`)}function bu(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function y$(e,t){return Cn(e,bu(t))}function Zi(e,t){return Cn(bu(e),bu(t))}function uR(e,t){return Zi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ru(e){let t=await Ve.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 Ve.realpath(e),...bu(t)}}async function Tt(e){for(let t of e){let n=await Ve.lstat(t.path);if(!n.isDirectory()||n.isSymbolicLink()||!y$(t,n)||await Ve.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function v$(e,t,n){let[r,i]=await Promise.all([Ve.lstat(e),Ve.realpath(e),Tt(n)]);if(!r.isFile()||r.isSymbolicLink()||!Zi(r,t)||!es(n[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return r}async function dR(e,t){let n=await zm(e,t);if(n)return n;let r=Je.resolve(e),i=Je.resolve(t);if(!es(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let s=[await Ru(r)],o=Je.relative(r,i).split(Je.sep).filter(Boolean),c=r;for(let l of o){await Tt(s),c=Je.join(c,l);try{await Ve.mkdir(c)}catch(a){if(a.code!=="EEXIST")throw a}let f=await Ru(c);if(!es(s[0].realPath,f.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${c}`);s.push(f)}return await Tt(s),s}async function zm(e,t){let n=Je.resolve(e),r=Je.resolve(t);if(!es(n,r))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await Ru(n)],s=Je.relative(n,r).split(Je.sep).filter(Boolean),o=n;for(let c of s){o=Je.join(o,c);try{let l=await Ru(o);if(!es(i[0].realPath,l.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(l)}catch(l){if(l.code==="ENOENT")return null;throw l}}return await Tt(i),i}async function Jm(e){let t;try{t=await Ve.open(e,"r"),await t.sync()}catch(n){let r=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw n}finally{await t?.close()}}async function k$(e,t,n){let r=Je.dirname(e),i=await dR(n.containedRoot,r),s=Je.join(r,`.${Je.basename(e)}.${lR()}.tmp`),o,c,l;try{await n.beforeTemporaryOpen?.(),o=await Ve.open(s,"wx"),c=await o.stat();let[f,a]=await Promise.all([Ve.lstat(s),Ve.realpath(s)]);if(await Tt(i),!f.isFile()||f.isSymbolicLink()||!Zi(c,f)||!es(i[0].realPath,a))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),l=await o.stat(),!Zi(c,l))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await n.afterTemporaryClose?.(),!l)throw new Error("Contained atomic write temporary file was not written");l=await v$(s,l,i),await n.beforeCommit?.(),await Tt(i);let d=await Ve.lstat(s);if(!d.isFile()||d.isSymbolicLink()||!l||!uR(d,l))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(n.requireAtomicPublication?await ku(s,e):await Km(s,e),await Ve.unlink(s)):await Vm(s,e),await Jm(r)}catch(f){await o?.close();try{await Tt(i),await Ve.rm(s,{force:!0})}catch{}throw f}}async function $e(e,t,n){await k$(e,t,n)}async function fR(e,t,n){let r=await zm(n.containedRoot,Je.dirname(e));if(!r)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await dR(n.containedRoot,Je.dirname(t)),s=await Ve.lstat(e);if(!s.isFile()||s.isSymbolicLink())throw new Error("Contained link source must be a regular file");let o=Je.join(Je.dirname(t),`.${Je.basename(t)}.${lR()}.tmp`);try{await Tt(r),await Tt(i),await ku(e,o),await n.beforeCommit?.(),await Tt(r),await Tt(i);let c=await Ve.lstat(o),l=await Ve.lstat(e);if(!c.isFile()||c.isSymbolicLink()||!l.isFile()||l.isSymbolicLink()||!Zi(s,l)||!Zi(l,c)||s.size!==l.size||s.mtimeMs!==l.mtimeMs)throw new Error("Contained link source changed before publication");let f=await Ve.lstat(t).catch(a=>{if(a.code==="ENOENT")return null;throw a});f?.isFile()&&!f.isSymbolicLink()&&Zi(l,f)?await Um(o):await Vm(o,t),await Jm(Je.dirname(t)),await Tt(r),await Tt(i)}catch(c){try{await Tt(i),await Ve.unlink(o)}catch{}throw c}}async function lr(e,t){let n=Je.dirname(e),r=await zm(t.containedRoot,n);if(!r)return!1;let i,s;try{i=await Ve.lstat(e),s=await Ve.realpath(e)}catch(l){if(l.code==="ENOENT")return!1;throw l}if(!i.isFile()||i.isSymbolicLink()||!es(r[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await Tt(r);let[o,c]=await Promise.all([Ve.lstat(e),Ve.realpath(e)]);if(!o.isFile()||o.isSymbolicLink()||!uR(i,o)||c!==s)throw new Error("Contained file removal target changed before removal");return await Um(e),await Tt(r),await Jm(n),!0}var Ht=ie(()=>{"use strict";cR();Ta()});var iz,Gm=ie(()=>{"use strict";Ht();li();ve();iz=Number.MAX_SAFE_INTEGER});var Cu=ie(()=>{"use strict";Ht();Qt();li();ve();Gm()});import{promises as wR}from"fs";import Xe from"path";import S$ from"os";function Xm(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ja(e,t){let n=Xe.resolve(e),r=t==="docs"?Xe.join(n,"docs"):n,i=Xe.join(r,"openspec"),s=Xe.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:t,openSpecBase:r,openSpecRoot:i,changesDir:Xe.join(i,"changes"),archiveDir:Xe.join(i,"changes","archive"),specsDir:Xe.join(i,"specs"),superpowersRoot:s,superpowersSpecsDir:Xe.join(s,"specs"),superpowersPlansDir:Xe.join(s,"plans"),superpowersReportsDir:Xe.join(s,"reports")}}async function yR(e){let t=await Qi(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new co;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new co("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function En(e,t){return ja(e,t??await yR(e))}async function E$(e){try{return await wR.lstat(e),!0}catch(t){if(Xm(t))return!1;throw t}}async function A$(e,t){let n=await En(e,t),r=n.artifactLayout==="legacy"?"docs":"legacy",i=ja(e,r).openSpecRoot,[s,o]=await Promise.all([M(n.projectRoot,qe(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),E$(i)]),c=s.exists;return{paths:n,configuredRootExists:c,alternateRoot:i,alternateRootExists:o,dualRoots:c&&o}}async function x$(e){let t=[e.openSpecRoot,e.changesDir,e.archiveDir,e.specsDir,e.superpowersRoot,e.superpowersSpecsDir,e.superpowersPlansDir,e.superpowersReportsDir];for(let n of t){let r=qe(e.projectRoot,n);await M(e.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Nt(e,t){let n=await A$(e,t);if(await x$(n.paths),!n.configuredRootExists){let r=qe(n.paths.projectRoot,n.paths.openSpecRoot),i=qe(n.paths.projectRoot,n.alternateRoot);throw new co(`Configured Classic OpenSpec root is missing: ${r} (alternate ${i} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function Ar(e,t){let n=Xe.join(Xe.resolve(e),".comet","classic-root-move.json");if(await mu(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await Nt(e,t);if(!await mu(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${qe(r.projectRoot,r.openSpecRoot)}`);return r}async function it(e){let t=Xe.resolve(e),n=null;try{(await wR.lstat(t)).isDirectory()||(t=Xe.dirname(t))}catch(s){if(!Xm(s))throw s}let r=t,i=Xe.resolve(S$.homedir());for(;;){Xe.basename(t)==="openspec"&&(n=Xe.dirname(t));let s=!1,o=t===i&&t!==r,c=null;if(!o)try{let{bytes:f}=await ce(t,hR,ri,{label:hR});c=f.toString("utf8")}catch(f){if(!Xm(f))throw f}if(c!==null)try{let f=Gi(c,{allowPartialProject:!0,allowMissingNativeFields:!0}).value;s=!!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===r)throw new ts(f);if(Xb(c))throw new ts(f)}if(s||await mu(Xe.join(t,".git")))return t;let l=Xe.dirname(t);if(l===t)return n??Xe.resolve(e);t=l}}function qe(e,t){return Xe.relative(Xe.resolve(e),t).replaceAll("\\","/")}var co,ts,hR,Ue=ie(()=>{"use strict";Fb();Qt();li();Cu();ve();co=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},ts=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="ClassicProjectConfigError"}},hR=".comet/config.yaml"});import I$ from"path";async function Su(e,t){let n=t??await Nt(e),r=I$.join(n.openSpecRoot,"config.yaml"),i=qe(n.projectRoot,r),s;try{s=(await ce(n.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 o=(0,vR.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${i} is invalid YAML (${o.errors[0].message})`);let c=o.toJS();if(!c||typeof c!="object"||Array.isArray(c))throw new Error(`Classic OpenSpec root is unhealthy: ${i} must contain a mapping`);let l=c.schema;if(typeof l!="string"||l.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${i} must declare a non-empty schema`);return{layout:n,configPath:i,schema:l}}var vR,Qm=ie(()=>{"use strict";vR=Rt(Pt(),1);ve();Ue()});import{spawnSync as _$}from"child_process";async function ui(e,t=process.cwd()){let n=e[0]==="--"?e.slice(1):[...e];if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- <openspec-args...>"};let r=await it(t),i=await Ar(r);await Su(r,i);let s=process.env.COMET_OPENSPEC||"openspec",o;try{pu(s,n,{cwd:i.openSpecBase}),o=Om(s,n,{cwd:i.openSpecBase})}catch(l){return{exitCode:l.code==="ENOENT"?127:70,executionStarted:!1,stderr:l instanceof Error?l.message:String(l)}}let c=_$(o.command,o.args,{cwd:i.openSpecBase,encoding:"utf8",shell:!1,windowsHide:!0,timeout:12e4,...o.env?{env:o.env}:{}});if(c.error){let l=c.error.code;return{exitCode:l==="ENOENT"?127:70,...c.pid===0&&["ENOENT","EACCES","ENOTDIR","ENOEXEC"].includes(l??"")?{executionStarted:!1}:{},stdout:c.stdout||void 0,stderr:c.stderr||(l==="ENOENT"?`OpenSpec CLI not found: ${s}`: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}}var Eu=ie(()=>{"use strict";Tm();Ue();Qm()});import{promises as P$}from"node:fs";import Zm from"node:path";function xu(e){return lo.some(t=>t===e)}async function O$(e,t={}){let n=[],r=[];for(let i of lo)try{let s=await P$.lstat(Zm.join(e,i));n.push(i),(!s.isFile()||s.isSymbolicLink())&&r.push(i)}catch(s){if(s.code!=="ENOENT")throw s}if(n.length>1)throw new Da(`Classic state files are ambiguous in ${e}: ${lo.join(" and ")} both exist; preserve both files and resolve the conflict before continuing`);if(r.length)throw new Error(`Classic state must be a regular file, not a symlink or directory: ${Zm.join(e,r[0])}`);return Zm.join(e,n[0]??t.defaultFileName??kR)}async function ue(e,t={}){return T$(e,t)}var kR,Au,lo,Da,T$,kt=ie(()=>{"use strict";Sn();kR="comet-state.yaml",Au=".comet.yaml",lo=[kR,Au],Da=class extends Error{};T$=rt("classicStateFile",(e,t)=>O$(e,t))});import{AsyncLocalStorage as N$}from"async_hooks";import{promises as bR}from"fs";import qa from"path";function $$(e,t){let n=qa.relative(e,t);return n===""||!qa.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${qa.sep}`)}async function j$(e){let t=qa.resolve(e.invocationCwd??process.cwd()),n=qa.resolve(e.projectRoot??await it(t)),[r,i]=await Promise.all([bR.realpath(t),bR.realpath(n)]);if(!$$(i,r))throw new Error(`Classic command invocation cwd is outside the discovered project: ${t}`);return{invocationCwd:t,projectRoot:n,observations:new Map}}async function D$(e,t){let n=uo.getStore();if(n)return t(n);let r=await j$(e);return uo.run(r,()=>t(r))}function Iu(){let e=uo.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}async function RR(e,t){let n=uo.getStore();if(!n?.observations)return t();let r=n.observations.get(e);if(r)return r;let i=t();n.observations.set(e,i);try{return await i}catch(s){throw n.observations.delete(e),s}}async function La(e){let t=uo.getStore();if(!t)return e();t.observations?.clear();try{return await uo.run({...t,observations:null},e)}finally{t.observations?.clear()}}function _u(e){return(t,n)=>D$(n,()=>e(t,n))}var uo,Wa=ie(()=>{"use strict";Ue();uo=new N$});var Pu=ie(()=>{"use strict"});var CR=ie(()=>{"use strict"});var eh=ie(()=>{"use strict";Pu()});var SR=ie(()=>{"use strict";Pu();eh()});var B$,ER=ie(()=>{"use strict";B$=Rt(Pt(),1);Ht();Qt();ve()});var Zz,AR=ie(()=>{"use strict";Ht();ve();Zz=Number.MAX_SAFE_INTEGER});var xR=ie(()=>{"use strict"});var IR=ie(()=>{"use strict"});var _R=ie(()=>{"use strict";xR();IR()});var PR=ie(()=>{"use strict";_R()});var gJ,OR=ie(()=>{"use strict";Sn();li();PR();gJ=rt("hookWritePolicy",async e=>(await Mm(e))?.hook??{allow_paths:[]})});import{promises as V$}from"node:fs";import U$ from"node:path";function Tu(e){return U$.join(e,".comet","current-change.json")}function K$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function TR(e){return e===null||typeof e=="string"}function z$(e){let t;try{t=JSON.parse(e)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!K$(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&&!TR(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ou,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ou)throw new Error(`current change selection schema must be ${Ou}`);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(!TR(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 fo(e){let t;try{let r=Tu(e),{bytes:i}=await Yi(r,NR,{label:"current change selection"});t=i.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...z$(t)}}async function th(e){await V$.rm(Tu(e),{force:!0})}async function Ma(e,t,n){let r=await fo(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==n?!1:(await th(e),!0)}var Ou,NR,J$,Fa=ie(()=>{"use strict";Sn();Xi();Ou="comet.selection.v2",NR=Number.MAX_SAFE_INTEGER;J$=rt("readCometCurrentSelection",e=>fo(e))});var jR=ie(()=>{"use strict";Pu();Ht();CR();SR();Qt();ER();ve();li();Cu();AR();OR();Fa();Gm();eh()});import{TextDecoder as G$}from"util";function DR(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function Y$(e,t){try{return new G$("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t} is not valid UTF-8`,{cause:n})}}async function nh(e,t,n,r,i={}){try{let s=await ce(e,t,n,{label:r,hooks:i.hooks});return{result:s,text:Y$(s,r)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function di(e,t,n,r,i={}){return(await nh(e,t,n,r,i))?.text??null}async function fi(e,t,n,r,i,s={}){if(Buffer.byteLength(n,"utf8")>r)throw new Error(`${i} exceeds ${r} bytes`);let o=await nh(e,t,r,i),c=await M(e,t,{label:i,expected:"file"});await $e(c.target,n,{containedRoot:c.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let l=await nh(e,t,r,i);if(!(!o&&!l)){if(!o||!l)throw new Error(`${i} changed before commit`);if(o.result.realPath!==l.result.realPath||!Cn(DR(o.result.stat),DR(l.result.stat))||o.text!==l.text)throw new Error(`${i} changed before commit`)}}})}async function Nu(e,t,n,r,i,s={}){let o=await di(e,t,r,i);await fi(e,t,`${o??""}${n}`,r,i,s)}async function $u(e,t,n,r={}){let i=await M(e,t,{label:n,expected:"file"});return i.exists?lr(i.target,{containedRoot:i.projectRoot,beforeRemove:r.beforeRemove}):!1}var ju=ie(()=>{"use strict";jR();Ta()});var WR={};nP(WR,{RUN_STATE_FILE:()=>Du,applyRunStateToDocument:()=>rh,readRunState:()=>Va,removeRunState:()=>Ua,runStateFromDocument:()=>ns,writeRunState:()=>rs});import X$ from"path";function Ba(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return n}function Ha(e,t){let n=Ba(e,t);if(X$.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return n}function Q$(e){let t=e.run_retries??"{}",n;try{n=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(n))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function ns(e){if(!e.run_id)return null;let t=Ba(e,"run_id"),n=Ba(e,"skill"),r=Ba(e,"skill_version"),i=Ba(e,"skill_hash"),s=Ha(e,"pending_ref"),o=Ha(e,"trajectory_ref"),c=Ha(e,"context_ref"),l=Ha(e,"artifacts_ref"),f=Ha(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:n,skillVersion:r,skillHash:i,orchestration:e.orchestration,currentStep:qR(e,"current_step"),iteration:a,pending:qR(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:c,artifactsRef:l,checkpointRef:f,status:e.run_status,retries:Q$(e)}}function rh(e,t){t?e.run_id=t.runId:delete e.run_id}function Z$(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 ej(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 ns(t)}async function Va(e,t={}){let n=await di(e,Du,LR,"Run state",t);if(n===null)return null;let r=JSON.parse(n);return ej(r)}async function rs(e,t,n={}){await fi(e,Du,JSON.stringify(Z$(t),null,2),LR,"Run state",n)}async function Ua(e,t={}){await $u(e,Du,"Run state",t)}var qR,Du,LR,qu=ie(()=>{"use strict";ju();qR=(e,t)=>{let n=e[t];return n==null?null:String(n)};Du=".comet/run-state.json",LR=Number.MAX_SAFE_INTEGER});function Et(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}function ih(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function po(e,t){let n=e[t];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${t} must be a string or null`);return n}function Bt(e,t,n,r=!0){let i=e[t];if(i==null||i===""){if(r)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof i!="string"||!n.includes(i))throw new Error(`Invalid Classic state: ${t} must be one of ${n.join(", ")}${r?" or null":""}`);return i}function sh(e,t,n=!0){let r=e[t];if(r==null||r===""){if(n)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof r!="boolean")throw new Error(`Invalid Classic state: ${t} must be true or false`);return r}function FR(e,t,n=0){let r=e[t];if(r==null||r==="")return n;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid Classic state: ${t} must be a non-negative integer`);return r}function Lu(e,t){let n=po(e,t);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${t} must be a relative repository path`);return n}function gj(e,t){let n=po(e,t);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${t} must be a sha256 hex digest`);return n}function wj(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==is)throw new Error(`Invalid Classic state: classic_migration must be ${is}`);return t}function yj(e){if(!pi.some(n=>ih(e,n)))return null;for(let n of hj)if(!ih(e,n))return null;return{workflow:Bt(e,"workflow",MR,!1),language:Bt(e,"language",nj),phase:Bt(e,"phase",tj,!1),contextCompression:Bt(e,"context_compression",rj),buildMode:Bt(e,"build_mode",ij),buildPause:Bt(e,"build_pause",sj),subagentDispatch:Bt(e,"subagent_dispatch",oj),tddMode:Bt(e,"tdd_mode",aj),reviewMode:Bt(e,"review_mode",cj),isolation:Bt(e,"isolation",lj),boundBranch:po(e,"bound_branch"),verifyMode:Bt(e,"verify_mode",uj),autoTransition:sh(e,"auto_transition"),baseRef:po(e,"base_ref"),designDoc:Lu(e,"design_doc"),plan:Lu(e,"plan"),verifyResult:Bt(e,"verify_result",dj,!1),verifyFailures:FR(e,"verify_failures"),...ih(e,"check_epoch")?{checkEpoch:FR(e,"check_epoch")}:{},verificationReport:Lu(e,"verification_report"),branchStatus:Bt(e,"branch_status",fj),createdAt:po(e,"created_at"),verifiedAt:po(e,"verified_at"),archiveConfirmation:Bt(e,"archive_confirmation",pj),archived:sh(e,"archived",!1),directOverride:sh(e,"direct_override"),handoffContext:Lu(e,"handoff_context"),handoffHash:gj(e,"handoff_hash"),classicProfile:Bt(e,"classic_profile",MR),classicMigration:wj(e)}}function tn(e,t){if(e.change_id!==void 0&&(typeof e.change_id!="string"||!oh.test(e.change_id)))throw new Error("Invalid Classic state: change_id must be an immutable UUID");let n=t??null;if(n===null&&t===void 0&&e.run_id&&e.skill)try{n=ns(e)}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:r})}return{classic:yj(e),run:n,unknownKeys:Object.keys(e).filter(r=>!mj.has(r))}}function Wu(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}}var MR,is,oh,ah,tj,nj,rj,ij,sj,oj,aj,cj,lj,uj,dj,fj,pj,pi,Ka,mj,hj,nn=ie(()=>{"use strict";qu();MR=["full","hotfix","tweak"],is=1,oh=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u,ah=`# comet-execution: managed-run
|
|
145
|
+
`;tj=["open","design","build","verify","archive"],nj=["en","zh-CN"],rj=["off","beta"],ij=["subagent-driven-development","executing-plans","direct","autonomous"],sj=["plan-ready"],oj=["confirmed"],aj=["tdd","direct"],cj=["off","standard","thorough"],lj=["current","branch","worktree"],uj=["light","full"],dj=["pending","pass","fail"],fj=["pending","handled"],pj=["pending","confirmed"],pi=["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"],Ka=["change_id","run_id","run_checkpoint","application_checkpoint"],mj=new Set([...pi,...Ka]),hj=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"]});import{createHash as vj}from"node:crypto";import{lstatSync as za,readFileSync as kj,realpathSync as HR}from"node:fs";import bj from"node:os";import Vt from"node:path";function ch(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function Mu(e){return process.platform==="win32"?HR.native(e):HR(e)}function Cj(e){return Rj(e)}function Sj(e){let t=Mu(Vt.resolve(e)),n=za(t,{bigint:!0});if(!n.isDirectory())throw new Error(`工作区必须是目录:${e}`);let r=ch(n),i=(l,f)=>({projectRoot:t,workspaceId:vj("sha256").update(JSON.stringify(["comet.workspace.v2",t,r,l,f])).digest("hex")}),s=Vt.join(t,".git"),o,c;try{let l=za(s);if(l.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${s}`);if(l.isDirectory())o=Mu(s),c=ch(za(o,{bigint:!0}));else if(l.isFile()){let f=/^gitdir: (.+)\r?\n?$/u.exec(kj(s,"utf8"));if(!f)throw new Error(`工作区 .git 文件格式无效:${s}`);o=Mu(Vt.resolve(t,f[1].trim()));let a=za(o,{bigint:!0});if(!a.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${o}`);c=ch(a)}else throw new Error(`工作区 .git 类型无效:${s}`)}catch(l){if(l.code!=="ENOENT")throw l;try{za(s)}catch(f){if(f.code==="ENOENT")return i(s,null);throw f}throw l}return i(o,c)}function BR(e){let t=Vt.dirname(e);if(t===e)return e;try{return Vt.join(Mu(t),Vt.basename(e))}catch(n){if(n.code!=="ENOENT")throw n;return Vt.join(BR(t),Vt.basename(e))}}function lh(e){let t=Cj(e),n=process.env.COMET_DATA_DIR;if(n!==void 0&&(!n.trim()||!Vt.isAbsolute(n)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let r=Ej(n??Vt.join(bj.homedir(),".comet")),i=Vt.relative(t.projectRoot,r);if(i===""||!Vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Vt.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${r};工作区:${t.projectRoot}`);let s=Vt.join(r,"workspaces",t.workspaceId);return{...t,dataRoot:r,workspaceRoot:s,runtimeRoot:Vt.join(s,"runtime")}}function lt(e){return lh(e).runtimeRoot}var Rj,Ej,uh=ie(()=>{"use strict";Sn();Rj=cr("workspaceIdentity",Sj);Ej=cr("workspaceRuntimeParent",BR)});import{promises as Ja}from"node:fs";import VR from"node:path";async function xr(e){return lt(e)}async function dh(e){return[lt(e)]}async function UR(e){let t=VR.dirname(e);if(t!==e){await UR(t);try{await Ja.mkdir(e,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r}}let n=await Ja.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function ur(e){let t=lt(e);return await UR(t),t}async function KR(e,t,n){try{let r=await Ja.lstat(e);if(r.isSymbolicLink())throw new Error("旧 Runtime 路径不能是符号链接:"+e);let i=r.isDirectory()?VR.join(e,".comet-runtime-migration.json"):e,s=await Ja.lstat(i);if(!s.isFile()||s.isSymbolicLink())return!1;let o;try{o=JSON.parse((await Yi(i,Number.MAX_SAFE_INTEGER,{label:"旧 Runtime 标记"})).bytes.toString("utf8"))}catch(c){if(c instanceof SyntaxError)return!1;throw c}return o?.schema!=="comet.workspace-runtime-migration.v1"||typeof o.workspaceId!="string"||typeof o.source!="string"||typeof o.target!="string"||!["file","directory"].includes(o.kind)?!1:!r.isDirectory()||(await Ja.readdir(e)).every(c=>c===".comet-runtime-migration.json")}catch(r){if(r.code==="ENOENT")return!1;throw r}}var rn=ie(()=>{"use strict";uh();Xi()});import{createHash as Aj,randomUUID as xj}from"node:crypto";import Ie from"node:path";function Fu(e){let t=Aj("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 JR(e,t){let n=await ue(t),r=Ie.relative(e,n).replaceAll("\\","/"),i=null;try{i=(await ce(e,r,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 s=(0,zR.parseDocument)(i,{uniqueKeys:!0});if(s.errors.length)throw new Error(`Invalid Classic state document: ${s.errors[0].message}`);let o=s.get("change_id");if(o!==void 0&&(typeof o!="string"||!oh.test(o)))throw new Error("Invalid Classic change_id: expected an immutable UUID");return{source:i,document:s,id:o}}async function Ij(e,t){let n=await ue(t),r=Ie.relative(e,n).replaceAll("\\","/"),i=()=>JR(e,t),s=await i();if(s.id)return s.id;let{source:o,document:c}=s,l=c.get("run_id"),f=typeof l=="string"&&l?Fu(`classic-run:${l}`):xj();return c.get("archived")===!0||Ie.basename(Ie.dirname(t))==="archive"?typeof l=="string"&&l?f:Fu(`classic-archive:${r}`):(c.set("change_id",f),await $e(n,c.toString(),{containedRoot:e,exclusive:o===null,beforeCommit:async()=>{if((await i()).source!==o)throw new Error("Classic state changed while assigning its instance identity")}}),f)}async function ph(e,t,n={}){let r=t??await it(e),i;try{i=await JR(r,e)}catch(m){if(m.code==="ENOENT")return null;throw m}let{document:s,id:o}=i,c=Ie.relative(r,e).replaceAll("\\","/"),l=s.get("run_id"),f=s.get("archived")===!0||Ie.basename(Ie.dirname(e))==="archive",a=o??(typeof l=="string"&&l?Fu(`classic-run:${l}`):f?Fu(`classic-archive:${c}`):null);if(!a)return e;let d=lt(r),p=Ie.parse(d).root;if(!(await M(p,Ie.relative(p,d).replaceAll("\\","/"),{label:"Classic read-only Runtime root",expected:"directory"})).exists)return n.includeMissing?Ie.join(d,"classic-changes",a):e;let u=await M(d,`classic-changes/${a}`,{label:"Classic read-only Run directory",expected:"directory"});return u.exists||n.includeMissing?u.target:e}async function Ce(e,t){return _j(e,t)}async function _j(e,t){let n=t??await it(e),r=Ie.relative(n,e).replaceAll("\\","/");if(r&&!(await M(n,r,{label:"Classic change directory",expected:"directory"})).exists)throw Object.assign(new Error("Classic change directory does not exist"),{code:"ENOENT"});await ue(e);let i=await ur(n),s=await Ij(n,e),o=Ie.join(i,"classic-changes",s);return await St(i,Ie.relative(i,o),{label:"Classic local Run directory"}),o}async function mo(e,t,n={}){let r=lt(e),i=Ie.relative(r,t);if(i===""||!i.startsWith(`..${Ie.sep}`)&&i!==".."&&!Ie.isAbsolute(i))return n.readOnly?{root:Ie.dirname(r),target:t}:(await ur(e),{root:r,target:t});let s=Ie.relative(Ie.resolve(e),t).replaceAll("\\","/");if(s.startsWith(".comet/runtime/"))return{root:r,target:Ie.join(r,s.slice(15))};let o=/^(?:(.*)\/)?\.comet\/([^/]+)(\/.*)?$/u.exec(s);if(!o||!fh.has(o[2]))return null;if(n.readOnly){let p=Ie.parse(r).root;if(!(await M(p,Ie.relative(p,Ie.join(r,"classic-changes")),{label:"Classic local records",expected:"directory"})).exists)return null}let c=o[1]??"";if(!(await M(e,Ie.relative(e,await ue(Ie.join(e,c))),{label:"Classic local change identity",expected:"file"})).exists)return null;let f=Ie.join(e,c),a=n.readOnly?await ph(f,e,{includeMissing:!0}):await Ce(f,e);if(!a||n.readOnly&&a===f)return null;let d=Ie.relative(r,a);if(Ie.isAbsolute(d)||d===".."||d.startsWith(`..${Ie.sep}`))throw new Error("Classic Runtime workspace changed while resolving a change-local target");return{root:n.readOnly?Ie.dirname(r):r,target:Ie.join(a,".comet",o[2],o[3]??"")}}var zR,fh,mi=ie(()=>{"use strict";kt();nn();ve();zR=Rt(Pt(),1);Ht();ve();Ue();rn();fh=new Set(["run-state.json","pending-action.json","trajectory.jsonl","context.md","artifacts.json","checkpoint.json","coordination.json","subagent-progress.md"])});import ho from"path";import{AsyncLocalStorage as Pj}from"node:async_hooks";async function Tj(e,t){let n=Oj.getStore();if(!n||n.root!==ho.resolve(e))return null;let r=nt(t,"Classic proposal source"),i=n.files.get(r);return i||(i=n.session.read(r,Hu),n.files.set(r,i)),i}async function Bu(e,t,n,r=!1){let i=ho.resolve(e),s=ho.isAbsolute(t)?ho.resolve(t):ho.resolve(i,t),o=await mo(i,s,{readOnly:!r});o&&(i=o.root,s=o.target);let c=ho.relative(i,s).replaceAll("\\","/");return{root:i,relative:nt(c,n),target:s}}async function Vn(e,t,n){let r=await Bu(e,t,n.label,n.migrate);return M(r.root,r.relative,n)}async function Ge(e,t,n){try{return(await Vn(e,t,{label:n.label,expected:n.expected??"any"})).exists}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function Ir(e,t,n,r){return await Ge(e,t,{label:n,expected:"file"})?(await GR(e,t,{label:n,hooks:r})).byteLength>0:!1}async function le(e,t,n){return(await GR(e,t,n)).toString("utf8")}async function GR(e,t,n){let r=await Bu(e,t,n.label);if(!n.hooks){let i=await Tj(r.root,r.relative);if(i){if(i.bytes.length>(n.maxBytes??Hu))throw new Error(`${n.label} exceeds the read limit`);return i.bytes}}return(await ce(r.root,r.relative,n.maxBytes??Hu,{label:n.label,hooks:n.hooks})).bytes}async function hi(e,t,n){let r=await Bu(e,t,n,!0);return St(r.root,r.relative,{label:n})}async function wt(e,t,n,r){let i=await Bu(e,t,r.label,!0);await M(i.root,i.relative,{label:r.label,expected:"file"}),await $e(i.target,n,{containedRoot:i.root,beforeTemporaryOpen:r.beforeTemporaryOpen,beforeCommit:r.beforeCommit,exclusive:r.exclusive})}var Hu,Oj,Qe=ie(()=>{"use strict";mi();Ht();Qt();ve();Hu=Number.MAX_SAFE_INTEGER,Oj=new Pj});import{promises as Vu}from"fs";import Un from"path";async function gi(e,t){let n=[],r=new Set;async function i(s,o){let c=await Vn(e,s,{label:"Classic capability directory",expected:"directory"});if(!c.exists)return;let l=await Vu.realpath(c.target);if(r.has(l))throw new Error(`Classic capability directory cycle: ${s}`);if(r.add(l),o){let a=`${s}/spec.md`;(await Vn(e,a,{label:"Classic capability spec",expected:"file"})).exists&&n.push(a)}let f=(await Vu.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(`${s}/${a.name}`,!0)}r.delete(l)}return await i(t.replaceAll("\\","/"),!1),n}function Ya(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}'
|
|
146
|
+
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function _r(e){let t=Ya(e);if(t)throw new Error(t)}async function Kn(e,t){_r(t);let n=[],r=async i=>(await M(e,Un.relative(e,i),{label:"Classic change directory",expected:"directory"}),ue(i));for(let i of["openspec/changes","docs/openspec/changes"]){n.push(await r(Un.join(e,i,t)));let s=Un.join(e,i,"archive"),o=await Uu(e,s,t);for(let c of o??[])c===t?await r(Un.join(s,c)):mh(c,t)&&n.push(await r(Un.join(s,c)))}return n}function Nj(e,t){return{label:qe(e,t),directory:t}}async function Ga(e,t,n){let r=Nj(e,t);if(!(await Vn(e,t,{label:n,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let s=await Vn(e,await ue(t),{label:`${n} state`,expected:"file"});return{change:r,exists:!0,stateExists:s.exists}}function mh(e,t){return e.slice(11)===t&&$j.test(e)}async function Uu(e,t,n){_r(n);let r=()=>M(e,Un.relative(e,t),{label:"Classic Archive directory",expected:"directory"}),i=await r();if(!i.exists)return null;let s=async()=>{let l=await Vu.lstat(i.target,{bigint:!0});if(!l.isDirectory()||l.isSymbolicLink())throw new Error("Classic Archive directory must be a real directory");return[l.dev,l.ino,l.mode,l.size,l.mtimeNs,l.ctimeNs].join(":")},o=await s(),c=await RR(`classic-archive:${JSON.stringify([i.target,n,o])}`,async()=>{let l=await Vu.readdir(i.target);if(await s()!==o)throw new Error("Classic Archive directory changed while inspecting state files");return l.filter(f=>f===n||mh(f,n))});if(!(await r()).exists||await s()!==o)throw new Error("Classic Archive directory changed while inspecting state files");return c}async function YR(e,t,n,r={}){if(!r.skipExactCompatibility){let o=await Ga(e,Un.join(t,n),`Classic archived change ${n}`);if(o.exists)return o.change}let i=await Uu(e,t,n),s=[];for(let o of i??[]){if(o===n)continue;let c=await Ga(e,Un.join(t,o),`Classic archived change ${o}`);c.exists&&c.stateExists&&s.push(c.change)}return s.sort((o,c)=>c.directory.localeCompare(o.directory))[0]??null}async function go(e,t=process.cwd()){_r(e);let n=await Nt(t),r=await Ga(n.projectRoot,Un.join(n.changesDir,e),`Classic active change ${e}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}async function wo(e,t=process.cwd(),n={}){_r(e);let r=await Nt(t);if(n.preferredArchiveName!==void 0){let i=n.preferredArchiveName;if(i!==e&&!mh(i,e))throw new Error(`Classic preferred archive name '${i}' does not belong to change '${e}'`);let s=await Ga(r.projectRoot,Un.join(r.archiveDir,i),`Classic preferred archived change ${i}`);return s.exists&&s.stateExists?s.change:null}return YR(r.projectRoot,r.archiveDir,e,n)}async function ss(e,t=process.cwd()){_r(e);let n=await Nt(t),r=await Ga(n.projectRoot,Un.join(n.changesDir,e),`Classic active change ${e}`);if(r.exists)return r.change;let i=await YR(n.projectRoot,n.archiveDir,e);return i||r.change}var $j,gn=ie(()=>{"use strict";kt();Wa();ve();Ue();Qe();$j=/^\d{4}-\d{2}-\d{2}-/u});import An from"node:path";async function Ku(e,t){let n=await Xa(e,t);if(n.problems.length)throw new Error(n.problems.join(`
|
|
147
|
+
`));n.source!=="legacy"&&await wt(e,An.join(t,QR),JSON.stringify({schema:"comet.classic.archive-requirements.v1",files:n.files.map(r=>An.relative(t,r).replaceAll("\\","/"))})+`
|
|
148
|
+
`,{label:"Classic archive requirements"})}async function os(e,t){let n=An.join(t,QR),r=["proposal.md","design.md","tasks.md"];if(await Ge(e,n,{label:"Classic archive requirements",expected:"file"})){let s=JSON.parse(await le(e,n,{label:"Classic archive requirements"}));if(s?.schema!=="comet.classic.archive-requirements.v1")throw new Error("Unsupported Classic archive requirements");r=s.files}if(!Array.isArray(r)||!r.includes("proposal.md")||!r.includes("tasks.md")||r.some(s=>typeof s!="string"||!(["proposal.md","design.md","tasks.md"].includes(s)||/^specs\/(?:[^/\\:]+\/)+spec\.md$/u.test(s))||s.split("/").some(o=>o==="."||o==="..")))throw new Error("Invalid Classic archive required files");let i=[];for(let s of r)await Ir(e,An.join(t,s),"Classic archived required file")||i.push(`Required archived artifact is missing or empty: ${s}`);return i}function jj(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 n=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(l=>typeof l!="string"))throw new Error("OpenSpec must expose dependency edges for every artifact; upgrade to a supported version");if(n.has(c.id))throw new Error(`Duplicate OpenSpec artifact: ${c.id}`);n.set(c.id,c)}let r=[],i=new Set,s=new Set,o=c=>{if(typeof c!="string"||!n.has(c))throw new Error(`Missing OpenSpec dependency: ${String(c)}`);if(s.has(c))throw new Error(`Cyclic OpenSpec dependency: ${c}`);if(i.has(c))return;s.add(c);let l=n.get(c);for(let f of l.requires)o(f);s.delete(c),i.add(c),r.push(l)};for(let c of[...t.applyRequires,"proposal","tasks"])o(c);return r}async function Xa(e,t,n){let r=An.join(t,".openspec.yaml");if(!await Ge(e,r,{label:"OpenSpec change metadata",expected:"file"})){if(n!==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=>An.join(t,d)),problems:[]}}let i=(0,XR.parseDocument)(await le(e,r,{label:"OpenSpec change metadata"}));if(i.errors.length)throw new Error(`Invalid OpenSpec metadata: ${i.errors[0].message}`);let s=await gi(e,An.join(t,"specs")),o=n===void 0?await ui(["status","--change",An.basename(t),"--json"],e):void 0;if(o&&o.exitCode!==0)throw new Error(`Cannot inspect OpenSpec artifact requirements: ${o.stderr??o.exitCode}`);let c;try{c=o?JSON.parse(o.stdout??""):n}catch{throw new Error("Unsupported OpenSpec status: expected JSON")}if(!c||typeof c.changeRoot!="string"||An.resolve(c.changeRoot)!==An.resolve(t))throw new Error("OpenSpec status resolves outside the selected Classic change");let l=jj(c),f=s,a={source:"openspec",required:l.map(d=>d.id),skipped:[],designRequired:l.some(d=>d.id==="design"),files:[],problems:[]};for(let d of l){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(An.posix.isAbsolute(p)||/^[A-Za-z]:/u.test(p)||p.split("/").includes(".."))throw new Error(`Unsafe OpenSpec artifact path: ${p}`);let u;if(d.id==="specs"&&["specs/**/*.md","specs/**/spec.md","specs/*/spec.md"].includes(p))u=f;else{if(["?","*","[","]","{","}"].some(m=>p.includes(m)))throw new Error(`Unsupported OpenSpec artifact pattern: ${p}`);u=[An.join(t,p)]}(d.status!=="done"||!u.length)&&a.problems.push(`Required OpenSpec artifact is not complete: ${d.id}`);for(let m of u)await Ir(e,m,`OpenSpec required artifact ${d.id}`)||a.problems.push(`Required OpenSpec file is missing or empty: ${m}`),a.files.push(m)}return a}var XR,QR,Qa=ie(()=>{"use strict";XR=Rt(Pt(),1);Eu();gn();Qe();QR=".comet/archive-requirements.json"});import{AsyncLocalStorage as $C}from"node:async_hooks";import{performance as TC}from"node:perf_hooks";async function jC(e,t=n=>{let r=n.completed===void 0?"":`:${n.completed}${n.total===void 0?"":`/${n.total}`} 项`;process.stderr.write(`[Comet] ${n.label}${r},已用 ${Math.floor(n.elapsedMs/1e3)} 秒
|
|
149
|
+
`)}){if(NC.getStore())return e();let n={label:"执行工作流命令"},r=Date.now(),i=setInterval(()=>{try{t({...n,elapsedMs:Date.now()-r})}catch{}},5e3);i.unref?.();try{return await NC.run(n,e)}finally{clearInterval(i)}}function aD(e=0){sD+=1,oD+=e;for(let t of bh.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}async function DC(e){let t={gitCommands:0,gitDurationMs:0};return{result:await bh.run([...bh.getStore()??[],t],e),metrics:t}}function mr(e){let t=TC.now();try{return e()}finally{aD(TC.now()-t)}}var sD,oD,bh,NC,ds=ie(()=>{"use strict";sD=0,oD=0,bh=new $C,NC=new $C});var dc=_(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.regexpCode=xe.getEsmExportName=xe.getProperty=xe.safeStringify=xe.stringify=xe.strConcat=xe.addCodeArg=xe.str=xe._=xe.nil=xe._Code=xe.Name=xe.IDENTIFIER=xe._CodeOrName=void 0;var lc=class{};xe._CodeOrName=lc;xe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var fs=class extends lc{constructor(t){if(super(),!xe.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}}};xe.Name=fs;var On=class extends lc{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((n,r)=>`${n}${r}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((n,r)=>(r instanceof fs&&(n[r.str]=(n[r.str]||0)+1),n),{})}};xe._Code=On;xe.nil=new On("");function iS(e,...t){let n=[e[0]],r=0;for(;r<t.length;)Nh(n,t[r]),n.push(e[++r]);return new On(n)}xe._=iS;var Th=new On("+");function sS(e,...t){let n=[uc(e[0])],r=0;for(;r<t.length;)n.push(Th),Nh(n,t[r]),n.push(Th,uc(e[++r]));return kD(n),new On(n)}xe.str=sS;function Nh(e,t){t instanceof On?e.push(...t._items):t instanceof fs?e.push(t):e.push(CD(t))}xe.addCodeArg=Nh;function kD(e){let t=1;for(;t<e.length-1;){if(e[t]===Th){let n=bD(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function bD(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof fs||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 fs))return`"${e}${t.slice(1)}`}function RD(e,t){return t.emptyStr()?e:e.emptyStr()?t:sS`${e}${t}`}xe.strConcat=RD;function CD(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:uc(Array.isArray(e)?e.join(","):e)}function SD(e){return new On(uc(e))}xe.stringify=SD;function uc(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}xe.safeStringify=uc;function ED(e){return typeof e=="string"&&xe.IDENTIFIER.test(e)?new On(`.${e}`):iS`[${e}]`}xe.getProperty=ED;function AD(e){if(typeof e=="string"&&xe.IDENTIFIER.test(e))return new On(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}xe.getEsmExportName=AD;function xD(e){return new On(e.toString())}xe.regexpCode=xD});var Dh=_(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.ValueScope=ln.ValueScopeName=ln.Scope=ln.varKinds=ln.UsedValueState=void 0;var cn=dc(),$h=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},dd;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(dd||(ln.UsedValueState=dd={}));ln.varKinds={const:new cn.Name("const"),let:new cn.Name("let"),var:new cn.Name("var")};var fd=class{constructor({prefixes:t,parent:n}={}){this._names={},this._prefixes=t,this._parent=n}toName(t){return t instanceof cn.Name?t:this.name(t)}name(t){return new cn.Name(this._newName(t))}_newName(t){let n=this._names[t]||this._nameGroup(t);return`${t}${n.index++}`}_nameGroup(t){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};ln.Scope=fd;var pd=class extends cn.Name{constructor(t,n){super(n),this.prefix=t}setValue(t,{property:n,itemIndex:r}){this.value=t,this.scopePath=(0,cn._)`.${new cn.Name(n)}[${r}]`}};ln.ValueScopeName=pd;var ID=(0,cn._)`\n`,jh=class extends fd{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?ID:cn.nil}}get(){return this._scope}name(t){return new pd(t,this._newName(t))}value(t,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:s}=i,o=(r=n.key)!==null&&r!==void 0?r:n.ref,c=this._values[s];if(c){let a=c.get(o);if(a)return a}else c=this._values[s]=new Map;c.set(o,i);let l=this._scope[s]||(this._scope[s]=[]),f=l.length;return l[f]=n.ref,i.setValue(n,{property:s,itemIndex:f}),i}getValue(t,n){let r=this._values[t];if(r)return r.get(n)}scopeRefs(t,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,cn._)`${t}${r.scopePath}`})}scopeCode(t=this._values,n,r){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},n,r)}_reduceValues(t,n,r={},i){let s=cn.nil;for(let o in t){let c=t[o];if(!c)continue;let l=r[o]=r[o]||new Map;c.forEach(f=>{if(l.has(f))return;l.set(f,dd.Started);let a=n(f);if(a){let d=this.opts.es5?ln.varKinds.var:ln.varKinds.const;s=(0,cn._)`${s}${d} ${f} = ${a};${this.opts._n}`}else if(a=i?.(f))s=(0,cn._)`${s}${a}${this.opts._n}`;else throw new $h(f);l.set(f,dd.Completed)})}return s}};ln.ValueScope=jh});var ge=_(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.or=he.and=he.not=he.CodeGen=he.operators=he.varKinds=he.ValueScopeName=he.ValueScope=he.Scope=he.Name=he.regexpCode=he.stringify=he.getProperty=he.nil=he.strConcat=he.str=he._=void 0;var be=dc(),Yn=Dh(),bi=dc();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return bi._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return bi.str}});Object.defineProperty(he,"strConcat",{enumerable:!0,get:function(){return bi.strConcat}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return bi.nil}});Object.defineProperty(he,"getProperty",{enumerable:!0,get:function(){return bi.getProperty}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return bi.stringify}});Object.defineProperty(he,"regexpCode",{enumerable:!0,get:function(){return bi.regexpCode}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return bi.Name}});var wd=Dh();Object.defineProperty(he,"Scope",{enumerable:!0,get:function(){return wd.Scope}});Object.defineProperty(he,"ValueScope",{enumerable:!0,get:function(){return wd.ValueScope}});Object.defineProperty(he,"ValueScopeName",{enumerable:!0,get:function(){return wd.ValueScopeName}});Object.defineProperty(he,"varKinds",{enumerable:!0,get:function(){return wd.varKinds}});he.operators={GT:new be._Code(">"),GTE:new be._Code(">="),LT:new be._Code("<"),LTE:new be._Code("<="),EQ:new be._Code("==="),NEQ:new be._Code("!=="),NOT:new be._Code("!"),OR:new be._Code("||"),AND:new be._Code("&&"),ADD:new be._Code("+")};var Dr=class{optimizeNodes(){return this}optimizeNames(t,n){return this}},qh=class extends Dr{constructor(t,n,r){super(),this.varKind=t,this.name=n,this.rhs=r}render({es5:t,_n:n}){let r=t?Yn.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+n}optimizeNames(t,n){if(t[this.name.str])return this.rhs&&(this.rhs=Eo(this.rhs,t,n)),this}get names(){return this.rhs instanceof be._CodeOrName?this.rhs.names:{}}},md=class extends Dr{constructor(t,n,r){super(),this.lhs=t,this.rhs=n,this.sideEffects=r}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,n){if(!(this.lhs instanceof be.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Eo(this.rhs,t,n),this}get names(){let t=this.lhs instanceof be.Name?{}:{...this.lhs.names};return gd(t,this.rhs)}},Lh=class extends md{constructor(t,n,r,i){super(t,r,i),this.op=n}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Wh=class extends Dr{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Mh=class extends Dr{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Fh=class extends Dr{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Hh=class extends Dr{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,n){return this.code=Eo(this.code,t,n),this}get names(){return this.code instanceof be._CodeOrName?this.code.names:{}}},fc=class extends Dr{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((n,r)=>n+r.render(t),"")}optimizeNodes(){let{nodes:t}=this,n=t.length;for(;n--;){let r=t[n].optimizeNodes();Array.isArray(r)?t.splice(n,1,...r):r?t[n]=r:t.splice(n,1)}return t.length>0?this:void 0}optimizeNames(t,n){let{nodes:r}=this,i=r.length;for(;i--;){let s=r[i];s.optimizeNames(t,n)||(_D(t,s.names),r.splice(i,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((t,n)=>hs(t,n.names),{})}},qr=class extends fc{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Bh=class extends fc{},So=class extends qr{};So.kind="else";var ps=class e extends qr{constructor(t,n){super(n),this.condition=t}render(t){let n=`if(${this.condition})`+super.render(t);return this.else&&(n+="else "+this.else.render(t)),n}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new So(r):r}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(oS(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(t,n),!!(super.optimizeNames(t,n)||this.else))return this.condition=Eo(this.condition,t,n),this}get names(){let t=super.names;return gd(t,this.condition),this.else&&hs(t,this.else.names),t}};ps.kind="if";var ms=class extends qr{};ms.kind="for";var Vh=class extends ms{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iteration=Eo(this.iteration,t,n),this}get names(){return hs(super.names,this.iteration.names)}},Uh=class extends ms{constructor(t,n,r,i){super(),this.varKind=t,this.name=n,this.from=r,this.to=i}render(t){let n=t.es5?Yn.varKinds.var:this.varKind,{name:r,from:i,to:s}=this;return`for(${n} ${r}=${i}; ${r}<${s}; ${r}++)`+super.render(t)}get names(){let t=gd(super.names,this.from);return gd(t,this.to)}},hd=class extends ms{constructor(t,n,r,i){super(),this.loop=t,this.varKind=n,this.name=r,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,n){if(super.optimizeNames(t,n))return this.iterable=Eo(this.iterable,t,n),this}get names(){return hs(super.names,this.iterable.names)}},pc=class extends qr{constructor(t,n,r){super(),this.name=t,this.args=n,this.async=r}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};pc.kind="func";var mc=class extends fc{render(t){return"return "+super.render(t)}};mc.kind="return";var Kh=class extends qr{render(t){let n="try"+super.render(t);return this.catch&&(n+=this.catch.render(t)),this.finally&&(n+=this.finally.render(t)),n}optimizeNodes(){var t,n;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(t,n){var r,i;return super.optimizeNames(t,n),(r=this.catch)===null||r===void 0||r.optimizeNames(t,n),(i=this.finally)===null||i===void 0||i.optimizeNames(t,n),this}get names(){let t=super.names;return this.catch&&hs(t,this.catch.names),this.finally&&hs(t,this.finally.names),t}},hc=class extends qr{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};hc.kind="catch";var gc=class extends qr{render(t){return"finally"+super.render(t)}};gc.kind="finally";var zh=class{constructor(t,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
150
|
+
`:""},this._extScope=t,this._scope=new Yn.Scope({parent:t}),this._nodes=[new Bh]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,n){let r=this._extScope.value(t,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(t,n){return this._extScope.getValue(t,n)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,n,r,i){let s=this._scope.toName(n);return r!==void 0&&i&&(this._constants[s.str]=r),this._leafNode(new qh(t,s,r)),s}const(t,n,r){return this._def(Yn.varKinds.const,t,n,r)}let(t,n,r){return this._def(Yn.varKinds.let,t,n,r)}var(t,n,r){return this._def(Yn.varKinds.var,t,n,r)}assign(t,n,r){return this._leafNode(new md(t,n,r))}add(t,n){return this._leafNode(new Lh(t,he.operators.ADD,n))}code(t){return typeof t=="function"?t():t!==be.nil&&this._leafNode(new Hh(t)),this}object(...t){let n=["{"];for(let[r,i]of t)n.length>1&&n.push(","),n.push(r),(r!==i||this.opts.es5)&&(n.push(":"),(0,be.addCodeArg)(n,i));return n.push("}"),new be._Code(n)}if(t,n,r){if(this._blockNode(new ps(t)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new ps(t))}else(){return this._elseNode(new So)}endIf(){return this._endBlockNode(ps,So)}_for(t,n){return this._blockNode(t),n&&this.code(n).endFor(),this}for(t,n){return this._for(new Vh(t),n)}forRange(t,n,r,i,s=this.opts.es5?Yn.varKinds.var:Yn.varKinds.let){let o=this._scope.toName(t);return this._for(new Uh(s,o,n,r),()=>i(o))}forOf(t,n,r,i=Yn.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let o=n instanceof be.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,be._)`${o}.length`,c=>{this.var(s,(0,be._)`${o}[${c}]`),r(s)})}return this._for(new hd("of",i,s,n),()=>r(s))}forIn(t,n,r,i=this.opts.es5?Yn.varKinds.var:Yn.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,be._)`Object.keys(${n})`,r);let s=this._scope.toName(t);return this._for(new hd("in",i,s,n),()=>r(s))}endFor(){return this._endBlockNode(ms)}label(t){return this._leafNode(new Wh(t))}break(t){return this._leafNode(new Mh(t))}return(t){let n=new mc;if(this._blockNode(n),this.code(t),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(mc)}try(t,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Kh;if(this._blockNode(i),this.code(t),n){let s=this.name("e");this._currNode=i.catch=new hc(s),n(s)}return r&&(this._currNode=i.finally=new gc,this.code(r)),this._endBlockNode(hc,gc)}throw(t){return this._leafNode(new Fh(t))}block(t,n){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(n),this}endBlock(t){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||t!==void 0&&r!==t)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${t} expected`);return this._nodes.length=n,this}func(t,n=be.nil,r,i){return this._blockNode(new pc(t,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(pc)}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,n){let r=this._currNode;if(r instanceof t||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${t.kind}/${n.kind}`:t.kind}"`)}_elseNode(t){let n=this._currNode;if(!(n instanceof ps))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let n=this._nodes;n[n.length-1]=t}};he.CodeGen=zh;function hs(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function gd(e,t){return t instanceof be._CodeOrName?hs(e,t.names):e}function Eo(e,t,n){if(e instanceof be.Name)return r(e);if(!i(e))return e;return new be._Code(e._items.reduce((s,o)=>(o instanceof be.Name&&(o=r(o)),o instanceof be._Code?s.push(...o._items):s.push(o),s),[]));function r(s){let o=n[s.str];return o===void 0||t[s.str]!==1?s:(delete t[s.str],o)}function i(s){return s instanceof be._Code&&s._items.some(o=>o instanceof be.Name&&t[o.str]===1&&n[o.str]!==void 0)}}function _D(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function oS(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,be._)`!${Jh(e)}`}he.not=oS;var PD=aS(he.operators.AND);function OD(...e){return e.reduce(PD)}he.and=OD;var TD=aS(he.operators.OR);function ND(...e){return e.reduce(TD)}he.or=ND;function aS(e){return(t,n)=>t===be.nil?n:n===be.nil?t:(0,be._)`${Jh(t)} ${e} ${Jh(n)}`}function Jh(e){return e instanceof be.Name?e:(0,be._)`(${e})`}});var Se=_(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.checkStrictMode=we.getErrorPath=we.Type=we.useFunc=we.setEvaluated=we.evaluatedPropsToName=we.mergeEvaluated=we.eachItem=we.unescapeJsonPointer=we.escapeJsonPointer=we.escapeFragment=we.unescapeFragment=we.schemaRefOrVal=we.schemaHasRulesButRef=we.schemaHasRules=we.checkUnknownRules=we.alwaysValidSchema=we.toHash=void 0;var je=ge(),$D=dc();function jD(e){let t={};for(let n of e)t[n]=!0;return t}we.toHash=jD;function DD(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(uS(e,t),!dS(t,e.self.RULES.all))}we.alwaysValidSchema=DD;function uS(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;let i=r.RULES.keywords;for(let s in t)i[s]||mS(e,`unknown keyword: "${s}"`)}we.checkUnknownRules=uS;function dS(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}we.schemaHasRules=dS;function qD(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}we.schemaHasRulesButRef=qD;function LD({topSchemaRef:e,schemaPath:t},n,r,i){if(!i){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,je._)`${n}`}return(0,je._)`${e}${t}${(0,je.getProperty)(r)}`}we.schemaRefOrVal=LD;function WD(e){return fS(decodeURIComponent(e))}we.unescapeFragment=WD;function MD(e){return encodeURIComponent(Yh(e))}we.escapeFragment=MD;function Yh(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}we.escapeJsonPointer=Yh;function fS(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}we.unescapeJsonPointer=fS;function FD(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}we.eachItem=FD;function cS({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(i,s,o,c)=>{let l=o===void 0?s:o instanceof je.Name?(s instanceof je.Name?e(i,s,o):t(i,s,o),o):s instanceof je.Name?(t(i,o,s),s):n(s,o);return c===je.Name&&!(l instanceof je.Name)?r(i,l):l}}we.mergeEvaluated={props:cS({mergeNames:(e,t,n)=>e.if((0,je._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,je._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,je._)`${n} || {}`).code((0,je._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,je._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,je._)`${n} || {}`),Xh(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:pS}),items:cS({mergeNames:(e,t,n)=>e.if((0,je._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,je._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,je._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,je._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function pS(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",(0,je._)`{}`);return t!==void 0&&Xh(e,n,t),n}we.evaluatedPropsToName=pS;function Xh(e,t,n){Object.keys(n).forEach(r=>e.assign((0,je._)`${t}${(0,je.getProperty)(r)}`,!0))}we.setEvaluated=Xh;var lS={};function HD(e,t){return e.scopeValue("func",{ref:t,code:lS[t.code]||(lS[t.code]=new $D._Code(t.code))})}we.useFunc=HD;var Gh;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Gh||(we.Type=Gh={}));function BD(e,t,n){if(e instanceof je.Name){let r=t===Gh.Num;return n?r?(0,je._)`"[" + ${e} + "]"`:(0,je._)`"['" + ${e} + "']"`:r?(0,je._)`"/" + ${e}`:(0,je._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,je.getProperty)(e).toString():"/"+Yh(e)}we.getErrorPath=BD;function mS(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}we.checkStrictMode=mS});var Lr=_(Qh=>{"use strict";Object.defineProperty(Qh,"__esModule",{value:!0});var Dt=ge(),VD={data:new Dt.Name("data"),valCxt:new Dt.Name("valCxt"),instancePath:new Dt.Name("instancePath"),parentData:new Dt.Name("parentData"),parentDataProperty:new Dt.Name("parentDataProperty"),rootData:new Dt.Name("rootData"),dynamicAnchors:new Dt.Name("dynamicAnchors"),vErrors:new Dt.Name("vErrors"),errors:new Dt.Name("errors"),this:new Dt.Name("this"),self:new Dt.Name("self"),scope:new Dt.Name("scope"),json:new Dt.Name("json"),jsonPos:new Dt.Name("jsonPos"),jsonLen:new Dt.Name("jsonLen"),jsonPart:new Dt.Name("jsonPart")};Qh.default=VD});var wc=_(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.extendErrors=qt.resetErrorsCount=qt.reportExtraError=qt.reportError=qt.keyword$DataError=qt.keywordError=void 0;var Ee=ge(),yd=Se(),Ut=Lr();qt.keywordError={message:({keyword:e})=>(0,Ee.str)`must pass "${e}" keyword validation`};qt.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Ee.str)`"${e}" keyword must be ${t} ($data)`:(0,Ee.str)`"${e}" keyword is invalid ($data)`};function UD(e,t=qt.keywordError,n,r){let{it:i}=e,{gen:s,compositeRule:o,allErrors:c}=i,l=wS(e,t,n);r??(o||c)?hS(s,l):gS(i,(0,Ee._)`[${l}]`)}qt.reportError=UD;function KD(e,t=qt.keywordError,n){let{it:r}=e,{gen:i,compositeRule:s,allErrors:o}=r,c=wS(e,t,n);hS(i,c),s||o||gS(r,Ut.default.vErrors)}qt.reportExtraError=KD;function zD(e,t){e.assign(Ut.default.errors,t),e.if((0,Ee._)`${Ut.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Ee._)`${Ut.default.vErrors}.length`,t),()=>e.assign(Ut.default.vErrors,null)))}qt.resetErrorsCount=zD;function JD({gen:e,keyword:t,schemaValue:n,data:r,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=e.name("err");e.forRange("i",i,Ut.default.errors,c=>{e.const(o,(0,Ee._)`${Ut.default.vErrors}[${c}]`),e.if((0,Ee._)`${o}.instancePath === undefined`,()=>e.assign((0,Ee._)`${o}.instancePath`,(0,Ee.strConcat)(Ut.default.instancePath,s.errorPath))),e.assign((0,Ee._)`${o}.schemaPath`,(0,Ee.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,Ee._)`${o}.schema`,n),e.assign((0,Ee._)`${o}.data`,r))})}qt.extendErrors=JD;function hS(e,t){let n=e.const("err",t);e.if((0,Ee._)`${Ut.default.vErrors} === null`,()=>e.assign(Ut.default.vErrors,(0,Ee._)`[${n}]`),(0,Ee._)`${Ut.default.vErrors}.push(${n})`),e.code((0,Ee._)`${Ut.default.errors}++`)}function gS(e,t){let{gen:n,validateName:r,schemaEnv:i}=e;i.$async?n.throw((0,Ee._)`new ${e.ValidationError}(${t})`):(n.assign((0,Ee._)`${r}.errors`,t),n.return(!1))}var gs={keyword:new Ee.Name("keyword"),schemaPath:new Ee.Name("schemaPath"),params:new Ee.Name("params"),propertyName:new Ee.Name("propertyName"),message:new Ee.Name("message"),schema:new Ee.Name("schema"),parentSchema:new Ee.Name("parentSchema")};function wS(e,t,n){let{createErrors:r}=e.it;return r===!1?(0,Ee._)`{}`:GD(e,t,n)}function GD(e,t,n={}){let{gen:r,it:i}=e,s=[YD(i,n),XD(e,n)];return QD(e,t,s),r.object(...s)}function YD({errorPath:e},{instancePath:t}){let n=t?(0,Ee.str)`${e}${(0,yd.getErrorPath)(t,yd.Type.Str)}`:e;return[Ut.default.instancePath,(0,Ee.strConcat)(Ut.default.instancePath,n)]}function XD({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:r}){let i=r?t:(0,Ee.str)`${t}/${e}`;return n&&(i=(0,Ee.str)`${i}${(0,yd.getErrorPath)(n,yd.Type.Str)}`),[gs.schemaPath,i]}function QD(e,{params:t,message:n},r){let{keyword:i,data:s,schemaValue:o,it:c}=e,{opts:l,propertyName:f,topSchemaRef:a,schemaPath:d}=c;r.push([gs.keyword,i],[gs.params,typeof t=="function"?t(e):t||(0,Ee._)`{}`]),l.messages&&r.push([gs.message,typeof n=="function"?n(e):n]),l.verbose&&r.push([gs.schema,o],[gs.parentSchema,(0,Ee._)`${a}${d}`],[Ut.default.data,s]),f&&r.push([gs.propertyName,f])}});var vS=_(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.boolOrEmptySchema=Ao.topBoolOrEmptySchema=void 0;var ZD=wc(),e1=ge(),t1=Lr(),n1={message:"boolean schema is false"};function r1(e){let{gen:t,schema:n,validateName:r}=e;n===!1?yS(e,!1):typeof n=="object"&&n.$async===!0?t.return(t1.default.data):(t.assign((0,e1._)`${r}.errors`,null),t.return(!0))}Ao.topBoolOrEmptySchema=r1;function i1(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),yS(e)):n.var(t,!0)}Ao.boolOrEmptySchema=i1;function yS(e,t){let{gen:n,data:r}=e,i={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,ZD.reportError)(i,n1,void 0,t)}});var Zh=_(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.getRules=xo.isJSONType=void 0;var s1=["string","number","integer","boolean","null","object","array"],o1=new Set(s1);function a1(e){return typeof e=="string"&&o1.has(e)}xo.isJSONType=a1;function c1(){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:{}}}xo.getRules=c1});var eg=_(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});Ri.shouldUseRule=Ri.shouldUseGroup=Ri.schemaHasRulesForType=void 0;function l1({schema:e,self:t},n){let r=t.RULES.types[n];return r&&r!==!0&&kS(e,r)}Ri.schemaHasRulesForType=l1;function kS(e,t){return t.rules.some(n=>bS(e,n))}Ri.shouldUseGroup=kS;function bS(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}Ri.shouldUseRule=bS});var yc=_(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.reportTypeError=Lt.checkDataTypes=Lt.checkDataType=Lt.coerceAndCheckDataType=Lt.getJSONTypes=Lt.getSchemaTypes=Lt.DataType=void 0;var u1=Zh(),d1=eg(),f1=wc(),de=ge(),RS=Se(),Io;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Io||(Lt.DataType=Io={}));function p1(e){let t=CS(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}Lt.getSchemaTypes=p1;function CS(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(u1.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Lt.getJSONTypes=CS;function m1(e,t){let{gen:n,data:r,opts:i}=e,s=h1(t,i.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,d1.schemaHasRulesForType)(e,t[0]));if(o){let c=ng(t,r,i.strictNumbers,Io.Wrong);n.if(c,()=>{s.length?g1(e,t,s):rg(e)})}return o}Lt.coerceAndCheckDataType=m1;var SS=new Set(["string","number","integer","boolean","null"]);function h1(e,t){return t?e.filter(n=>SS.has(n)||t==="array"&&n==="array"):[]}function g1(e,t,n){let{gen:r,data:i,opts:s}=e,o=r.let("dataType",(0,de._)`typeof ${i}`),c=r.let("coerced",(0,de._)`undefined`);s.coerceTypes==="array"&&r.if((0,de._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0,de._)`${i}[0]`).assign(o,(0,de._)`typeof ${i}`).if(ng(t,i,s.strictNumbers),()=>r.assign(c,i))),r.if((0,de._)`${c} !== undefined`);for(let f of n)(SS.has(f)||f==="array"&&s.coerceTypes==="array")&&l(f);r.else(),rg(e),r.endIf(),r.if((0,de._)`${c} !== undefined`,()=>{r.assign(i,c),w1(e,c)});function l(f){switch(f){case"string":r.elseIf((0,de._)`${o} == "number" || ${o} == "boolean"`).assign(c,(0,de._)`"" + ${i}`).elseIf((0,de._)`${i} === null`).assign(c,(0,de._)`""`);return;case"number":r.elseIf((0,de._)`${o} == "boolean" || ${i} === null
|
|
151
|
+
|| (${o} == "string" && ${i} && ${i} == +${i})`).assign(c,(0,de._)`+${i}`);return;case"integer":r.elseIf((0,de._)`${o} === "boolean" || ${i} === null
|
|
152
|
+
|| (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(c,(0,de._)`+${i}`);return;case"boolean":r.elseIf((0,de._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(c,!1).elseIf((0,de._)`${i} === "true" || ${i} === 1`).assign(c,!0);return;case"null":r.elseIf((0,de._)`${i} === "" || ${i} === 0 || ${i} === false`),r.assign(c,null);return;case"array":r.elseIf((0,de._)`${o} === "string" || ${o} === "number"
|
|
153
|
+
|| ${o} === "boolean" || ${i} === null`).assign(c,(0,de._)`[${i}]`)}}}function w1({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,de._)`${t} !== undefined`,()=>e.assign((0,de._)`${t}[${n}]`,r))}function tg(e,t,n,r=Io.Correct){let i=r===Io.Correct?de.operators.EQ:de.operators.NEQ,s;switch(e){case"null":return(0,de._)`${t} ${i} null`;case"array":s=(0,de._)`Array.isArray(${t})`;break;case"object":s=(0,de._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o((0,de._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return(0,de._)`typeof ${t} ${i} ${e}`}return r===Io.Correct?s:(0,de.not)(s);function o(c=de.nil){return(0,de.and)((0,de._)`typeof ${t} == "number"`,c,n?(0,de._)`isFinite(${t})`:de.nil)}}Lt.checkDataType=tg;function ng(e,t,n,r){if(e.length===1)return tg(e[0],t,n,r);let i,s=(0,RS.toHash)(e);if(s.array&&s.object){let o=(0,de._)`typeof ${t} != "object"`;i=s.null?o:(0,de._)`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else i=de.nil;s.number&&delete s.integer;for(let o in s)i=(0,de.and)(i,tg(o,t,n,r));return i}Lt.checkDataTypes=ng;var y1={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,de._)`{type: ${e}}`:(0,de._)`{type: ${t}}`};function rg(e){let t=v1(e);(0,f1.reportError)(t,y1)}Lt.reportTypeError=rg;function v1(e){let{gen:t,data:n,schema:r}=e,i=(0,RS.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}});var AS=_(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});vd.assignDefaults=void 0;var _o=ge(),k1=Se();function b1(e,t){let{properties:n,items:r}=e.schema;if(t==="object"&&n)for(let i in n)ES(e,i,n[i].default);else t==="array"&&Array.isArray(r)&&r.forEach((i,s)=>ES(e,s,i.default))}vd.assignDefaults=b1;function ES(e,t,n){let{gen:r,compositeRule:i,data:s,opts:o}=e;if(n===void 0)return;let c=(0,_o._)`${s}${(0,_o.getProperty)(t)}`;if(i){(0,k1.checkStrictMode)(e,`default is ignored for: ${c}`);return}let l=(0,_o._)`${c} === undefined`;o.useDefaults==="empty"&&(l=(0,_o._)`${l} || ${c} === null || ${c} === ""`),r.if(l,(0,_o._)`${c} = ${(0,_o.stringify)(n)}`)}});var Tn=_(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.validateUnion=Ne.validateArray=Ne.usePattern=Ne.callValidateCode=Ne.schemaProperties=Ne.allSchemaProperties=Ne.noPropertyInData=Ne.propertyInData=Ne.isOwnProperty=Ne.hasPropFunc=Ne.reportMissingProp=Ne.checkMissingProp=Ne.checkReportMissingProp=void 0;var We=ge(),ig=Se(),Ci=Lr(),R1=Se();function C1(e,t){let{gen:n,data:r,it:i}=e;n.if(og(n,r,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,We._)`${t}`},!0),e.error()})}Ne.checkReportMissingProp=C1;function S1({gen:e,data:t,it:{opts:n}},r,i){return(0,We.or)(...r.map(s=>(0,We.and)(og(e,t,s,n.ownProperties),(0,We._)`${i} = ${s}`)))}Ne.checkMissingProp=S1;function E1(e,t){e.setParams({missingProperty:t},!0),e.error()}Ne.reportMissingProp=E1;function xS(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,We._)`Object.prototype.hasOwnProperty`})}Ne.hasPropFunc=xS;function sg(e,t,n){return(0,We._)`${xS(e)}.call(${t}, ${n})`}Ne.isOwnProperty=sg;function A1(e,t,n,r){let i=(0,We._)`${t}${(0,We.getProperty)(n)} !== undefined`;return r?(0,We._)`${i} && ${sg(e,t,n)}`:i}Ne.propertyInData=A1;function og(e,t,n,r){let i=(0,We._)`${t}${(0,We.getProperty)(n)} === undefined`;return r?(0,We.or)(i,(0,We.not)(sg(e,t,n))):i}Ne.noPropertyInData=og;function IS(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Ne.allSchemaProperties=IS;function x1(e,t){return IS(t).filter(n=>!(0,ig.alwaysValidSchema)(e,t[n]))}Ne.schemaProperties=x1;function I1({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:i,errorPath:s},it:o},c,l,f){let a=f?(0,We._)`${e}, ${t}, ${r}${i}`:t,d=[[Ci.default.instancePath,(0,We.strConcat)(Ci.default.instancePath,s)],[Ci.default.parentData,o.parentData],[Ci.default.parentDataProperty,o.parentDataProperty],[Ci.default.rootData,Ci.default.rootData]];o.opts.dynamicRef&&d.push([Ci.default.dynamicAnchors,Ci.default.dynamicAnchors]);let p=(0,We._)`${a}, ${n.object(...d)}`;return l!==We.nil?(0,We._)`${c}.call(${l}, ${p})`:(0,We._)`${c}(${p})`}Ne.callValidateCode=I1;var _1=(0,We._)`new RegExp`;function P1({gen:e,it:{opts:t}},n){let r=t.unicodeRegExp?"u":"",{regExp:i}=t.code,s=i(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,We._)`${i.code==="new RegExp"?_1:(0,R1.useFunc)(e,i)}(${n}, ${r})`})}Ne.usePattern=P1;function O1(e){let{gen:t,data:n,keyword:r,it:i}=e,s=t.name("valid");if(i.allErrors){let c=t.let("valid",!0);return o(()=>t.assign(c,!1)),c}return t.var(s,!0),o(()=>t.break()),s;function o(c){let l=t.const("len",(0,We._)`${n}.length`);t.forRange("i",0,l,f=>{e.subschema({keyword:r,dataProp:f,dataPropType:ig.Type.Num},s),t.if((0,We.not)(s),c)})}}Ne.validateArray=O1;function T1(e){let{gen:t,schema:n,keyword:r,it:i}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,ig.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let o=t.let("valid",!1),c=t.name("_valid");t.block(()=>n.forEach((l,f)=>{let a=e.subschema({keyword:r,schemaProp:f,compositeRule:!0},c);t.assign(o,(0,We._)`${o} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,We.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}Ne.validateUnion=T1});var OS=_(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.validateKeywordUsage=gr.validSchemaType=gr.funcKeywordCode=gr.macroKeywordCode=void 0;var Kt=ge(),ws=Lr(),N1=Tn(),$1=wc();function j1(e,t){let{gen:n,keyword:r,schema:i,parentSchema:s,it:o}=e,c=t.macro.call(o.self,i,s,o),l=PS(n,r,c);o.opts.validateSchema!==!1&&o.self.validateSchema(c,!0);let f=n.name("valid");e.subschema({schema:c,schemaPath:Kt.nil,errSchemaPath:`${o.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},f),e.pass(f,()=>e.error(!0))}gr.macroKeywordCode=j1;function D1(e,t){var n;let{gen:r,keyword:i,schema:s,parentSchema:o,$data:c,it:l}=e;L1(l,t);let f=!c&&t.compile?t.compile.call(l.self,s,o,l):t.validate,a=PS(r,i,f),d=r.let("valid");e.block$data(d,p),e.ok((n=t.valid)!==null&&n!==void 0?n:d);function p(){if(t.errors===!1)h(),t.modifying&&_S(e),g(()=>e.error());else{let w=t.async?u():m();t.modifying&&_S(e),g(()=>q1(e,w))}}function u(){let w=r.let("ruleErrs",null);return r.try(()=>h((0,Kt._)`await `),k=>r.assign(d,!1).if((0,Kt._)`${k} instanceof ${l.ValidationError}`,()=>r.assign(w,(0,Kt._)`${k}.errors`),()=>r.throw(k))),w}function m(){let w=(0,Kt._)`${a}.errors`;return r.assign(w,null),h(Kt.nil),w}function h(w=t.async?(0,Kt._)`await `:Kt.nil){let k=l.opts.passContext?ws.default.this:ws.default.self,y=!("compile"in t&&!c||t.schema===!1);r.assign(d,(0,Kt._)`${w}${(0,N1.callValidateCode)(e,a,k,y)}`,t.modifying)}function g(w){var k;r.if((0,Kt.not)((k=t.valid)!==null&&k!==void 0?k:d),w)}}gr.funcKeywordCode=D1;function _S(e){let{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,Kt._)`${r.parentData}[${r.parentDataProperty}]`))}function q1(e,t){let{gen:n}=e;n.if((0,Kt._)`Array.isArray(${t})`,()=>{n.assign(ws.default.vErrors,(0,Kt._)`${ws.default.vErrors} === null ? ${t} : ${ws.default.vErrors}.concat(${t})`).assign(ws.default.errors,(0,Kt._)`${ws.default.vErrors}.length`),(0,$1.extendErrors)(e)},()=>e.error())}function L1({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function PS(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Kt.stringify)(n)})}function W1(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}gr.validSchemaType=W1;function M1({schema:e,opts:t,self:n,errSchemaPath:r},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(c=>!Object.prototype.hasOwnProperty.call(e,c)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[s])){let l=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}gr.validateKeywordUsage=M1});var NS=_(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.extendSubschemaMode=Si.extendSubschemaData=Si.getSubschema=void 0;var wr=ge(),TS=Se();function F1(e,{keyword:t,schemaProp:n,schema:r,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let c=e.schema[t];return n===void 0?{schema:c,schemaPath:(0,wr._)`${e.schemaPath}${(0,wr.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[n],schemaPath:(0,wr._)`${e.schemaPath}${(0,wr.getProperty)(t)}${(0,wr.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,TS.escapeFragment)(n)}`}}if(r!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Si.getSubschema=F1;function H1(e,t,{dataProp:n,dataPropType:r,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(n!==void 0){let{errorPath:f,dataPathArr:a,opts:d}=t,p=c.let("data",(0,wr._)`${t.data}${(0,wr.getProperty)(n)}`,!0);l(p),e.errorPath=(0,wr.str)`${f}${(0,TS.getErrorPath)(n,r,d.jsPropertySyntax)}`,e.parentDataProperty=(0,wr._)`${n}`,e.dataPathArr=[...a,e.parentDataProperty]}if(i!==void 0){let f=i instanceof wr.Name?i:c.let("data",i,!0);l(f),o!==void 0&&(e.propertyName=o)}s&&(e.dataTypes=s);function l(f){e.data=f,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,f]}}Si.extendSubschemaData=H1;function B1(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:s}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}Si.extendSubschemaMode=B1});var ag=_((V6,$S)=>{"use strict";$S.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,i,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[i]))return!1;for(i=r;i--!==0;){var o=s[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}});var DS=_((U6,jS)=>{"use strict";var Ei=jS.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},i=n.post||function(){};kd(t,r,i,e,"",e)};Ei.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ei.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ei.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ei.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 kd(e,t,n,r,i,s,o,c,l,f){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,i,s,o,c,l,f);for(var a in r){var d=r[a];if(Array.isArray(d)){if(a in Ei.arrayKeywords)for(var p=0;p<d.length;p++)kd(e,t,n,d[p],i+"/"+a+"/"+p,s,i,a,r,p)}else if(a in Ei.propsKeywords){if(d&&typeof d=="object")for(var u in d)kd(e,t,n,d[u],i+"/"+a+"/"+V1(u),s,i,a,r,u)}else(a in Ei.keywords||e.allKeys&&!(a in Ei.skipKeywords))&&kd(e,t,n,d,i+"/"+a,s,i,a,r)}n(r,i,s,o,c,l,f)}}function V1(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var vc=_(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.getSchemaRefs=un.resolveUrl=un.normalizeId=un._getFullPath=un.getFullPath=un.inlineRef=void 0;var U1=Se(),K1=ag(),z1=DS(),J1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function G1(e,t=!0){return typeof e=="boolean"?!0:t===!0?!cg(e):t?qS(e)<=t:!1}un.inlineRef=G1;var Y1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cg(e){for(let t in e){if(Y1.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(cg)||typeof n=="object"&&cg(n))return!0}return!1}function qS(e){let t=0;for(let n in e){if(n==="$ref")return 1/0;if(t++,!J1.has(n)&&(typeof e[n]=="object"&&(0,U1.eachItem)(e[n],r=>t+=qS(r)),t===1/0))return 1/0}return t}function LS(e,t="",n){n!==!1&&(t=Po(t));let r=e.parse(t);return WS(e,r)}un.getFullPath=LS;function WS(e,t){return e.serialize(t).split("#")[0]+"#"}un._getFullPath=WS;var X1=/#\/?$/;function Po(e){return e?e.replace(X1,""):""}un.normalizeId=Po;function Q1(e,t,n){return n=Po(n),e.resolve(t,n)}un.resolveUrl=Q1;var Z1=/^[a-z_][-a-z0-9._]*$/i;function eq(e,t){if(typeof e=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,i=Po(e[n]||t),s={"":i},o=LS(r,i,!1),c={},l=new Set;return z1(e,{allKeys:!0},(d,p,u,m)=>{if(m===void 0)return;let h=o+p,g=s[m];typeof d[n]=="string"&&(g=w.call(this,d[n])),k.call(this,d.$anchor),k.call(this,d.$dynamicAnchor),s[p]=g;function w(y){let R=this.opts.uriResolver.resolve;if(y=Po(g?R(g,y):y),l.has(y))throw a(y);l.add(y);let C=this.refs[y];return typeof C=="string"&&(C=this.refs[C]),typeof C=="object"?f(d,C.schema,y):y!==Po(h)&&(y[0]==="#"?(f(d,c[y],y),c[y]=d):this.refs[y]=h),y}function k(y){if(typeof y=="string"){if(!Z1.test(y))throw new Error(`invalid anchor "${y}"`);w.call(this,`#${y}`)}}}),c;function f(d,p,u){if(p!==void 0&&!K1(d,p))throw a(u)}function a(d){return new Error(`reference "${d}" resolves to more than one schema`)}}un.getSchemaRefs=eq});var Rc=_(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.getData=Ai.KeywordCxt=Ai.validateFunctionCode=void 0;var VS=vS(),MS=yc(),ug=eg(),bd=yc(),tq=AS(),bc=OS(),lg=NS(),te=ge(),oe=Lr(),nq=vc(),Wr=Se(),kc=wc();function rq(e){if(zS(e)&&(JS(e),KS(e))){oq(e);return}US(e,()=>(0,VS.topBoolOrEmptySchema)(e))}Ai.validateFunctionCode=rq;function US({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},s){i.code.es5?e.func(t,(0,te._)`${oe.default.data}, ${oe.default.valCxt}`,r.$async,()=>{e.code((0,te._)`"use strict"; ${FS(n,i)}`),sq(e,i),e.code(s)}):e.func(t,(0,te._)`${oe.default.data}, ${iq(i)}`,r.$async,()=>e.code(FS(n,i)).code(s))}function iq(e){return(0,te._)`{${oe.default.instancePath}="", ${oe.default.parentData}, ${oe.default.parentDataProperty}, ${oe.default.rootData}=${oe.default.data}${e.dynamicRef?(0,te._)`, ${oe.default.dynamicAnchors}={}`:te.nil}}={}`}function sq(e,t){e.if(oe.default.valCxt,()=>{e.var(oe.default.instancePath,(0,te._)`${oe.default.valCxt}.${oe.default.instancePath}`),e.var(oe.default.parentData,(0,te._)`${oe.default.valCxt}.${oe.default.parentData}`),e.var(oe.default.parentDataProperty,(0,te._)`${oe.default.valCxt}.${oe.default.parentDataProperty}`),e.var(oe.default.rootData,(0,te._)`${oe.default.valCxt}.${oe.default.rootData}`),t.dynamicRef&&e.var(oe.default.dynamicAnchors,(0,te._)`${oe.default.valCxt}.${oe.default.dynamicAnchors}`)},()=>{e.var(oe.default.instancePath,(0,te._)`""`),e.var(oe.default.parentData,(0,te._)`undefined`),e.var(oe.default.parentDataProperty,(0,te._)`undefined`),e.var(oe.default.rootData,oe.default.data),t.dynamicRef&&e.var(oe.default.dynamicAnchors,(0,te._)`{}`)})}function oq(e){let{schema:t,opts:n,gen:r}=e;US(e,()=>{n.$comment&&t.$comment&&YS(e),dq(e),r.let(oe.default.vErrors,null),r.let(oe.default.errors,0),n.unevaluated&&aq(e),GS(e),mq(e)})}function aq(e){let{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,te._)`${n}.evaluated`),t.if((0,te._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,te._)`${e.evaluated}.props`,(0,te._)`undefined`)),t.if((0,te._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,te._)`${e.evaluated}.items`,(0,te._)`undefined`))}function FS(e,t){let n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,te._)`/*# sourceURL=${n} */`:te.nil}function cq(e,t){if(zS(e)&&(JS(e),KS(e))){lq(e,t);return}(0,VS.boolOrEmptySchema)(e,t)}function KS({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function zS(e){return typeof e.schema!="boolean"}function lq(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&YS(e),fq(e),pq(e);let s=r.const("_errs",oe.default.errors);GS(e,s),r.var(t,(0,te._)`${s} === ${oe.default.errors}`)}function JS(e){(0,Wr.checkUnknownRules)(e),uq(e)}function GS(e,t){if(e.opts.jtd)return HS(e,[],!1,t);let n=(0,MS.getSchemaTypes)(e.schema),r=(0,MS.coerceAndCheckDataType)(e,n);HS(e,n,!r,t)}function uq(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,Wr.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function dq(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Wr.checkStrictMode)(e,"default is ignored in the schema root")}function fq(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,nq.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function pq(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function YS({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let s=n.$comment;if(i.$comment===!0)e.code((0,te._)`${oe.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,te.str)`${r}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,te._)`${oe.default.self}.opts.$comment(${s}, ${o}, ${c}.schema)`)}}function mq(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:s}=e;n.$async?t.if((0,te._)`${oe.default.errors} === 0`,()=>t.return(oe.default.data),()=>t.throw((0,te._)`new ${i}(${oe.default.vErrors})`)):(t.assign((0,te._)`${r}.errors`,oe.default.vErrors),s.unevaluated&&hq(e),t.return((0,te._)`${oe.default.errors} === 0`))}function hq({gen:e,evaluated:t,props:n,items:r}){n instanceof te.Name&&e.assign((0,te._)`${t}.props`,n),r instanceof te.Name&&e.assign((0,te._)`${t}.items`,r)}function HS(e,t,n,r){let{gen:i,schema:s,data:o,allErrors:c,opts:l,self:f}=e,{RULES:a}=f;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,Wr.schemaHasRulesButRef)(s,a))){i.block(()=>QS(e,"$ref",a.all.$ref.definition));return}l.jtd||gq(e,t),i.block(()=>{for(let p of a.rules)d(p);d(a.post)});function d(p){(0,ug.shouldUseGroup)(s,p)&&(p.type?(i.if((0,bd.checkDataType)(p.type,o,l.strictNumbers)),BS(e,p),t.length===1&&t[0]===p.type&&n&&(i.else(),(0,bd.reportTypeError)(e)),i.endIf()):BS(e,p),c||i.if((0,te._)`${oe.default.errors} === ${r||0}`))}}function BS(e,t){let{gen:n,schema:r,opts:{useDefaults:i}}=e;i&&(0,tq.assignDefaults)(e,t.type),n.block(()=>{for(let s of t.rules)(0,ug.shouldUseRule)(r,s)&&QS(e,s.keyword,s.definition,t.type)})}function gq(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(wq(e,t),e.opts.allowUnionTypes||yq(e,t),vq(e,e.dataTypes))}function wq(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{XS(e.dataTypes,n)||dg(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),bq(e,t)}}function yq(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&dg(e,"use allowUnionTypes to allow union type keyword")}function vq(e,t){let n=e.self.RULES.all;for(let r in n){let i=n[r];if(typeof i=="object"&&(0,ug.shouldUseRule)(e.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>kq(t,o))&&dg(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function kq(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function XS(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function bq(e,t){let n=[];for(let r of e.dataTypes)XS(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function dg(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,Wr.checkStrictMode)(e,t,e.opts.strictTypes)}var Rd=class{constructor(t,n,r){if((0,bc.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Wr.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",ZS(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,bc.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=t.gen.const("_errs",oe.default.errors))}result(t,n,r){this.failResult((0,te.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,te.not)(t),void 0,n)}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:n}=this;this.fail((0,te._)`${n} !== undefined && (${(0,te.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?kc.reportExtraError:kc.reportError)(this,this.def.error,n)}$dataError(){(0,kc.reportError)(this,this.def.$dataError||kc.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,kc.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=te.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=te.nil,n=te.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:s,def:o}=this;r.if((0,te.or)((0,te._)`${i} === undefined`,n)),t!==te.nil&&r.assign(t,!0),(s.length||o.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==te.nil&&r.assign(t,!1)),r.else()}invalid$data(){let{gen:t,schemaCode:n,schemaType:r,def:i,it:s}=this;return(0,te.or)(o(),c());function o(){if(r.length){if(!(n instanceof te.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,te._)`${(0,bd.checkDataTypes)(l,n,s.opts.strictNumbers,bd.DataType.Wrong)}`}return te.nil}function c(){if(i.validateSchema){let l=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,te._)`!${l}(${n})`}return te.nil}}subschema(t,n){let r=(0,lg.getSubschema)(this.it,t);(0,lg.extendSubschemaData)(r,this.it,t),(0,lg.extendSubschemaMode)(r,t);let i={...this.it,...r,items:void 0,props:void 0};return cq(i,n),i}mergeEvaluated(t,n){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=Wr.mergeEvaluated.props(i,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=Wr.mergeEvaluated.items(i,t.items,r.items,n)))}mergeValidEvaluated(t,n){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return i.if(n,()=>this.mergeEvaluated(t,te.Name)),!0}};Ai.KeywordCxt=Rd;function QS(e,t,n,r){let i=new Rd(e,n,t);"code"in n?n.code(i,r):i.$data&&n.validate?(0,bc.funcKeywordCode)(i,n):"macro"in n?(0,bc.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,bc.funcKeywordCode)(i,n)}var Rq=/^\/(?:[^~]|~0|~1)*$/,Cq=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ZS(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,s;if(e==="")return oe.default.rootData;if(e[0]==="/"){if(!Rq.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,s=oe.default.rootData}else{let f=Cq.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(l("property/index",a));return r[t-a]}if(a>t)throw new Error(l("data",a));if(s=n[t-a],!i)return s}let o=s,c=i.split("/");for(let f of c)f&&(s=(0,te._)`${s}${(0,te.getProperty)((0,Wr.unescapeJsonPointer)(f))}`,o=(0,te._)`${o} && ${s}`);return o;function l(f,a){return`Cannot access ${f} ${a} levels up, current level is ${t}`}}Ai.getData=ZS});var Cd=_(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var fg=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};pg.default=fg});var Cc=_(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var mg=vc(),hg=class extends Error{constructor(t,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,mg.resolveUrl)(t,n,r),this.missingSchema=(0,mg.normalizeId)((0,mg.getFullPath)(t,this.missingRef))}};gg.default=hg});var Ed=_(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.resolveSchema=Nn.getCompilingSchema=Nn.resolveRef=Nn.compileSchema=Nn.SchemaEnv=void 0;var Xn=ge(),Sq=Cd(),ys=Lr(),Qn=vc(),eE=Se(),Eq=Rc(),Oo=class{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Qn.normalizeId)(r?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r?.$async,this.refs={}}};Nn.SchemaEnv=Oo;function yg(e){let t=tE.call(this,e);if(t)return t;let n=(0,Qn.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new Xn.CodeGen(this.scope,{es5:r,lines:i,ownProperties:s}),c;e.$async&&(c=o.scopeValue("Error",{ref:Sq.default,code:(0,Xn._)`require("ajv/dist/runtime/validation_error").default`}));let l=o.scopeName("validate");e.validateName=l;let f={gen:o,allErrors:this.opts.allErrors,data:ys.default.data,parentData:ys.default.parentData,parentDataProperty:ys.default.parentDataProperty,dataNames:[ys.default.data],dataPathArr:[Xn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Xn.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Xn.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Xn._)`""`,opts:this.opts,self:this},a;try{this._compilations.add(e),(0,Eq.validateFunctionCode)(f),o.optimize(this.opts.code.optimize);let d=o.toString();a=`${o.scopeRefs(ys.default.scope)}return ${d}`,this.opts.code.process&&(a=this.opts.code.process(a,e));let u=new Function(`${ys.default.self}`,`${ys.default.scope}`,a)(this,this.scope.get());if(this.scope.value(l,{ref:u}),u.errors=null,u.schema=e.schema,u.schemaEnv=e,e.$async&&(u.$async=!0),this.opts.code.source===!0&&(u.source={validateName:l,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=f;u.evaluated={props:m instanceof Xn.Name?void 0:m,items:h instanceof Xn.Name?void 0:h,dynamicProps:m instanceof Xn.Name,dynamicItems:h instanceof Xn.Name},u.source&&(u.source.evaluated=(0,Xn.stringify)(u.evaluated))}return e.validate=u,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)}}Nn.compileSchema=yg;function Aq(e,t,n){var r;n=(0,Qn.resolveUrl)(this.opts.uriResolver,t,n);let i=e.refs[n];if(i)return i;let s=_q.call(this,e,n);if(s===void 0){let o=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:c}=this.opts;o&&(s=new Oo({schema:o,schemaId:c,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=xq.call(this,s)}Nn.resolveRef=Aq;function xq(e){return(0,Qn.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:yg.call(this,e)}function tE(e){for(let t of this._compilations)if(Iq(t,e))return t}Nn.getCompilingSchema=tE;function Iq(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function _q(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Sd.call(this,e,t)}function Sd(e,t){let n=this.opts.uriResolver.parse(t),r=(0,Qn._getFullPath)(this.opts.uriResolver,n),i=(0,Qn.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===i)return wg.call(this,n,e);let s=(0,Qn.normalizeId)(r),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let c=Sd.call(this,e,o);return typeof c?.schema!="object"?void 0:wg.call(this,n,c)}if(typeof o?.schema=="object"){if(o.validate||yg.call(this,o),s===(0,Qn.normalizeId)(t)){let{schema:c}=o,{schemaId:l}=this.opts,f=c[l];return f&&(i=(0,Qn.resolveUrl)(this.opts.uriResolver,i,f)),new Oo({schema:c,schemaId:l,root:e,baseId:i})}return wg.call(this,n,o)}}Nn.resolveSchema=Sd;var Pq=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function wg(e,{baseId:t,schema:n,root:r}){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 n=="boolean")return;let l=n[(0,eE.unescapeFragment)(c)];if(l===void 0)return;n=l;let f=typeof n=="object"&&n[this.opts.schemaId];!Pq.has(c)&&f&&(t=(0,Qn.resolveUrl)(this.opts.uriResolver,t,f))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,eE.schemaHasRulesButRef)(n,this.RULES)){let c=(0,Qn.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Sd.call(this,r,c)}let{schemaId:o}=this.opts;if(s=s||new Oo({schema:n,schemaId:o,root:r,baseId:t}),s.schema!==s.root.schema)return s}});var nE=_((X6,Oq)=>{Oq.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 Sg=_((Q6,uE)=>{"use strict";var Tq=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kg=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),Nq=RegExp.prototype.test.bind(/^\d*$/u),vs=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),bg=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),iE=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Rg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),$q=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),dn=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)dn[t]="%"+e[t>>4]+e[t&15]}function Wt(e){return e<2048?dn[192|e>>6]+dn[128|e&63]:e<65536?dn[224|e>>12]+dn[128|e>>6&63]+dn[128|e&63]:dn[240|e>>18]+dn[128|e>>12&63]+dn[128|e>>6&63]+dn[128|e&63]}function jq(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}var Dq=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),qq=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),Lq=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),Wq=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Mq(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!Lq(e[t])){if(e[t]==="%"&&t+2<e.length&&vs(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function rE(e){let t=-1,n=0,r=-1,i=0;for(let c=0;c<e.length;c++)e[c]==="0"?(r===-1&&(r=c),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(":");let s=e.slice(0,t).join(":"),o=e.slice(t+n).join(":");return s+"::"+o}function Fq(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let n=t===-1?e.split(":"):e.slice(0,t).split(":"),r=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(n.length===1&&n[0]===""&&(n.length=0),r.length===1&&r[0]===""&&(r.length=0));let i=n.concat(r),s=0;for(let c=0;c<i.length;c++){let l=i[c];if(l==="")return;if(l.indexOf(".")!==-1){if(c!==i.length-1||t!==-1&&r.length===0||!kg(l))return;s+=2;continue}if(!Dq(l))return;i[c]=parseInt(l,16).toString(16),s++}if(t===-1)return s!==8?void 0:rE(i);if(s>=8)return;let o=i.slice(0,n.length);for(let c=s;c<8;c++)o.push("0");for(let c=n.length;c<i.length;c++)o.push(i[c]);return rE(o)}function vg(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 r=t?e.slice(1,-1):e;if(t&&qq(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:!1,isIPVFuture:!0};if(Hq(r,":")<2)return{host:e,isIPV6:!1,error:t};let i="",s=r.indexOf("%");if(s!==-1){let c=r.slice(s,s+3).toLowerCase()==="%25"?3:1;if(i=r.slice(s+c),!Mq(i))return{host:e,isIPV6:!1,error:!0};r=r.slice(0,s)}let o=Fq(r);return o===void 0?{host:e,isIPV6:!1,error:!0}:{host:o+(i?"%"+i:""),escapedHost:o+(i?"%25"+i:""),isIPV6:!0}}function Hq(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function sE(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.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]==="/")){n.push("/");break}}else if(i===3&&t==="/.."){n.length!==0&&n.pop(),n.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),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}function Bq(e){if(e===""||e[0]==="/")return sE(e);let t=e.split("/"),n=t.length-1,r=[],i=!1;for(let s=0;s<=n;s++){let o=t[s];o==="."||o===".."?(o===".."&&(r.length!==0&&r[r.length-1]!==".."?r.pop():r.push("..")),i=s===n):r.push(o)}return i&&r[r.length-1]!==".."&&r.push(""),(r.length===0||r[0]===""||r[0].includes(":"))&&r.unshift("."),r.join("/")}var Vq={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Uq=/[@/?#:]/g,Kq=/[@/?#]/g;function oE(e,t){let n=t?Kq:Uq;return n.lastIndex=0,e.replace(n,r=>Vq[r])}function aE(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let i=e.slice(r+1,r+3);if(vs(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));t&&bg(o)?n+=o:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function zq(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(vs(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&bg(o)?t+=o:t+="%"+s,n+=2;continue}}if(iE(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=lE(i)?r:dn[i];else if(i<55296||i>57343)t+=Wt(i);else if(i<=56319&&n+1<e.length){let s=e.charCodeAt(n+1);s>=56320&&s<=57343?(t+=Wt(65536+(i-55296<<10)+(s-56320)),n++):t+=Wt(65533)}else t+=Wt(65533)}}return t}function Jq(e,t=!1){let n="",r=t&&e[0]!=="/";for(let i=0;i<e.length;i++){let s=e[i];if(s==="%"&&i+2<e.length){let o=e.slice(i+1,i+3);if(vs(o)){n+="%"+o.toUpperCase(),i+=2;continue}}if(s==="/"&&(r=!1),iE(s)&&(s!==":"||!r))n+=s;else{let o=e.charCodeAt(i);if(o<128)n+=dn[o];else if(o<55296||o>57343)n+=Wt(o);else if(o<=56319&&i+1<e.length){let c=e.charCodeAt(i+1);c>=56320&&c<=57343?(n+=Wt(65536+(o-55296<<10)+(c-56320)),i++):n+=Wt(65533)}else n+=Wt(65533)}}return n}function Cg(e,t){let n="";for(let r=0;r<e.length;r++){let i=e[r];if(i==="%"&&r+2<e.length){let s=e.slice(r+1,r+3);if(vs(s)){n+="%"+s.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let s=e.charCodeAt(r);if(s<128)n+=dn[s];else if(s<55296||s>57343)n+=Wt(s);else if(s<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(n+=Wt(65536+(s-55296<<10)+(o-56320)),r++):n+=Wt(65533)}else n+=Wt(65533)}}return n}function cE(e){return Cg(e,$q)}function Gq(e){return Cg(e,Rg)}function Yq(e){return Cg(e,Rg)}function lE(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 Xq(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(vs(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));bg(o)?t+=o:t+="%"+s,n+=2;continue}}if(Rg(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=lE(i)?r:dn[i];else if(i<55296||i>57343)t+=Wt(i);else if(i<=56319&&n+1<e.length){let s=e.charCodeAt(n+1);s>=56320&&s<=57343?(t+=Wt(65536+(i-55296<<10)+(s-56320)),n++):t+=Wt(65533)}else t+=Wt(65533)}}return t}function Qq(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let r=e.slice(n+1,n+3);if(vs(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function Zq(e){let t=[];if(e.userinfo!==void 0&&(t.push(cE(e.userinfo)),t.push("@")),e.host!==void 0){let n=e.host;if(!kg(n)){let r=vg(n);r.isIPV6!==!0&&r.isIPVFuture!==!0&&(n=aE(n,!0),r=vg(n)),r.isIPV6===!0||r.isIPVFuture===!0?n=`[${r.escapedHost}]`:n=oE(n,!1)}t.push(n)}if(typeof e.port=="number"||typeof e.port=="string"){let n=String(e.port);if(!Nq(n))throw new TypeError("URI port is malformed.");t.push(":"),t.push(n)}return t.length?t.join(""):void 0}uE.exports={nonSimpleDomain:Wq,recomposeAuthority:Zq,reescapeHostDelimiters:oE,normalizePercentEncoding:aE,normalizePathEncoding:zq,serializePathEncoding:Jq,normalizeQueryFragmentEncoding:Xq,encodeUserinfo:cE,encodeQuery:Gq,encodeFragment:Yq,escapePreservingEscapes:Qq,removeDotSegments:sE,removeDotSegmentsRelative:Bq,isIPv4:kg,isUUID:Tq,normalizeIPv6:vg,stringArrayToHexStripped:jq}});var hE=_((Z6,mE)=>{"use strict";var{isUUID:eL}=Sg(),tL=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,nL=["http","https","ws","wss","urn","urn:uuid"];function rL(e){return nL.indexOf(e)!==-1}function Eg(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 dE(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function fE(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 iL(e){return e.secure=Eg(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function sL(e){if((e.port===(Eg(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("?"),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!=="/"?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function oL(e,t){if(!e.path)return e.error="URN can not be parsed",e;let n=e.path.match(tL);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];let i=`${r}:${t.nid||e.nid}`,s=Ag(i);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function aL(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),i=`${n}:${t.nid||r}`,s=Ag(i);s&&(e=s.serialize(e,t));let o=e,c=e.nss;return o.path=`${r||t.nid}:${c}`,t.skipEscape=!0,o}function cL(e,t){let n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!eL(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function lL(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var pE={scheme:"http",domainHost:!0,parse:dE,serialize:fE},uL={scheme:"https",domainHost:pE.domainHost,parse:dE,serialize:fE},Ad={scheme:"ws",domainHost:!0,parse:iL,serialize:sL},dL={scheme:"wss",domainHost:Ad.domainHost,parse:Ad.parse,serialize:Ad.serialize},fL={scheme:"urn",parse:oL,serialize:aL,skipNormalize:!0},pL={scheme:"urn:uuid",parse:cL,serialize:lL,skipNormalize:!0},xd={http:pE,https:uL,ws:Ad,wss:dL,urn:fL,"urn:uuid":pL};Object.setPrototypeOf(xd,null);function Ag(e){return e&&(xd[e]||xd[e.toLowerCase()])||void 0}mE.exports={wsIsSecure:Eg,SCHEMES:xd,isValidSchemeName:rL,getSchemeHandler:Ag}});var PE=_((e9,Td)=>{"use strict";var{normalizeIPv6:kE,removeDotSegments:Ec,removeDotSegmentsRelative:bE,recomposeAuthority:mL,normalizePercentEncoding:xg,normalizePathEncoding:hL,serializePathEncoding:gE,normalizeQueryFragmentEncoding:wE,encodeQuery:gL,encodeFragment:wL,reescapeHostDelimiters:yL,isIPv4:RE,nonSimpleDomain:vL}=Sg(),{SCHEMES:CE,getSchemeHandler:Ig}=hE(),SE=/^[A-Za-z][A-Za-z0-9+.-]*$/u,EE="URI scheme is malformed.",Id="URI host is malformed.",kL=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function yE(e){let t=String(e);if(!SE.test(t))throw new TypeError(EE);return t}function bL(e,t){return typeof e=="string"?e=PL(e,t):typeof e=="object"&&(e=Pd(ks(e,t),t)),e}function RL(e,t,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:f}=_d(e,r),{parsed:a,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:u,malformedHost:m,malformedScheme:h}=_d(t,r);if(s||d||o||p||c||u||l||m||f||h)throw new Error(i.error||a.error||"URI is malformed.");let g=AE(i,a,r,!0),w=Ig(n&&n.scheme||g.scheme),k=g.host,y=k!==void 0&&k!==""&&(RE(k)||kE(k).isIPV6);if(IE(g,n||{},w,y))throw new Error(Id);xE(g,n||{},w,y);let R=k&&k.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(k);if(g.error&&!R)throw new Error(g.error);return r.skipEscape=!0,ks(g,r)}function AE(e,t,n,r){let i={};if(r||(e=Pd(ks(e,n),n),t=Pd(ks(t,n),n)),n=n||{},!n.tolerant&&t.scheme)i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=Ec(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=Ec(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=Ec(t.path);else{let s=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;s&&!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&&!s&&i.path[0]!=="/"?bE(i.path):Ec(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 CL(e,t,n){let r=vE(e,n),i=vE(t,n);return r!==void 0&&i!==void 0&&r===i}function ks(e,t){let n={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:""},r=Object.assign({},t),i=[];n.scheme&&(n.scheme=yE(n.scheme));let s=Ig(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r);let o=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,c=(n.scheme===void 0||r.reference==="suffix")&&!o,l=!r.skipEscape&&c;n.path!==void 0&&(r.skipEscape?n.path=xg(n.path):n.path=gE(n.path,l)),r.reference!=="suffix"&&n.scheme&&(n.scheme=yE(n.scheme),i.push(n.scheme,":"));let f=mL(n);if(f!==void 0&&(r.reference!=="suffix"&&i.push("//"),i.push(f),n.path&&n.path[0]!=="/"&&i.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=c&&a[0]!=="/"?bE(a):Ec(a)),c&&(a=gE(a,!0)),f===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return n.query!==void 0&&i.push("?",gL(n.query)),n.fragment!==void 0&&i.push("#",wL(n.fragment)),i.join("")}var SL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,EL=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,AL=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function xL(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 Sc(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 Od(e){return e[0]==="["&&e[e.length-1]==="]"}function IL(e){let t=e[4];return Sc(e[3])||t!==void 0&&!Od(t)&&Sc(t)||Sc(e[6])||Sc(e[7])||Sc(e[8])}function xE(e,t,n,r){if(IE(e,t,n,r))return e.error=e.error||Id,!0;if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!Od(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&vL(e.host)){let i;try{i=new URL("http://"+e.host)}catch(s){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!_L(i))return e.error=e.error||Id,!0;e.host=i.hostname}return!1}function IE(e,t,n,r){return!!(e.host&&r===!1&&!Od(e.host)&&(t.domainHost||n&&n.domainHost)&&kL.test(e.host))}function _L(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function _d(e,t){let n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,s=!1,o=!1,c=!1,l=!1,f=!1,a=!1;n.reference==="suffix"&&(n.scheme?e=n.scheme+":"+e:e="//"+e);let d=e.match(EL);d!==null&&d[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=!0);let p=e.match(AL);if(p!==null){let m=p[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",i=!0):m.length!==h.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",i=!0))}let u=e.match(SL);if(u){r.scheme=u[1],r.userinfo=u[3],r.host=u[4],r.port=parseInt(u[5],10),r.path=u[6]||"",r.query=u[7],r.fragment=u[8],r.scheme!==void 0&&(SE.test(r.scheme)?r.scheme=r.scheme.toLowerCase():(r.error=r.error||EE,f=!0)),s=IL(u),s&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=u[5]);let m=xL(r,u);if(m!==void 0&&(r.error=r.error||m,i=!0),r.host)if(RE(r.host)===!1){let w=Od(r.host),k=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,y=kE(r.host);a=y.isIPV6||y.isIPVFuture===!0,l=k&&(!w||y.error===!0),r.host=a?y.host:y.host.toLowerCase(),l&&(r.error=r.error||Id,i=!0)}else a=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let h=Ig(n.scheme||r.scheme);if(l||(c=xE(r,n,h,a)),e.indexOf("%")!==-1&&r.host!==void 0&&!l){let g=a?r.host:xg(r.host,!0);a||(g=xg(g.toLowerCase())),r.host=a||n.scheme!=="null"?yL(g,a):g}(!h||h&&!h.skipNormalize)&&(r.path&&(r.path=hL(r.path)),r.query&&(r.query=wE(r.query)),r.fragment&&(r.fragment=wE(r.fragment))),h&&h.parse&&(h.parse(r,n),h===CE.urn&&r.nid===void 0&&(o=!0))}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:c,malformedScheme:f}}function Pd(e,t){return _d(e,t).parsed}function PL(e,t){return _E(e,t).normalized}function _E(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:c}=_d(e,t);return{normalized:r||i||s||o||c?e:ks(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:c}}function vE(e,t){if(typeof e!="string"&&typeof e!="object")return;let n;try{n=typeof e=="string"?e:ks(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:c,malformedScheme:l}=_E(n,t);return i||s||o||c||l?void 0:r}var _g={SCHEMES:CE,normalize:bL,resolve:RL,resolveComponent:AE,equal:CL,serialize:ks,parse:Pd};Td.exports=_g;Td.exports.default=_g;Td.exports.fastUri=_g});var TE=_(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var OE=PE();OE.code='require("ajv/dist/runtime/uri").default';Pg.default=OE});var ME=_(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.CodeGen=At.Name=At.nil=At.stringify=At.str=At._=At.KeywordCxt=void 0;var OL=Rc();Object.defineProperty(At,"KeywordCxt",{enumerable:!0,get:function(){return OL.KeywordCxt}});var To=ge();Object.defineProperty(At,"_",{enumerable:!0,get:function(){return To._}});Object.defineProperty(At,"str",{enumerable:!0,get:function(){return To.str}});Object.defineProperty(At,"stringify",{enumerable:!0,get:function(){return To.stringify}});Object.defineProperty(At,"nil",{enumerable:!0,get:function(){return To.nil}});Object.defineProperty(At,"Name",{enumerable:!0,get:function(){return To.Name}});Object.defineProperty(At,"CodeGen",{enumerable:!0,get:function(){return To.CodeGen}});var TL=Cd(),qE=Cc(),NL=Zh(),Ac=Ed(),$L=ge(),xc=vc(),Nd=yc(),Tg=Se(),NE=nE(),jL=TE(),LE=(e,t)=>new RegExp(e,t);LE.code="new RegExp";var DL=["removeAdditional","useDefaults","coerceTypes"],qL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),LL={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."},WL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$E=200;function ML(e){var t,n,r,i,s,o,c,l,f,a,d,p,u,m,h,g,w,k,y,R,C,A,q,D,K;let L=e.strict,Z=(t=e.code)===null||t===void 0?void 0:t.optimize,Y=Z===!0||Z===void 0?1:Z||0,fe=(r=(n=e.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:LE,z=(i=e.uriResolver)!==null&&i!==void 0?i:jL.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:L)!==null&&o!==void 0?o:!0,strictNumbers:(l=(c=e.strictNumbers)!==null&&c!==void 0?c:L)!==null&&l!==void 0?l:!0,strictTypes:(a=(f=e.strictTypes)!==null&&f!==void 0?f:L)!==null&&a!==void 0?a:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:L)!==null&&p!==void 0?p:"log",strictRequired:(m=(u=e.strictRequired)!==null&&u!==void 0?u:L)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Y,regExp:fe}:{optimize:Y,regExp:fe},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:$E,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:$E,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(k=e.messages)!==null&&k!==void 0?k:!0,inlineRefs:(y=e.inlineRefs)!==null&&y!==void 0?y:!0,schemaId:(R=e.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(C=e.addUsedSchema)!==null&&C!==void 0?C:!0,validateSchema:(A=e.validateSchema)!==null&&A!==void 0?A:!0,validateFormats:(q=e.validateFormats)!==null&&q!==void 0?q:!0,unicodeRegExp:(D=e.unicodeRegExp)!==null&&D!==void 0?D:!0,int32range:(K=e.int32range)!==null&&K!==void 0?K:!0,uriResolver:z}}var Ic=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,...ML(t)};let{es5:n,lines:r}=this.opts.code;this.scope=new $L.ValueScope({scope:{},prefixes:qL,es5:n,lines:r}),this.logger=KL(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,NL.getRules)(),jE.call(this,LL,t,"NOT SUPPORTED"),jE.call(this,WL,t,"DEPRECATED","warn"),this._metaOpts=VL.call(this),t.formats&&HL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&BL.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),FL.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:n,schemaId:r}=this.opts,i=NE;r==="id"&&(i={...NE},i.id=i.$id,delete i.$id),n&&t&&this.addMetaSchema(i,i[r],!1)}defaultMeta(){let{meta:t,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[n]||t:void 0}validate(t,n){let r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error(`no schema with key or ref "${t}"`)}else r=this.compile(t);let i=r(n);return"$async"in r||(this.errors=r.errors),i}compile(t,n){let r=this._addSchema(t,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(t,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,t,n);async function i(a,d){await s.call(this,a.$schema);let p=this._addSchema(a,d);return p.validate||o.call(this,p)}async function s(a){a&&!this.getSchema(a)&&await i.call(this,{$ref:a},!0)}async function o(a){try{return this._compileSchemaEnv(a)}catch(d){if(!(d instanceof qE.default))throw d;return c.call(this,d),await l.call(this,d.missingSchema),o.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 l(a){let d=await f.call(this,a);this.refs[a]||await s.call(this,d.$schema),this.refs[a]||this.addSchema(d,a,n)}async function f(a){let d=this._loading[a];if(d)return d;try{return await(this._loading[a]=r(a))}finally{delete this._loading[a]}}}addSchema(t,n,r,i=this.opts.validateSchema){if(Array.isArray(t)){for(let o of t)this.addSchema(o,void 0,r,i);return this}let s;if(typeof t=="object"){let{schemaId:o}=this.opts;if(s=t[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return n=(0,xc.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(t,r,n,i,!0),this}addMetaSchema(t,n,r=this.opts.validateSchema){return this.addSchema(t,n,!0,r),this}validateSchema(t,n){if(typeof t=="boolean")return!0;let r;if(r=t.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(r,t);if(!i&&n){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(t){let n;for(;typeof(n=DE.call(this,t))=="string";)t=n;if(n===void 0){let{schemaId:r}=this.opts,i=new Ac.SchemaEnv({schema:{},schemaId:r});if(n=Ac.resolveSchema.call(this,i,t),!n)return;this.refs[t]=n}return n.validate||this._compileSchemaEnv(n)}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 n=DE.call(this,t);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let n=t;this._cache.delete(n);let r=t[this.opts.schemaId];return r&&(r=(0,xc.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let n of t)this.addKeyword(n);return this}addKeyword(t,n){let r;if(typeof t=="string")r=t,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof t=="object"&&n===void 0){if(n=t,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(JL.call(this,r,n),!n)return(0,Tg.eachItem)(r,s=>Og.call(this,s)),this;YL.call(this,n);let i={...n,type:(0,Nd.getJSONTypes)(n.type),schemaType:(0,Nd.getJSONTypes)(n.schemaType)};return(0,Tg.eachItem)(r,i.type.length===0?s=>Og.call(this,s,i):s=>i.type.forEach(o=>Og.call(this,s,i,o))),this}getKeyword(t){let n=this.RULES.all[t];return typeof n=="object"?n.definition:!!n}removeKeyword(t){let{RULES:n}=this;delete n.keywords[t],delete n.all[t];for(let r of n.rules){let i=r.rules.findIndex(s=>s.keyword===t);i>=0&&r.rules.splice(i,1)}return this}addFormat(t,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[t]=n,this}errorsText(t=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${r}${i.instancePath} ${i.message}`).reduce((i,s)=>i+n+s)}$dataMetaSchema(t,n){let r=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of n){let s=i.split("/").slice(1),o=t;for(let c of s)o=o[c];for(let c in r){let l=r[c];if(typeof l!="object")continue;let{$data:f}=l.definition,a=o[c];f&&a&&(o[c]=WE(a))}}return t}_removeAllSchemas(t,n){for(let r in t){let i=t[r];(!n||n.test(r))&&(typeof i=="string"?delete t[r]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[r]))}}_addSchema(t,n,r,i=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:c}=this.opts;if(typeof t=="object")o=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 l=this._cache.get(t);if(l!==void 0)return l;r=(0,xc.normalizeId)(o||r);let f=xc.getSchemaRefs.call(this,t,r);return l=new Ac.SchemaEnv({schema:t,schemaId:c,meta:n,baseId:r,localRefs:f}),this._cache.set(l.schema,l),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=l),i&&this.validateSchema(t,!0),l}_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):Ac.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let n=this.opts;this.opts=this._metaOpts;try{Ac.compileSchema.call(this,t)}finally{this.opts=n}}};Ic.ValidationError=TL.default;Ic.MissingRefError=qE.default;At.default=Ic;function jE(e,t,n,r="error"){for(let i in e){let s=i;s in t&&this.logger[r](`${n}: option ${i}. ${e[s]}`)}}function DE(e){return e=(0,xc.normalizeId)(e),this.schemas[e]||this.refs[e]}function FL(){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 HL(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function BL(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 n=e[t];n.keyword||(n.keyword=t),this.addKeyword(n)}}function VL(){let e={...this.opts};for(let t of DL)delete e[t];return e}var UL={log(){},warn(){},error(){}};function KL(e){if(e===!1)return UL;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 zL=/^[a-z_$][a-z0-9_$:-]*$/i;function JL(e,t){let{RULES:n}=this;if((0,Tg.eachItem)(e,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!zL.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Og(e,t,n){var r;let i=t?.post;if(n&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:l})=>l===n);if(o||(o={type:n,rules:[]},s.rules.push(o)),s.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,Nd.getJSONTypes)(t.type),schemaType:(0,Nd.getJSONTypes)(t.schemaType)}};t.before?GL.call(this,o,c,t.before):o.rules.push(c),s.all[e]=c,(r=t.implements)===null||r===void 0||r.forEach(l=>this.addKeyword(l))}function GL(e,t,n){let r=e.rules.findIndex(i=>i.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function YL(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=WE(t)),e.validateSchema=this.compile(t,!0))}var XL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function WE(e){return{anyOf:[e,XL]}}});var FE=_(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var QL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ng.default=QL});var UE=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.callRef=bs.getValidate=void 0;var ZL=Cc(),HE=Tn(),fn=ge(),No=Lr(),BE=Ed(),$d=Se(),eW={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:n,it:r}=e,{baseId:i,schemaEnv:s,validateName:o,opts:c,self:l}=r,{root:f}=s;if((n==="#"||n==="#/")&&i===f.baseId)return d();let a=BE.resolveRef.call(l,f,i,n);if(a===void 0)throw new ZL.default(r.opts.uriResolver,i,n);if(a instanceof BE.SchemaEnv)return p(a);return u(a);function d(){if(s===f)return jd(e,o,s,s.$async);let m=t.scopeValue("root",{ref:f});return jd(e,(0,fn._)`${m}.validate`,f,f.$async)}function p(m){let h=VE(e,m);jd(e,h,m,m.$async)}function u(m){let h=t.scopeValue("schema",c.code.source===!0?{ref:m,code:(0,fn.stringify)(m)}:{ref:m}),g=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:fn.nil,topSchemaRef:h,errSchemaPath:n},g);e.mergeEvaluated(w),e.ok(g)}}};function VE(e,t){let{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,fn._)`${n.scopeValue("wrapper",{ref:t})}.validate`}bs.getValidate=VE;function jd(e,t,n,r){let{gen:i,it:s}=e,{allErrors:o,schemaEnv:c,opts:l}=s,f=l.passContext?No.default.this:fn.nil;r?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,fn._)`await ${(0,HE.callValidateCode)(e,t,f)}`),u(t),o||i.assign(m,!0)},h=>{i.if((0,fn._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),p(h),o||i.assign(m,!1)}),e.ok(m)}function d(){e.result((0,HE.callValidateCode)(e,t,f),()=>u(t),()=>p(t))}function p(m){let h=(0,fn._)`${m}.errors`;i.assign(No.default.vErrors,(0,fn._)`${No.default.vErrors} === null ? ${h} : ${No.default.vErrors}.concat(${h})`),i.assign(No.default.errors,(0,fn._)`${No.default.vErrors}.length`)}function u(m){var h;if(!s.opts.unevaluated)return;let g=(h=n?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=$d.mergeEvaluated.props(i,g.props,s.props));else{let w=i.var("props",(0,fn._)`${m}.evaluated.props`);s.props=$d.mergeEvaluated.props(i,w,s.props,fn.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=$d.mergeEvaluated.items(i,g.items,s.items));else{let w=i.var("items",(0,fn._)`${m}.evaluated.items`);s.items=$d.mergeEvaluated.items(i,w,s.items,fn.Name)}}}bs.callRef=jd;bs.default=eW});var KE=_($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var tW=FE(),nW=UE(),rW=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",tW.default,nW.default];$g.default=rW});var zE=_(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var Dd=ge(),xi=Dd.operators,qd={maximum:{okStr:"<=",ok:xi.LTE,fail:xi.GT},minimum:{okStr:">=",ok:xi.GTE,fail:xi.LT},exclusiveMaximum:{okStr:"<",ok:xi.LT,fail:xi.GTE},exclusiveMinimum:{okStr:">",ok:xi.GT,fail:xi.LTE}},iW={message:({keyword:e,schemaCode:t})=>(0,Dd.str)`must be ${qd[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Dd._)`{comparison: ${qd[e].okStr}, limit: ${t}}`},sW={keyword:Object.keys(qd),type:"number",schemaType:"number",$data:!0,error:iW,code(e){let{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,Dd._)`${n} ${qd[t].fail} ${r} || isNaN(${n})`)}};jg.default=sW});var JE=_(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var _c=ge(),oW={message:({schemaCode:e})=>(0,_c.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,_c._)`{multipleOf: ${e}}`},aW={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:oW,code(e){let{gen:t,data:n,schemaCode:r,it:i}=e,s=i.opts.multipleOfPrecision,o=t.let("res"),c=s?(0,_c._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,_c._)`${o} !== parseInt(${o})`;e.fail$data((0,_c._)`(${r} === 0 || (${o} = ${n}/${r}, ${c}))`)}};Dg.default=aW});var Lg=_(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});function GE(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)===56320&&r++);return n}qg.default=GE;GE.code='require("ajv/dist/runtime/ucs2length").default'});var YE=_(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});var Rs=ge(),cW=Se(),lW=Lg(),uW={message({keyword:e,schemaCode:t}){let n=e==="maxLength"?"more":"fewer";return(0,Rs.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,Rs._)`{limit: ${e}}`},dW={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:uW,code(e){let{keyword:t,data:n,schemaCode:r,it:i}=e,s=t==="maxLength"?Rs.operators.GT:Rs.operators.LT,o=i.opts.unicode===!1?(0,Rs._)`${n}.length`:(0,Rs._)`${(0,cW.useFunc)(e.gen,lW.default)}(${n})`;e.fail$data((0,Rs._)`${o} ${s} ${r}`)}};Wg.default=dW});var XE=_(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var fW=Tn(),pW=Se(),$o=ge(),mW={message:({schemaCode:e})=>(0,$o.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,$o._)`{pattern: ${e}}`},hW={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:mW,code(e){let{gen:t,data:n,$data:r,schema:i,schemaCode:s,it:o}=e,c=o.opts.unicodeRegExp?"u":"";if(r){let{regExp:l}=o.opts.code,f=l.code==="new RegExp"?(0,$o._)`new RegExp`:(0,pW.useFunc)(t,l),a=t.let("valid");t.try(()=>t.assign(a,(0,$o._)`${f}(${s}, ${c}).test(${n})`),()=>t.assign(a,!1)),e.fail$data((0,$o._)`!${a}`)}else{let l=(0,fW.usePattern)(e,i);e.fail$data((0,$o._)`!${l}.test(${n})`)}}};Mg.default=hW});var QE=_(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var Pc=ge(),gW={message({keyword:e,schemaCode:t}){let n=e==="maxProperties"?"more":"fewer";return(0,Pc.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,Pc._)`{limit: ${e}}`},wW={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:gW,code(e){let{keyword:t,data:n,schemaCode:r}=e,i=t==="maxProperties"?Pc.operators.GT:Pc.operators.LT;e.fail$data((0,Pc._)`Object.keys(${n}).length ${i} ${r}`)}};Fg.default=wW});var ZE=_(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var Oc=Tn(),Tc=ge(),yW=Se(),vW={message:({params:{missingProperty:e}})=>(0,Tc.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Tc._)`{missingProperty: ${e}}`},kW={keyword:"required",type:"object",schemaType:"array",$data:!0,error:vW,code(e){let{gen:t,schema:n,schemaCode:r,data:i,$data:s,it:o}=e,{opts:c}=o;if(!s&&n.length===0)return;let l=n.length>=c.loopRequired;if(o.allErrors?f():a(),c.strictRequired){let u=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of n)if(u?.[h]===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,w=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,yW.checkStrictMode)(o,w,o.opts.strictRequired)}}function f(){if(l||s)e.block$data(Tc.nil,d);else for(let u of n)(0,Oc.checkReportMissingProp)(e,u)}function a(){let u=t.let("missing");if(l||s){let m=t.let("valid",!0);e.block$data(m,()=>p(u,m)),e.ok(m)}else t.if((0,Oc.checkMissingProp)(e,n,u)),(0,Oc.reportMissingProp)(e,u),t.else()}function d(){t.forOf("prop",r,u=>{e.setParams({missingProperty:u}),t.if((0,Oc.noPropertyInData)(t,i,u,c.ownProperties),()=>e.error())})}function p(u,m){e.setParams({missingProperty:u}),t.forOf(u,r,()=>{t.assign(m,(0,Oc.propertyInData)(t,i,u,c.ownProperties)),t.if((0,Tc.not)(m),()=>{e.error(),t.break()})},Tc.nil)}}};Hg.default=kW});var eA=_(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var Nc=ge(),bW={message({keyword:e,schemaCode:t}){let n=e==="maxItems"?"more":"fewer";return(0,Nc.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,Nc._)`{limit: ${e}}`},RW={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:bW,code(e){let{keyword:t,data:n,schemaCode:r}=e,i=t==="maxItems"?Nc.operators.GT:Nc.operators.LT;e.fail$data((0,Nc._)`${n}.length ${i} ${r}`)}};Bg.default=RW});var Ld=_(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var tA=ag();tA.code='require("ajv/dist/runtime/equal").default';Vg.default=tA});var nA=_(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var Ug=yc(),xt=ge(),CW=Se(),SW=Ld(),EW={message:({params:{i:e,j:t}})=>(0,xt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,xt._)`{i: ${e}, j: ${t}}`},AW={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:EW,code(e){let{gen:t,data:n,$data:r,schema:i,parentSchema:s,schemaCode:o,it:c}=e;if(!r&&!i)return;let l=t.let("valid"),f=s.items?(0,Ug.getSchemaTypes)(s.items):[];e.block$data(l,a,(0,xt._)`${o} === false`),e.ok(l);function a(){let m=t.let("i",(0,xt._)`${n}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(l,!0),t.if((0,xt._)`${m} > 1`,()=>(d()?p:u)(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,Ug.checkDataTypes)(f,g,c.opts.strictNumbers,Ug.DataType.Wrong),k=t.const("indices",(0,xt._)`{}`);t.for((0,xt._)`;${m}--;`,()=>{t.let(g,(0,xt._)`${n}[${m}]`),t.if(w,(0,xt._)`continue`),f.length>1&&t.if((0,xt._)`typeof ${g} == "string"`,(0,xt._)`${g} += "_"`),t.if((0,xt._)`typeof ${k}[${g}] == "number"`,()=>{t.assign(h,(0,xt._)`${k}[${g}]`),e.error(),t.assign(l,!1).break()}).code((0,xt._)`${k}[${g}] = ${m}`)})}function u(m,h){let g=(0,CW.useFunc)(t,SW.default),w=t.name("outer");t.label(w).for((0,xt._)`;${m}--;`,()=>t.for((0,xt._)`${h} = ${m}; ${h}--;`,()=>t.if((0,xt._)`${g}(${n}[${m}], ${n}[${h}])`,()=>{e.error(),t.assign(l,!1).break(w)})))}}};Kg.default=AW});var rA=_(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var zg=ge(),xW=Se(),IW=Ld(),_W={message:"must be equal to constant",params:({schemaCode:e})=>(0,zg._)`{allowedValue: ${e}}`},PW={keyword:"const",$data:!0,error:_W,code(e){let{gen:t,data:n,$data:r,schemaCode:i,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,zg._)`!${(0,xW.useFunc)(t,IW.default)}(${n}, ${i})`):e.fail((0,zg._)`${s} !== ${n}`)}};Jg.default=PW});var iA=_(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});var $c=ge(),OW=Se(),TW=Ld(),NW={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,$c._)`{allowedValues: ${e}}`},$W={keyword:"enum",schemaType:"array",$data:!0,error:NW,code(e){let{gen:t,data:n,$data:r,schema:i,schemaCode:s,it:o}=e;if(!r&&i.length===0)throw new Error("enum must have non-empty array");let c=i.length>=o.opts.loopEnum,l,f=()=>l??(l=(0,OW.useFunc)(t,TW.default)),a;if(c||r)a=t.let("valid"),e.block$data(a,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let u=t.const("vSchema",s);a=(0,$c.or)(...i.map((m,h)=>p(u,h)))}e.pass(a);function d(){t.assign(a,!1),t.forOf("v",s,u=>t.if((0,$c._)`${f()}(${n}, ${u})`,()=>t.assign(a,!0).break()))}function p(u,m){let h=i[m];return typeof h=="object"&&h!==null?(0,$c._)`${f()}(${n}, ${u}[${m}])`:(0,$c._)`${n} === ${h}`}}};Gg.default=$W});var sA=_(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var jW=zE(),DW=JE(),qW=YE(),LW=XE(),WW=QE(),MW=ZE(),FW=eA(),HW=nA(),BW=rA(),VW=iA(),UW=[jW.default,DW.default,qW.default,LW.default,WW.default,MW.default,FW.default,HW.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},BW.default,VW.default];Yg.default=UW});var Qg=_(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.validateAdditionalItems=void 0;var Cs=ge(),Xg=Se(),KW={message:({params:{len:e}})=>(0,Cs.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Cs._)`{limit: ${e}}`},zW={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:KW,code(e){let{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,Xg.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}oA(e,r)}};function oA(e,t){let{gen:n,schema:r,data:i,keyword:s,it:o}=e;o.items=!0;let c=n.const("len",(0,Cs._)`${i}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,Cs._)`${c} <= ${t.length}`);else if(typeof r=="object"&&!(0,Xg.alwaysValidSchema)(o,r)){let f=n.var("valid",(0,Cs._)`${c} <= ${t.length}`);n.if((0,Cs.not)(f),()=>l(f)),e.ok(f)}function l(f){n.forRange("i",t.length,c,a=>{e.subschema({keyword:s,dataProp:a,dataPropType:Xg.Type.Num},f),o.allErrors||n.if((0,Cs.not)(f),()=>n.break())})}}jc.validateAdditionalItems=oA;jc.default=zW});var Zg=_(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.validateTuple=void 0;var aA=ge(),Wd=Se(),JW=Tn(),GW={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:n}=e;if(Array.isArray(t))return cA(e,"additionalItems",t);n.items=!0,!(0,Wd.alwaysValidSchema)(n,t)&&e.ok((0,JW.validateArray)(e))}};function cA(e,t,n=e.schema){let{gen:r,parentSchema:i,data:s,keyword:o,it:c}=e;a(i),c.opts.unevaluated&&n.length&&c.items!==!0&&(c.items=Wd.mergeEvaluated.items(r,n.length,c.items));let l=r.name("valid"),f=r.const("len",(0,aA._)`${s}.length`);n.forEach((d,p)=>{(0,Wd.alwaysValidSchema)(c,d)||(r.if((0,aA._)`${f} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},l)),e.ok(l))});function a(d){let{opts:p,errSchemaPath:u}=c,m=n.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Wd.checkStrictMode)(c,g,p.strictTuples)}}}Dc.validateTuple=cA;Dc.default=GW});var lA=_(ew=>{"use strict";Object.defineProperty(ew,"__esModule",{value:!0});var YW=Zg(),XW={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,YW.validateTuple)(e,"items")};ew.default=XW});var dA=_(tw=>{"use strict";Object.defineProperty(tw,"__esModule",{value:!0});var uA=ge(),QW=Se(),ZW=Tn(),eM=Qg(),tM={message:({params:{len:e}})=>(0,uA.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,uA._)`{limit: ${e}}`},nM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:tM,code(e){let{schema:t,parentSchema:n,it:r}=e,{prefixItems:i}=n;r.items=!0,!(0,QW.alwaysValidSchema)(r,t)&&(i?(0,eM.validateAdditionalItems)(e,i):e.ok((0,ZW.validateArray)(e)))}};tw.default=nM});var fA=_(nw=>{"use strict";Object.defineProperty(nw,"__esModule",{value:!0});var $n=ge(),Md=Se(),rM={message:({params:{min:e,max:t}})=>t===void 0?(0,$n.str)`must contain at least ${e} valid item(s)`:(0,$n.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,$n._)`{minContains: ${e}}`:(0,$n._)`{minContains: ${e}, maxContains: ${t}}`},iM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:rM,code(e){let{gen:t,schema:n,parentSchema:r,data:i,it:s}=e,o,c,{minContains:l,maxContains:f}=r;s.opts.next?(o=l===void 0?1:l,c=f):o=1;let a=t.const("len",(0,$n._)`${i}.length`);if(e.setParams({min:o,max:c}),c===void 0&&o===0){(0,Md.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&o>c){(0,Md.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Md.alwaysValidSchema)(s,n)){let h=(0,$n._)`${a} >= ${o}`;c!==void 0&&(h=(0,$n._)`${h} && ${a} <= ${c}`),e.pass(h);return}s.items=!0;let d=t.name("valid");c===void 0&&o===1?u(d,()=>t.if(d,()=>t.break())):o===0?(t.let(d,!0),c!==void 0&&t.if((0,$n._)`${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);u(h,()=>t.if(h,()=>m(g)))}function u(h,g){t.forRange("i",0,a,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Md.Type.Num,compositeRule:!0},h),g()})}function m(h){t.code((0,$n._)`${h}++`),c===void 0?t.if((0,$n._)`${h} >= ${o}`,()=>t.assign(d,!0).break()):(t.if((0,$n._)`${h} > ${c}`,()=>t.assign(d,!1).break()),o===1?t.assign(d,!0):t.if((0,$n._)`${h} >= ${o}`,()=>t.assign(d,!0)))}}};nw.default=iM});var hA=_(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.validateSchemaDeps=yr.validatePropertyDeps=yr.error=void 0;var rw=ge(),sM=Se(),qc=Tn();yr.error={message:({params:{property:e,depsCount:t,deps:n}})=>{let r=t===1?"property":"properties";return(0,rw.str)`must have ${r} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:r}})=>(0,rw._)`{property: ${e},
|
|
154
|
+
missingProperty: ${r},
|
|
155
|
+
depsCount: ${t},
|
|
156
|
+
deps: ${n}}`};var oM={keyword:"dependencies",type:"object",schemaType:"object",error:yr.error,code(e){let[t,n]=aM(e);pA(e,t),mA(e,n)}};function aM({schema:e}){let t={},n={};for(let r in e){if(r==="__proto__")continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function pA(e,t=e.schema){let{gen:n,data:r,it:i}=e;if(Object.keys(t).length===0)return;let s=n.let("missing");for(let o in t){let c=t[o];if(c.length===0)continue;let l=(0,qc.propertyInData)(n,r,o,i.opts.ownProperties);e.setParams({property:o,depsCount:c.length,deps:c.join(", ")}),i.allErrors?n.if(l,()=>{for(let f of c)(0,qc.checkReportMissingProp)(e,f)}):(n.if((0,rw._)`${l} && (${(0,qc.checkMissingProp)(e,c,s)})`),(0,qc.reportMissingProp)(e,s),n.else())}}yr.validatePropertyDeps=pA;function mA(e,t=e.schema){let{gen:n,data:r,keyword:i,it:s}=e,o=n.name("valid");for(let c in t)(0,sM.alwaysValidSchema)(s,t[c])||(n.if((0,qc.propertyInData)(n,r,c,s.opts.ownProperties),()=>{let l=e.subschema({keyword:i,schemaProp:c},o);e.mergeValidEvaluated(l,o)},()=>n.var(o,!0)),e.ok(o))}yr.validateSchemaDeps=mA;yr.default=oM});var wA=_(iw=>{"use strict";Object.defineProperty(iw,"__esModule",{value:!0});var gA=ge(),cM=Se(),lM={message:"property name must be valid",params:({params:e})=>(0,gA._)`{propertyName: ${e.propertyName}}`},uM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:lM,code(e){let{gen:t,schema:n,data:r,it:i}=e;if((0,cM.alwaysValidSchema)(i,n))return;let s=t.name("valid");t.forIn("key",r,o=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,gA.not)(s),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(s)}};iw.default=uM});var ow=_(sw=>{"use strict";Object.defineProperty(sw,"__esModule",{value:!0});var Fd=Tn(),Zn=ge(),dM=Lr(),Hd=Se(),fM={message:"must NOT have additional properties",params:({params:e})=>(0,Zn._)`{additionalProperty: ${e.additionalProperty}}`},pM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:fM,code(e){let{gen:t,schema:n,parentSchema:r,data:i,errsCount:s,it:o}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:c,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Hd.alwaysValidSchema)(o,n))return;let f=(0,Fd.allSchemaProperties)(r.properties),a=(0,Fd.allSchemaProperties)(r.patternProperties);d(),e.ok((0,Zn._)`${s} === ${dM.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,Hd.schemaRefOrVal)(o,r.properties,"properties");w=(0,Fd.isOwnProperty)(t,k,g)}else f.length?w=(0,Zn.or)(...f.map(k=>(0,Zn._)`${g} === ${k}`)):w=Zn.nil;return a.length&&(w=(0,Zn.or)(w,...a.map(k=>(0,Zn._)`${(0,Fd.usePattern)(e,k)}.test(${g})`))),(0,Zn.not)(w)}function u(g){t.code((0,Zn._)`delete ${i}[${g}]`)}function m(g){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){u(g);return}if(n===!1){e.setParams({additionalProperty:g}),e.error(),c||t.break();return}if(typeof n=="object"&&!(0,Hd.alwaysValidSchema)(o,n)){let w=t.name("valid");l.removeAdditional==="failing"?(h(g,w,!1),t.if((0,Zn.not)(w),()=>{e.reset(),u(g)})):(h(g,w),c||t.if((0,Zn.not)(w),()=>t.break()))}}function h(g,w,k){let y={keyword:"additionalProperties",dataProp:g,dataPropType:Hd.Type.Str};k===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(y,w)}}};sw.default=pM});var kA=_(cw=>{"use strict";Object.defineProperty(cw,"__esModule",{value:!0});var mM=Rc(),yA=Tn(),aw=Se(),vA=ow(),hM={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,parentSchema:r,data:i,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&vA.default.code(new mM.KeywordCxt(s,vA.default,"additionalProperties"));let o=(0,yA.allSchemaProperties)(n);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=aw.mergeEvaluated.props(t,(0,aw.toHash)(o),s.props));let c=o.filter(d=>!(0,aw.alwaysValidSchema)(s,n[d]));if(c.length===0)return;let l=t.name("valid");for(let d of c)f(d)?a(d):(t.if((0,yA.propertyInData)(t,i,d,s.opts.ownProperties)),a(d),s.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(l);function f(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function a(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},l)}}};cw.default=hM});var SA=_(lw=>{"use strict";Object.defineProperty(lw,"__esModule",{value:!0});var bA=Tn(),Bd=ge(),RA=Se(),CA=Se(),gM={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,data:r,parentSchema:i,it:s}=e,{opts:o}=s,c=(0,bA.allSchemaProperties)(n),l=c.filter(h=>(0,RA.alwaysValidSchema)(s,n[h]));if(c.length===0||l.length===c.length&&(!s.opts.unevaluated||s.props===!0))return;let f=o.strictSchema&&!o.allowMatchingProperties&&i.properties,a=t.name("valid");s.props!==!0&&!(s.props instanceof Bd.Name)&&(s.props=(0,CA.evaluatedPropsToName)(t,s.props));let{props:d}=s;p();function p(){for(let h of c)f&&u(h),s.allErrors?m(h):(t.var(a,!0),m(h),t.if(a))}function u(h){for(let g in f)new RegExp(h).test(g)&&(0,RA.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",r,g=>{t.if((0,Bd._)`${(0,bA.usePattern)(e,h)}.test(${g})`,()=>{let w=l.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:CA.Type.Str},a),s.opts.unevaluated&&d!==!0?t.assign((0,Bd._)`${d}[${g}]`,!0):!w&&!s.allErrors&&t.if((0,Bd.not)(a),()=>t.break())})})}}};lw.default=gM});var EA=_(uw=>{"use strict";Object.defineProperty(uw,"__esModule",{value:!0});var wM=Se(),yM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:n,it:r}=e;if((0,wM.alwaysValidSchema)(r,n)){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"}};uw.default=yM});var AA=_(dw=>{"use strict";Object.defineProperty(dw,"__esModule",{value:!0});var vM=Tn(),kM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:vM.validateUnion,error:{message:"must match a schema in anyOf"}};dw.default=kM});var xA=_(fw=>{"use strict";Object.defineProperty(fw,"__esModule",{value:!0});var Vd=ge(),bM=Se(),RM={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Vd._)`{passingSchemas: ${e.passing}}`},CM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:RM,code(e){let{gen:t,schema:n,parentSchema:r,it:i}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(i.opts.discriminator&&r.discriminator)return;let s=n,o=t.let("valid",!1),c=t.let("passing",null),l=t.name("_valid");e.setParams({passing:c}),t.block(f),e.result(o,()=>e.reset(),()=>e.error(!0));function f(){s.forEach((a,d)=>{let p;(0,bM.alwaysValidSchema)(i,a)?t.var(l,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},l),d>0&&t.if((0,Vd._)`${l} && ${o}`).assign(o,!1).assign(c,(0,Vd._)`[${c}, ${d}]`).else(),t.if(l,()=>{t.assign(o,!0),t.assign(c,d),p&&e.mergeEvaluated(p,Vd.Name)})})}}};fw.default=CM});var IA=_(pw=>{"use strict";Object.defineProperty(pw,"__esModule",{value:!0});var SM=Se(),EM={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");let i=t.name("valid");n.forEach((s,o)=>{if((0,SM.alwaysValidSchema)(r,s))return;let c=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(c)})}};pw.default=EM});var OA=_(mw=>{"use strict";Object.defineProperty(mw,"__esModule",{value:!0});var Ud=ge(),PA=Se(),AM={message:({params:e})=>(0,Ud.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ud._)`{failingKeyword: ${e.ifClause}}`},xM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:AM,code(e){let{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,PA.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=_A(r,"then"),s=_A(r,"else");if(!i&&!s)return;let o=t.let("valid",!0),c=t.name("_valid");if(l(),e.reset(),i&&s){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,Ud.not)(c),f("else"));e.pass(o,()=>e.error(!0));function l(){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(o,c),e.mergeValidEvaluated(p,o),d?t.assign(d,(0,Ud._)`${a}`):e.setParams({ifClause:a})}}}};function _A(e,t){let n=e.schema[t];return n!==void 0&&!(0,PA.alwaysValidSchema)(e,n)}mw.default=xM});var TA=_(hw=>{"use strict";Object.defineProperty(hw,"__esModule",{value:!0});var IM=Se(),_M={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,IM.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};hw.default=_M});var NA=_(gw=>{"use strict";Object.defineProperty(gw,"__esModule",{value:!0});var PM=Qg(),OM=lA(),TM=Zg(),NM=dA(),$M=fA(),jM=hA(),DM=wA(),qM=ow(),LM=kA(),WM=SA(),MM=EA(),FM=AA(),HM=xA(),BM=IA(),VM=OA(),UM=TA();function KM(e=!1){let t=[MM.default,FM.default,HM.default,BM.default,VM.default,UM.default,DM.default,qM.default,jM.default,LM.default,WM.default];return e?t.push(OM.default,NM.default):t.push(PM.default,TM.default),t.push($M.default),t}gw.default=KM});var $A=_(ww=>{"use strict";Object.defineProperty(ww,"__esModule",{value:!0});var ot=ge(),zM={message:({schemaCode:e})=>(0,ot.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ot._)`{format: ${e}}`},JM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:zM,code(e,t){let{gen:n,data:r,$data:i,schema:s,schemaCode:o,it:c}=e,{opts:l,errSchemaPath:f,schemaEnv:a,self:d}=c;if(!l.validateFormats)return;i?p():u();function p(){let m=n.scopeValue("formats",{ref:d.formats,code:l.code.formats}),h=n.const("fDef",(0,ot._)`${m}[${o}]`),g=n.let("fType"),w=n.let("format");n.if((0,ot._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,ot._)`${h}.type || "string"`).assign(w,(0,ot._)`${h}.validate`),()=>n.assign(g,(0,ot._)`"string"`).assign(w,h)),e.fail$data((0,ot.or)(k(),y()));function k(){return l.strictSchema===!1?ot.nil:(0,ot._)`${o} && !${w}`}function y(){let R=a.$async?(0,ot._)`(${h}.async ? await ${w}(${r}) : ${w}(${r}))`:(0,ot._)`${w}(${r})`,C=(0,ot._)`(typeof ${w} == "function" ? ${R} : ${w}.test(${r}))`;return(0,ot._)`${w} && ${w} !== true && ${g} === ${t} && !${C}`}}function u(){let m=d.formats[s];if(!m){k();return}if(m===!0)return;let[h,g,w]=y(m);h===t&&e.pass(R());function k(){if(l.strictSchema===!1){d.logger.warn(C());return}throw new Error(C());function C(){return`unknown format "${s}" ignored in schema at path "${f}"`}}function y(C){let A=C instanceof RegExp?(0,ot.regexpCode)(C):l.code.formats?(0,ot._)`${l.code.formats}${(0,ot.getProperty)(s)}`:void 0,q=n.scopeValue("formats",{key:s,ref:C,code:A});return typeof C=="object"&&!(C instanceof RegExp)?[C.type||"string",C.validate,(0,ot._)`${q}.validate`]:["string",C,q]}function R(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!a.$async)throw new Error("async format in sync schema");return(0,ot._)`await ${w}(${r})`}return typeof g=="function"?(0,ot._)`${w}(${r})`:(0,ot._)`${w}.test(${r})`}}}};ww.default=JM});var jA=_(yw=>{"use strict";Object.defineProperty(yw,"__esModule",{value:!0});var GM=$A(),YM=[GM.default];yw.default=YM});var DA=_(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.contentVocabulary=jo.metadataVocabulary=void 0;jo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];jo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var LA=_(vw=>{"use strict";Object.defineProperty(vw,"__esModule",{value:!0});var XM=KE(),QM=sA(),ZM=NA(),eF=jA(),qA=DA(),tF=[XM.default,QM.default,(0,ZM.default)(),eF.default,qA.metadataVocabulary,qA.contentVocabulary];vw.default=tF});var MA=_(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});Kd.DiscrError=void 0;var WA;(function(e){e.Tag="tag",e.Mapping="mapping"})(WA||(Kd.DiscrError=WA={}))});var HA=_(bw=>{"use strict";Object.defineProperty(bw,"__esModule",{value:!0});var Do=ge(),kw=MA(),FA=Ed(),nF=Cc(),rF=Se(),iF={message:({params:{discrError:e,tagName:t}})=>e===kw.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Do._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},sF={keyword:"discriminator",type:"object",schemaType:"object",error:iF,code(e){let{gen:t,data:n,schema:r,parentSchema:i,it:s}=e,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=r.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let l=t.let("valid",!1),f=t.const("tag",(0,Do._)`${n}${(0,Do.getProperty)(c)}`);t.if((0,Do._)`typeof ${f} == "string"`,()=>a(),()=>e.error(!1,{discrError:kw.DiscrError.Tag,tag:f,tagName:c})),e.ok(l);function a(){let u=p();t.if(!1);for(let m in u)t.elseIf((0,Do._)`${f} === ${m}`),t.assign(l,d(u[m]));t.else(),e.error(!1,{discrError:kw.DiscrError.Mapping,tag:f,tagName:c}),t.endIf()}function d(u){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:u},m);return e.mergeEvaluated(h,Do.Name),m}function p(){var u;let m={},h=w(i),g=!0;for(let R=0;R<o.length;R++){let C=o[R];if(C?.$ref&&!(0,rF.schemaHasRulesButRef)(C,s.self.RULES)){let q=C.$ref;if(C=FA.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,q),C instanceof FA.SchemaEnv&&(C=C.schema),C===void 0)throw new nF.default(s.opts.uriResolver,s.baseId,q)}let A=(u=C?.properties)===null||u===void 0?void 0:u[c];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);g=g&&(h||w(C)),k(A,R)}if(!g)throw new Error(`discriminator: "${c}" must be required`);return m;function w({required:R}){return Array.isArray(R)&&R.includes(c)}function k(R,C){if(R.const)y(R.const,C);else if(R.enum)for(let A of R.enum)y(A,C);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function y(R,C){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${c}" values must be unique strings`);m[R]=C}}}};bw.default=sF});var BA=_((H9,oF)=>{oF.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 UA=_((Me,Rw)=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.MissingRefError=Me.ValidationError=Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=Me.Ajv=void 0;var aF=ME(),cF=LA(),lF=HA(),VA=BA(),uF=["/properties"],zd="http://json-schema.org/draft-07/schema",qo=class extends aF.default{_addVocabularies(){super._addVocabularies(),cF.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(lF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(VA,uF):VA;this.addMetaSchema(t,zd,!1),this.refs["http://json-schema.org/schema"]=zd}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(zd)?zd:void 0)}};Me.Ajv=qo;Rw.exports=Me=qo;Rw.exports.Ajv=qo;Object.defineProperty(Me,"__esModule",{value:!0});Me.default=qo;var dF=Rc();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return dF.KeywordCxt}});var Lo=ge();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return Lo._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return Lo.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return Lo.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return Lo.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return Lo.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return Lo.CodeGen}});var fF=Cd();Object.defineProperty(Me,"ValidationError",{enumerable:!0,get:function(){return fF.default}});var pF=Cc();Object.defineProperty(Me,"MissingRefError",{enumerable:!0,get:function(){return pF.default}})});import{createRequire as NF}from"node:module";function Mo(e,t){if(!Yd){let n=process.emitWarning;process.emitWarning=((r,...i)=>{String(r instanceof Error?r.message:r).startsWith("SQLite is an experimental feature and might change at any time")||Reflect.apply(n,process,[r,...i])});try{Yd=$F("node:sqlite").DatabaseSync}finally{process.emitWarning=n}}return t===void 0?new Yd(e):new Yd(e,t)}var $F,Yd,Xd=ie(()=>{"use strict";$F=NF(import.meta.url??__filename)});import{AsyncLocalStorage as jF}from"node:async_hooks";function tx(e){return Math.max(0,Math.min(e,(ex.getStore()?.deadline??1/0)-performance.now()))}function nx(){let e=ex.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new Tw}var ex,Tw,rx=ie(()=>{"use strict";ex=new jF,Tw=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}}});import{randomUUID as DF}from"node:crypto";import{promises as _i}from"node:fs";import Fc from"node:path";import{performance as ix}from"node:perf_hooks";async function sx(e){let t,n;try{let r=await _i.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("File lock metadata must be a regular file: "+e);n=[r.dev,r.ino,r.size,r.mtimeMs].join(":"),t=await _i.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}try{let r=JSON.parse(t),i=r.nonce??r.id,s=typeof r.createdAt=="number"?r.createdAt:Date.parse(r.createdAt);if(typeof i=="string"&&i&&Number.isFinite(s))return{owner:{nonce:i,createdAt:s,...r.protocolVersion===2?{protocolVersion:2}:{},...typeof r.operation=="string"?{operation:r.operation}:{}},token:i,legacy:r.protocolVersion!==2}}catch{}return{owner:null,token:n,legacy:!0}}async function qF(e){let t=e+".sqlite";try{let r=await _i.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("File lock database must be a regular file: "+t)}catch(r){if(r.code!=="ENOENT")throw r}let n;try{n=Mo(Fc.toNamespacedPath(t))}catch(r){throw new Error("Unable to open Runtime lock database "+t,{cause:r})}try{return n.exec("PRAGMA busy_timeout=0; BEGIN IMMEDIATE;"),n}catch(r){if(n.close(),/database is (?:locked|busy)/iu.test(String(r)))return null;throw new Error("Unable to acquire Runtime lock transaction "+t,{cause:r})}}function ox(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function LF(e,t={}){e=Fc.resolve(e),await _i.mkdir(Fc.dirname(e),{recursive:!0});let n=await _i.lstat(Fc.dirname(e));if(!n.isDirectory()||n.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+Fc.dirname(e));let r=ix.now()+tx(t.timeoutMs??3e4),i;for(;nx(),i=await qF(e),!i;){if(ix.now()>=r)throw new Error("Timed out waiting for file lock: "+e);await new Promise(c=>setTimeout(c,t.retryMs??20))}let s={protocolVersion:2,nonce:DF(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let c=await sx(e);if(c?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
|
|
157
|
+
Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));c&&await _i.unlink(e),await _i.writeFile(e,JSON.stringify(s),{mode:384,flag:"wx"})}catch(c){throw ox(i),c}let o=!1;return{owner:s,async release(){if(o)return!0;o=!0;let c=!0;try{let l=await sx(e);l?.token===s.nonce?l.owner?.createdAt===s.createdAt&&l.owner.operation===s.operation?await _i.unlink(e):(c=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
|
|
158
|
+
`)):l&&(c=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
|
|
159
|
+
`))}finally{ox(i)}return c}}}async function ax(e,t,n={}){let r=await LF(e,n),i;try{i=await t()}catch(s){try{await r.release()}catch(o){process.stderr.write("[comet] lock cleanup failed; preserved the original operation error: "+String(o)+`
|
|
160
|
+
`)}throw s}return await r.release(),i}var cx=ie(()=>{"use strict";Xd();rx()});var Wx=ie(()=>{"use strict"});import{spawn as S8,execFileSync as oB}from"node:child_process";import zw from"node:path";function lB(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Mx(e,t,n={}){let r=n.timeoutMs??aB,i=n.maxBufferBytes??cB;if(!Number.isSafeInteger(r)||r<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(i)||i<1)throw new Error("External command max buffer must be a positive integer");let s=zw.resolve(n.cwd??process.cwd()),o=n.env??process.env,c=process.platform==="win32"?so(e,o,s):e,l=zw.win32.extname(c).toLowerCase(),f=l===".bat"||l===".cmd";process.platform==="win32"&&f&&Lb(t);try{let a=()=>oB(c,[...t],{cwd:s,env:o,...n.input!==void 0?{input:n.input}:{},encoding:"utf8",stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:r,killSignal:"SIGKILL",maxBuffer:i,windowsHide:!0,shell:process.platform==="win32"&&f});return/^(?:git|git\.exe)$/iu.test(zw.win32.basename(e))?mr(a):a()}catch(a){let d=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new Ti(e,t,d,{cause:a,timedOut:lB(a)})}}var aB,cB,Ti,uf=ie(()=>{"use strict";Wx();ds();fu();aB=6e4,cB=8*1024*1024,Ti=class extends Error{constructor(n,r,i,s){super(`${n} ${r.join(" ")} failed${i?`: ${i}`:""}`,s);this.command=n;this.args=r;this.stderr=i;this.name="ExternalCommandError",this.timedOut=s?.timedOut===!0}command;args;stderr;timedOut}});import{execFileSync as Fx}from"node:child_process";function Hx(e,t){if(t.some(o=>!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(o)))throw new Error("Git commit paths require complete commit IDs");if(!t.length)return new Map;let n;try{n=mr(()=>Fx("git",["diff-tree","--stdin","--always","--no-renames","--name-status","-r","-z"],{cwd:e,input:t.join(`
|
|
161
|
+
`)+`
|
|
162
|
+
`,encoding:"utf8",timeout:dB,maxBuffer:fB,windowsHide:!0}))}catch(o){if(!["ENOBUFS","ETIMEDOUT"].includes(o.code??""))throw o;return new Map(t.map(c=>[c,mr(()=>Fx("git",["diff-tree","--no-commit-id","--no-renames","--name-only","-r","-z",c],{cwd:e,encoding:"utf8",windowsHide:!0})).split("\0").filter(Boolean)]))}let r=n.split("\0"),i=new Map,s=0;for(let o of t){if(r[s++]!==o)throw new Error(`Git commit path response does not match ${o}`);let c=[];for(;/^[ACDMTUXB]$/u.test(r[s]??"");){s+=1;let l=r[s++];if(!l)throw new Error("Git commit path response is incomplete");c.push(l)}i.set(o,c)}if(r.slice(s).some(Boolean))throw new Error("Git commit path response has unexpected records");return i}var dB,fB,Jw=ie(()=>{"use strict";ds();uf();dB=3e4,fB=8*1024*1024});import{createHash as PU}from"crypto";import Cr from"path";function Jf(e){return`${e.replace(/\n+$/u,"")}
|
|
163
|
+
`}function Hi(e,t,n){let r=e.replace(/\r\n/gu,`
|
|
164
|
+
`),i=r.split(`
|
|
165
|
+
`),s=i[0]==="---"?i.indexOf("---",1):-1,o=n.match(/^([^:\n]+):/u)?.[1]?.trim();if(s!==-1){let l=i.slice(1,s);if(l.filter(a=>/^archived-with:/u.test(a)).length===1&&l.includes(`archived-with: ${t}`)&&(!n||l.includes(n)&&l.filter(a=>a.startsWith(`${o}:`)).length===1))return Jf(r);let f=i.slice(1,s).filter(a=>{let d=a.match(/^([^:\n]+):/u)?.[1]?.trim();return d===void 0?!0:d!=="archived-with"&&d!==o});return f.push(`archived-with: ${t}`),n&&f.push(n),Jf(["---",...f,"---",...i.slice(s+1)].join(`
|
|
166
|
+
`))}let c=["---",`archived-with: ${t}`];return n&&c.push(n),o!=="status"&&c.push("status: final"),c.push("---"),Jf([...c,r].join(`
|
|
167
|
+
`))}function ht(e,t,n){if(!e)return null;let r=e.replaceAll("\\","/");return r.startsWith(`${t}/`)?`${n}/${r.slice(t.length+1)}`:r}Qa();ju();import zu from"path";var Pr={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 dr(e,t){if(zu.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let n=zu.resolve(e),r=zu.resolve(n,t);if(r!==n&&!r.startsWith(n+zu.sep))throw new Error("Run path must stay inside the change directory")}async function ZR(e,t,n,r={}){dr(e,t),await Nu(e,t,`${JSON.stringify(n)}
|
|
168
|
+
`,Pr.trajectory,"Run trajectory",r)}async function eC(e,t,n={}){dr(e,t);let r=await di(e,t,Pr.trajectory,"Run trajectory",n);return r===null?[]:r.split(/\r?\n/).map((i,s)=>({line:i,number:s+1})).filter(({line:i})=>i.length>0).map(({line:i,number:s})=>{try{return JSON.parse(i)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function tC(e,t,n={}){dr(e,t);let r=await di(e,t,Pr.artifacts,"Run artifacts",n);return r===null?{}:JSON.parse(r)}async function nC(e,t,n,r={}){dr(e,t),await fi(e,t,JSON.stringify(n,null,2)+`
|
|
169
|
+
`,Pr.artifacts,"Run artifacts",r)}async function rC(e,t,n,r={}){dr(e,t),await fi(e,t,n,Pr.context,"Run context",r)}async function iC(e,t,n={}){return dr(e,t),di(e,t,Pr.context,"Run context",n)}async function sC(e,t,n,r={}){dr(e,t),await fi(e,t,JSON.stringify(n,null,2)+`
|
|
170
|
+
`,Pr.pendingAction,"Run pending action",r)}async function oC(e,t,n={}){dr(e,t);let r=await di(e,t,Pr.pendingAction,"Run pending action",n);return r===null?null:JSON.parse(r)}async function aC(e,t,n={}){dr(e,t),await $u(e,t,"Run pending action",n)}async function cC(e,t,n,r={}){dr(e,t),await fi(e,t,JSON.stringify(n,null,2)+`
|
|
171
|
+
`,Pr.checkpoint,"Run checkpoint",r)}mi();rn();Ue();import wi from"node:path";async function Ju(e,t){let n=wi.resolve(e,t),r=wi.relative(wi.resolve(e),n);if(wi.isAbsolute(t)||wi.isAbsolute(r)||r===".."||r.startsWith(`..${wi.sep}`))throw new Error("Run path must stay inside the change directory");let i=await it(e),s=await mo(i,n,{readOnly:!0}),o=s?.root??e,c=s?.target??n,l=o===wi.parse(c).root?lt(i):o;return{root:l,ref:wi.relative(l,c).replaceAll("\\","/"),inspectionRoot:o,target:c}}async function Or(...e){return e[0]=await Ce(e[0]),ZR(...e)}async function Tr(...e){let t=await Ju(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,eC(...e)}async function Za(...e){let t=await Ju(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,tC(...e)}async function yo(...e){return e[0]=await Ce(e[0]),nC(...e)}async function Gu(...e){return e[0]=await Ce(e[0]),rC(...e)}async function lC(...e){let t=await Ju(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,iC(...e)}async function uC(...e){return e[0]=await Ce(e[0]),sC(...e)}async function Yu(...e){let t=await Ju(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,oC(...e)}async function Xu(...e){return e[0]=await Ce(e[0]),aC(...e)}async function Qu(...e){return e[0]=await Ce(e[0]),cC(...e)}import ed from"path";import{createHash as qj}from"node:crypto";import{types as Lj}from"node:util";var dC=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"}),b=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="RuntimeProtocolError",this.recovery=Object.hasOwn(dC,n)?dC[n]:"manual-review"}code;recovery};var hh=new WeakMap,fC=new WeakMap;function xn(e){return hh.has(e)}function Zu(e,t=!0,n=!1,r=!1){let i=new Set,s=new WeakMap;function o(c,l){if(l>64)throw new b("INVALID_JSON","数据嵌套超过 64 层");if(c===null||typeof c=="string"||typeof c=="boolean")return n?JSON.stringify(c):c;if(typeof c=="number"&&Number.isFinite(c))return n?JSON.stringify(c):c===0?0:c;if(typeof c!="object"||c===null)throw new b("INVALID_JSON","数据必须能无损保存为 JSON");if(i.has(c))throw new b("INVALID_JSON","数据包含循环引用");if(Lj.isProxy(c))throw new b("INVALID_JSON","仅接受无执行行为的 JSON 数据");let f=hh.get(c);if(!t&&!n&&f!==void 0){if(l+f>64)throw new b("INVALID_JSON","数据嵌套超过 64 层");return s.set(c,{value:c,height:f}),c}let a=s.get(c);if(a){if(l+a.height>64)throw new b("INVALID_JSON","数据嵌套超过 64 层");return t?Oe(a.value):n?a.value:c}i.add(c);let d=0,p=m=>m&&typeof m=="object"?s.get(m)?.height??0:0,u=m=>(s.set(c,{value:m,height:d}),r&&(Object.freeze(c),hh.set(c,d)),m);try{if(Array.isArray(c)){if(Reflect.ownKeys(c).length!==c.length+1)throw new b("INVALID_JSON","数组不能包含空洞或额外属性");let w=[];for(let k=0;k<c.length;k+=1){let y=Object.getOwnPropertyDescriptor(c,String(k));if(!y||!("value"in y))throw new b("INVALID_JSON","数组元素必须是普通数据");let R=o(y.value,l+1);d=Math.max(d,1+p(y.value)),(t||n)&&w.push(R)}return u(n?`[${w.join(",")}]`:t?w:c)}let m=Object.getPrototypeOf(c);if(m!==Object.prototype&&m!==null)throw new b("INVALID_JSON","仅接受普通 JSON 对象");let h=[],g=Reflect.ownKeys(c);(t||n)&&g.sort((w,k)=>{let y=String(w),R=String(k),C=String(Number(y))===y&&Number.isInteger(Number(y))&&Number(y)>=0&&Number(y)<4294967295,A=String(Number(R))===R&&Number.isInteger(Number(R))&&Number(R)>=0&&Number(R)<4294967295;return C||A?C&&A?Number(y)-Number(R):C?-1:1:y<R?-1:y>R?1:0});for(let w of g){let k=Object.getOwnPropertyDescriptor(c,w);if(typeof w!="string"||!k.enumerable||!("value"in k))throw new b("INVALID_JSON","对象属性必须是可枚举的字符串数据属性");let y=o(k.value,l+1);d=Math.max(d,1+p(k.value)),(t||n)&&h.push([w,y])}return u(n?`{${h.map(([w,k])=>`${JSON.stringify(w)}:${k}`).join(",")}}`:t?Object.fromEntries(h):c)}finally{i.delete(c)}}return o(e,0)}function Nr(e){return Zu(e,!1,!0)}function Ye(e){return Zu(e)}function Oe(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++)n.push(Oe(e[r]));return n}let t={};for(let n of Object.keys(e)){let r=Oe(e[n]);n==="__proto__"?Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0}):t[n]=r}return t}function In(e){Zu(e,!1)}function j(e){let t=e!==null&&typeof e=="object"&&xn(e),n=t?fC.get(e):void 0;if(n!==void 0)return n;let r=qj("sha256").update(Nr(e)).digest("hex");return t&&fC.set(e,r),r}function as(e){return Zu(e,!1,!1,!0),e}kt();Sn();rn();ve();Ue();mi();ve();var nc=Rt(Pt(),1);Ht();ve();nn();nn();qu();import{randomUUID as Wj}from"node:crypto";import fr from"path";import{AsyncLocalStorage as Mj}from"node:async_hooks";var pC=new Mj,ec=".comet-state-transaction.json";async function sn(e,t){let n=await Ce(e);return pC.getStore()===n?t():pC.run(n,async()=>(await hC(e),t()))}async function tc(e,t){let n=t===ec?await Ce(e):e;try{return(await ce(n,t,Number.MAX_SAFE_INTEGER,{label:"Classic state transaction"})).bytes.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}function Fj(e){if(e===null)return null;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic transaction Run");let t=e,n=ns({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(!n)throw new Error("Invalid Classic transaction Run identity");return n}async function hC(e){let t=await tc(e,ec);if(t===null)return;let n=JSON.parse(t);if(!n||n.schema!=="comet.classic.state-transaction.v1"||n.beforeYaml!==null&&typeof n.beforeYaml!="string"||typeof n.afterYaml!="string")throw new Error("Invalid Classic state transaction");let r=await ue(e),i=n.stateFile??Au;if(typeof i!="string"||!xu(i)||fr.basename(r)!==i)throw new Error("Classic state transaction belongs to a different state filename; preserve files for recovery");let s=await tc(e,i);if(s!==n.beforeYaml&&s!==n.afterYaml)throw new Error("Classic state transaction conflicts with current YAML; preserve files for recovery");let o=Fj(s===n.afterYaml?n.afterRun:n.beforeRun);if(await ue(e)!==r)throw new Error("Classic state filename changed during transaction recovery");o?await rs(await Ce(e),o):await Ua(await Ce(e));let c=await Ce(e);await lr(fr.join(c,ec),{containedRoot:c})}function gC(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 cs(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 mC(e,t,n){e.get(t)!==n&&e.set(t,n)}function wC(e,t){if(t.classic)for(let[n,r]of Object.entries(Wu(t.classic)))n==="auto_transition"&&r===null&&!e.has(n)||mC(e,n,r);else for(let n of pi)e.delete(n);rh(e.toJS(),t.run),t.run?mC(e,"run_id",t.run.runId):e.delete("run_id")}function Hj(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 n of t)e.delete(n)}function yC(e){let t=!1;for(let n of["build_command","verify_command"])e.has(n)&&(e.delete(n),t=!0);return t}async function gh(e){let t;try{t=(await ce(fr.dirname(e),fr.basename(e),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new nc.Document({})}let n=(0,nc.parseDocument)(t);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return cs(n),n}var Bj=rt("classicStateProjection",e=>Vj(e));async function $t(e,t={}){return t.migrate===!1?Bj(e):sn(e,()=>Uj(e,t))}async function Vj(e){let t=await ph(e);if(t===null)return tn({});if((await M(t,ec,{label:"Classic state transaction",expected:"file"})).exists)throw new Error("Classic state transaction is incomplete; use an explicit state operation to recover it");let n=await gh(await ue(e));yC(n);let r=cs(n),i=await Va(t);return!i&&r.run_id&&r.skill&&(i=ns(r)),gC(r,i),tn(r,i)}async function Uj(e,t){let n=t.migrate!==!1,r=await ue(e),i=await gh(r),s=cs(i),o=yC(i);o&&(s=cs(i));let c=await Va(await Ce(e));if(gC(s,c),!c&&s.run_id&&s.skill){let{runStateFromDocument:l}=await Promise.resolve().then(()=>(qu(),WR));c=l(s),c&&n&&(await rs(await Ce(e),c),Hj(i),o=!0)}return o&&n&&await $e(r,i.toString(),{containedRoot:e}),tn(cs(i),c)}async function $r(e,t,n={}){let r=await ue(e,{defaultFileName:Au});if(await tc(e,fr.basename(r))===null){let i=new nc.Document({change_id:Wj()});wC(i,{...t,unknownKeys:t.unknownKeys??[]}),tn(cs(i),t.run??null);let s=await it(e),o=await ur(s),c=await St(o,`classic-changes/${i.get("change_id")}`,{label:"Classic initial Run"});t.run&&await rs(c,t.run),await $e(r,i.toString(),{containedRoot:e,exclusive:!0,beforeCommit:n.beforeCommit});return}return sn(e,()=>Kj(e,t,n))}async function Kj(e,t,n){let r=await ue(e),i=await tc(e,fr.basename(r));if(i!==null&&Et(i))throw new Error("Classic managed Run state is owned by the SDK; compat writes are not allowed");let s=await gh(r);s.has("change_id")||s.set("change_id",fr.basename(await Ce(e)));let o=s.get("check_epoch")??0;if(typeof o=="number"&&o>(t.classic?.checkEpoch??0))throw new Error("Classic state changed during this operation; reload before retrying");wC(s,{...t,unknownKeys:t.unknownKeys??[]}),tn(cs(s),t.run??null);let c=await tc(e,fr.basename(r)),l=s.toString();if(c===l){await n.beforeCommit?.(),t.run?await rs(await Ce(e),t.run):await Ua(await Ce(e));return}let f=await Ce(e),a=fr.join(f,ec);await $e(a,JSON.stringify({schema:"comet.classic.state-transaction.v1",stateFile:fr.basename(r),beforeYaml:c,afterYaml:l,beforeRun:await Va(await Ce(e)),afterRun:t.run}),{containedRoot:f});try{t.run?await rs(await Ce(e),t.run):await Ua(await Ce(e)),await $e(r,l,{containedRoot:e,beforeCommit:n.beforeCommit})}catch(d){throw await hC(e).catch(()=>{}),d}await lr(a,{containedRoot:f}).catch(()=>{})}function zj(e){if(e!=="build"&&e!=="verify")throw new Error(`Invalid command check scope: '${String(e)}'`)}function Jj(e,t="."){if(t.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=ed.resolve(e),r=ed.resolve(n,t);if(r!==n&&!r.startsWith(n+ed.sep))throw new Error(`Command check cwd must resolve within the project root: '${t}'`);return ed.relative(n,r).replaceAll("\\","/")||"."}async function Gj(e,t,n,r){let s=[...(await wh(t,n.trajectoryRef)).events].reverse().find(o=>o.runId===n.runId&&o.type==="checkpoint"&&o.data?.kind==="classic-accepted-verify-check")?.data;if(!s||s.reportRef!==r.verificationReport||s.verifiedAt!==r.verifiedAt||typeof s.sequence!="number"||typeof s.checkEpoch!="number"||s.checkEpoch>(r.checkEpoch??0))throw new Error("原 Verify 缺少对应报告的接受证据;保留原批准和工作,只诊断缺失记录");return{...s,sequence:s.sequence,actionId:s.actionId,reportSha256:s.reportSha256,checkEpoch:s.checkEpoch,manifestHash:typeof s.manifestHash=="string"?s.manifestHash:null,candidateManifestRef:typeof s.candidateManifestRef=="string"?s.candidateManifestRef:null,candidateManifestHash:typeof s.candidateManifestHash=="string"?s.candidateManifestHash:null,bindingHash:j(s)}}async function vC(e,t,n,r){if(r.archived||!(await wh(t,n.trajectoryRef)).events.some(s=>s.runId===n.runId&&s.type==="checkpoint"&&s.data?.kind==="classic-accepted-verify-check"))return;await Gj(e,t,n,r);let i=await Xj(e,t,n,"verify");if(!i.record)throw new Error(`原验收检查不再适用:${i.reason??"结果缺失"};由当前 Agent 只补受影响检查,保留报告和批准`)}async function wh(e,t){let n=await Tr(e,t);return{events:n,maximumSequence:n.reduce((r,i)=>Math.max(r,i.sequence),0)}}async function Yj(e,t,n,r){zj(r);let{events:i}=await wh(t,n.trajectoryRef);for(let s of i.reverse()){if(s.runId!==n.runId)continue;if(s.type==="command_checks_invalidated"&&(!Array.isArray(s.data?.scopes)||s.data.scopes.includes(r)))return null;if(s.data?.scope!==r)continue;if(["command_check_started","command_check_consumed"].includes(s.type))return null;if(!["command_check_executed","command_check_recorded"].includes(s.type))continue;let o=s.data;if(typeof o.command!="string"||!Number.isInteger(o.exitCode)||typeof o.cwd!="string")return null;let c;try{c=Jj(e,o.cwd)}catch{continue}return{...o,sequence:s.sequence,timestamp:s.timestamp,runId:n.runId,scope:r,cwd:c,...s.type==="command_check_executed"?{provenance:"runtime"}:{}}}return null}async function Xj(e,t,n,r){let i=await Yj(e,t,n,r);if(!i)return{record:null,reason:"没有本阶段的完整检查报告;请在 Agent 平台执行并提交实际结果"};if(!i.provenance)return{record:null,reason:"旧手工声明没有平台检查来源;请核对后提交实际结果"};if(i.exitCode!==0)return{record:null,reason:"检查未通过,退出码 "+i.exitCode};let s=(await $t(t,{migrate:!1})).classic;return s?.phase!=="archive"&&(i.checkEpoch??0)!==(s?.checkEpoch??0)?{record:null,reason:"报告属于较早阶段,请由 Agent 核对当前工作后提交结果"}:{record:i}}Wa();kt();Fa();Sn();rn();Sn();Ht();Xi();ve();rn();import{promises as Qj}from"node:fs";import{AsyncLocalStorage as Zj}from"node:async_hooks";import zn from"node:path";var us="comet.change-owner.v1",bC=["native","classic-full","classic-hotfix","classic-tweak"],eD=rt("changeOwnerRuntimeRoots",e=>dh(e)),RC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Jn(e,t,n="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!RC.test(t))throw new Error(`Invalid change name: ${t}`);return`${n==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function vh(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Change runtime owner must be a JSON object");let r=e,i=r.schema===us&&r.workflow===t&&r.change===n,s=r.format==="compat"&&Object.keys(r).length===4,o=r.format==="sdk"&&Object.keys(r).length===6&&r.runId===n&&(typeof r.application=="string"&&/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(r.application)&&!bC.includes(r.application)||(t==="native"?r.application==="native":r.application==="classic-full"||r.application==="classic-hotfix"||r.application==="classic-tweak"));if(!i||!s&&!o)throw new Error(`Invalid change runtime owner for ${t}/${n}`);return r}async function td(e,t,n,r){let i;try{({bytes:i}=await ce(e,t,Number.MAX_SAFE_INTEGER,{label:"change runtime owner"}))}catch(o){if(o.code==="ENOENT")return null;throw o}let s;try{s=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new Error(`Invalid change runtime owner JSON for ${n}/${r}`)}return vh(s,n,r)}function CC(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function SC(e,t){return Jn(e,t),`change-owner-records/${e}/${t}.json`}async function kh(e,t,n){let r;try{r=await ce(e,SC(t,n),Number.MAX_SAFE_INTEGER,{label:"canonical change runtime owner",bigint:!0})}catch(s){if(s.code==="ENOENT")return null;throw s}let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r.bytes))}catch{throw new Error(`Invalid canonical Runtime owner for ${t}/${n}`)}return{owner:vh(i,t,n),identity:CC(r.stat)}}async function EC(e,t,n){let r=await Na(e,"change owner bindings"),i=async c=>{try{let{stat:l}=await r.stat(Jn(t,n,c));return CC(l)}catch(l){if(l.code==="ENOENT")return null;throw l}},s=await i("active"),o=await i("history");return await r.finish({allowDirectoryContentChanges:!0}),{active:s,history:o}}async function tD(e,t,n=!1){let r=await EC(e,t.workflow,t.change);if(r.active===null&&r.history===null)return;if(r.active!==null&&r.history!==null)throw new Error(`Conflicting or missing Runtime owner for ${t.workflow}/${t.change}`);let i=n?null:await kh(e,t.workflow,t.change);if(i?.identity&&i.identity===(r.active??r.history))return;let s=SC(t.workflow,t.change);await St(e,zn.posix.dirname(s),{label:"canonical change runtime owners"});let o=Jn(t.workflow,t.change,r.active?"active":"history");try{await fR(zn.join(e,o),zn.join(e,s),{containedRoot:e})}catch(c){if(!["ENOTSUP","EOPNOTSUPP"].includes(c.code??""))throw c}}async function nD(e,t,n){let r;try{r=await kh(e,t,n)}catch(s){if(s instanceof Ot&&s.reason==="changed")return null;throw s}if(!r?.identity)return null;let i=await EC(e,t,n);return i.active===r.identity&&i.history===null||i.history===r.identity&&i.active===null?r:null}var ls=new Zj,AC=cr("verifiedOwnerBatchResults",()=>new Map),xC=(e,t,n)=>`${JSON.stringify([e,t])}\0${n}`;async function IC(e){let t=ls.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??eD(e)}async function _C(e,t,n=!1){let r=ls.getStore();if(r?.active&&e.every(s=>r.roots.has(s)))return t();let i={roots:new Set(e),runtimeRoots:new Map,owners:new Map,projects:new Set,active:!0};try{let s=await ls.run(i,()=>ci(()=>n?eR(t):t())),o=AC();for(let c of o.keys())[...i.projects].some(l=>c.startsWith(l+"\0"))&&o.delete(c);for(let[c,l]of i.owners)o.set(c,l);return s}finally{i.active=!1}}async function yh(e,t,n){let r=await nD(e,t,n);return r?r.owner:_C([e],async()=>{let i=await td(e,Jn(t,n),t,n),s=await td(e,Jn(t,n,"history"),t,n);if(i&&s)throw new Error(`Conflicting active and history Runtime owners for ${t}/${n}`);return i??s})}async function yi(e,t,n,r={}){if(Jn(t,n),!r.readOnly)return ls.run(null,()=>ci(async()=>yh(await xr(e),t,n)));let[i,s]=await IC(e),o=zn.parse(i).root,l=(await M(o,zn.relative(o,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await yh(i,t,n):null,f=s?await yh(s,t,n):null;if(l&&f&&JSON.stringify(Object.entries(l).sort())!==JSON.stringify(Object.entries(f).sort()))throw new Error(`Conflicting current and legacy Runtime owners for ${t}/${n}`);return l??f}async function kC(e,t,n,r={}){let i=await yi(e,t,n,r),s=i?.format==="sdk"?i:null,o=ls.getStore();return r.readOnly&&o?.active&&o.owners.set(xC(e,t,n),s),s}async function pr(e,t,n,r={}){if(!r.readOnly||ls.getStore()?.active)return kC(e,t,n,r);let i=AC(),s=xC(e,t,n);if(i.has(s))return i.get(s);let o=kC(e,t,n,r).catch(c=>{throw i.get(s)===o&&i.delete(s),c});return i.set(s,o),o}async function rD(e,t,n,r=!1){Jn(t,"validate");let i=n.readOnly?await IC(e):[await xr(e)],s=async()=>{let o={active:new Set,history:new Set};for(let c of i)for(let l of["active","history"]){let f=zn.parse(c).root,a=zn.posix.dirname(Jn(t,"validate",l)),d=await M(f,zn.relative(f,zn.join(c,a)).replaceAll("\\","/"),{label:`${t} ${l} change runtime owners`,expected:"directory"});if(!d.exists)continue;let p=await Qj.readdir(d.target,{withFileTypes:!0});for(let u of p){if(u.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(u.name))continue;if(t==="classic"&&l==="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(u.isFile()&&h.test(u.name)||u.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(u.name))continue}if(!u.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${u.name}`);let m=u.name.slice(0,-5);if(!u.isFile()||!RC.test(m))throw new Error(`Invalid ${t} change runtime owner entry: ${u.name}`);o[l].add(m)}}return o};return r?s():_C(i,s)}var Q4=rt("changeOwnerPartitions",rD);async function iD(e,t,n){return Zb(),ls.run(null,()=>ci(async()=>{let r=await ur(e);return Jn(t.workflow,t.change),n(r)}))}async function PC(e,t,n={}){let r=Jn(t.workflow,t.change),i=vh(t,t.workflow,t.change);return iD(e,i,async s=>{if(await td(s,Jn(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 St(s,zn.posix.dirname(r),{label:"change runtime owner directory"});try{await $e(zn.join(s,...r.split("/")),`${JSON.stringify(i)}
|
|
172
|
+
`,{containedRoot:s,exclusive:!0,requireAtomicPublication:!0})}catch(c){if(c.code!=="EEXIST")throw c;let l=await td(s,r,t.workflow,t.change);if(JSON.stringify(l)!==JSON.stringify(i))throw new Error(`Change ${t.workflow}/${t.change} is already bound to another Runtime`,{cause:c})}return(n.canonical||await kh(s,t.workflow,t.change))&&await tD(s,i),i})}function rc(e,t,n={}){return PC(e,t,n)}function OC(e,t){return PC(e,t)}kt();ds();import{execFileSync as Rh}from"child_process";var cD=Rt(Pt(),1);Sn();Qe();Ht();ve();function st(e){let t={cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0};try{let n=mr(()=>Rh("git",["rev-parse","--abbrev-ref","HEAD"],t).trim());if(n&&n!=="HEAD")return n}catch{}try{return mr(()=>Rh("git",["symbolic-ref","--quiet","--short","HEAD"],t).trim())||null}catch{return null}}var d6=cr("liveGitBranch",e=>st(e));function on(e){try{return mr(()=>Rh("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 f6=cr("isGitWorkTree",e=>on(e)),lD=["current","branch","worktree"];function vo(e){return lD.includes(e)}function _n(e){return vo(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{randomUUID as vD}from"node:crypto";import{types as uD}from"node:util";import{createHash as dD}from"node:crypto";var qC=new WeakMap,LC=new WeakMap;function WC(e,t){let n=e!==null&&typeof e=="object"&&t?.(e);if(n){let i=LC.get(e);if(i!==void 0)return i}let r=JSON.stringify(e);return n&&r.length<=64*1024&&LC.set(e,r),r}function fD(e,t,n){let r=new WeakMap,i=w=>{let k=r.get(w);if(k)return k;let y=Array.isArray(w)?[...w]:{...w};return r.set(w,y),y},s=i(e),o=[],c=[],l=[],f=new Map,a=new Map,d=new WeakMap,p=new Map,u=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 y=WC(w,n);return k=f.get(y),k===void 0&&(k=o.length,o.push(w),f.set(y,k)),w&&typeof w=="object"&&d.set(w,k),k},g=w=>{let k=m.get(w);if(k!==void 0)return k;let y=w.base===void 0?void 0:g(w.base),R=c.length;return c.push({...y===void 0?{}:{base:y},entries:w.entries.map(([C,A])=>[C,h(A)]),removed:[...w.removed]}),m.set(w,R),R};for(let w of t){let k=s,y=e;for(let K of w.path.slice(0,-1)){y=y[K];let L=i(y);Object.defineProperty(k,K,{value:L,enumerable:!0,writable:!0,configurable:!0}),k=L}let R=w.path.at(-1),C=k[R];if(!C||typeof C!="object"||Array.isArray(C))continue;if(n?.(C)){let K=qC.get(C);if(!K){let L=C,Z=u.get(w.group),Y=Object.entries(L),fe=Z?Y.filter(([Le,I])=>!Object.hasOwn(Z.source,Le)||h(Z.source[Le])!==h(I)):Y,z=Z?Object.keys(Z.source).filter(Le=>!Object.hasOwn(L,Le)):[],ne=Z&&fe.length+z.length<Y.length;K={...ne?{base:Z.node}:{},entries:ne?fe:Y,removed:ne?z:[]},qC.set(C,K)}u.set(w.group,{source:C,node:K}),l.push({path:w.path,map:g(K)}),Object.defineProperty(k,R,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let A=new Map;for(let[K,L]of Object.entries(C)){let Z=L&&typeof L=="object"?d.get(L):void 0;if(Z===void 0){let Y=WC(L,n);Z=f.get(Y),Z===void 0&&(Z=o.length,o.push(L),f.set(Y,Z)),L&&typeof L=="object"&&d.set(L,Z)}A.set(K,Z)}let q=JSON.stringify([...A]),D=a.get(q);if(D===void 0){let K=p.get(w.group),L=[...A].filter(([fe,z])=>K?.entries.get(fe)!==z),Z=K?[...K.entries.keys()].filter(fe=>!A.has(fe)):[],Y=K&&L.length+Z.length<A.size;D=c.length,c.push({...Y?{base:K.id}:{},entries:Y?L:[...A],removed:Y?Z:[]}),a.set(q,D)}p.set(w.group,{id:D,entries:A}),l.push({path:w.path,map:D}),Object.defineProperty(k,R,{value:{},enumerable:!0,writable:!0,configurable:!0})}return l.length?{record:s,pool:{version:1,values:o,maps:c,bindings:l}}:{record:s}}function pD(){let e=[],t=s=>s===null?0:e[s].height,n=(s,o,c,l)=>{let f=e.length;return e.push({key:s,value:o,left:c,right:l,height:1+Math.max(t(c),t(l))}),f},r=(s,o,c,l)=>{if(t(c)>t(l)+1){let f=e[c];if(t(f.left)>=t(f.right))return n(f.key,f.value,f.left,n(s,o,f.right,l));let a=e[f.right];return n(a.key,a.value,n(f.key,f.value,f.left,a.left),n(s,o,a.right,l))}if(t(l)>t(c)+1){let f=e[l];if(t(f.right)>=t(f.left))return n(f.key,f.value,n(s,o,c,f.left),f.right);let a=e[f.left];return n(a.key,a.value,n(s,o,c,a.left),n(f.key,f.value,a.right,f.right))}return n(s,o,c,l)},i=(s,o,c)=>{if(s===null)return c===void 0?null:n(o,c,null,null);let l=e[s];if(o<l.key){let a=i(l.left,o,c);return a===l.left?s:r(l.key,l.value,a,l.right)}if(o>l.key){let a=i(l.right,o,c);return a===l.right?s:r(l.key,l.value,l.left,a)}if(c!==void 0)return c===l.value?s:n(o,c,l.left,l.right);if(l.left===null)return l.right;if(l.right===null)return l.left;let f=e[l.right];for(;f.left!==null;)f=e[f.left];return r(f.key,f.value,l.left,i(l.right,f.key,void 0))};return{nodes:e,set:i}}function FC(e){let{nodes:t,set:n}=pD(),r=[];for(let l of e.maps){let f=l.base===void 0?null:r[l.base];for(let a of l.removed)f=n(f,a,void 0);for(let[a,d]of l.entries)f=n(f,a,d);r.push(f)}let i=[],s=new Map,o=l=>{if(l===null)return null;let f=s.get(l);if(f!==void 0)return f;let a=t[l],d=o(a.left),p=o(a.right),u=i.length;return i.push({...a,left:d,right:p}),s.set(l,u),u},c=r.map(o);return{version:3,values:e.values,nodes:i,maps:c,bindings:e.bindings}}function HC(e,t,n){let r=fD(e,t,n);return{record:r.record,...r.pool?{pool:FC(r.pool)}:{}}}var jr=new WeakMap,ic=new WeakMap;function*nd(e,t=e.root){if(t===null)return;let n=e.pool.nodes[t];yield*nd(e,n.left),yield[n.key,e.pool.values[n.value]],yield*nd(e,n.right)}function mD(e){let t=r=>{let i=e.root;for(;i!==null;){let s=e.pool.nodes[i];if(r===s.key)return s.value;i=r<s.key?s.left:s.right}},n=new Proxy({},{ownKeys:()=>[...nd(e)].map(([r])=>r),get:(r,i)=>typeof i=="string"?e.pool.values[t(i)??-1]:void 0,has:(r,i)=>typeof i=="string"&&t(i)!==void 0,getOwnPropertyDescriptor:(r,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 jr.set(n,e),n}var Ze=e=>{throw new Error(e)},ko=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;function BC(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return Ze("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(s=>!["version","values","maps","bindings"].includes(s))&&Ze("JSON 引用池字段无效"),i.maps.forEach((s,o)=>{(!s||!Array.isArray(s.entries)||!Array.isArray(s.removed)||s.base!==void 0&&!ko(s.base,o)||Object.keys(s).some(l=>!["base","entries","removed"].includes(l)))&&Ze("JSON 映射引用无效");let c=new Set;for(let l of s.removed)(typeof l!="string"||c.has(l))&&Ze("JSON 删除键无效"),c.add(l);for(let l of s.entries)(!Array.isArray(l)||l.length!==2||typeof l[0]!="string"||!ko(l[1],i.values.length)||c.has(l[0]))&&Ze("JSON 值引用无效"),c.add(l[0])}),BC(FC(i))}let n=e;if(n.version!==3||!Array.isArray(n.nodes)||Object.keys(n).some(i=>!["version","values","maps","bindings","nodes"].includes(i)))return Ze("JSON 引用池版本或字段无效");let r=[];return n.nodes.forEach((i,s)=>{(!i||typeof i.key!="string"||!ko(i.value,n.values.length)||![i.left,i.right].every(l=>l===null||ko(l,s))||Object.keys(i).some(l=>!["key","value","left","right","height"].includes(l)))&&Ze("JSON 树引用无效");let o=i.left===null?void 0:n.nodes[i.left],c=i.right===null?void 0:n.nodes[i.right];(i.height!==1+Math.max(o?.height??0,c?.height??0)||Math.abs((o?.height??0)-(c?.height??0))>1||i.left!==null&&r[i.left].max>=i.key||i.right!==null&&r[i.right].min<=i.key)&&Ze("JSON 树顺序或平衡无效"),r.push({min:i.left===null?i.key:r[i.left].min,max:i.right===null?i.key:r[i.right].max})}),n.maps.some(i=>i!==null&&!ko(i,n.nodes.length))&&Ze("JSON 映射根无效"),n}function hD(e,t){let n=(m,h=0,g=new Set)=>{if(h>64&&Ze("JSON 数据嵌套过深"),!(m===null||typeof m=="string"||typeof m=="boolean"||typeof m=="number"&&Number.isFinite(m))){if(typeof m!="object"||m===null||uD.isProxy(m)||g.has(m))return Ze("JSON 数据无效");Object.getPrototypeOf(m)!==Object.prototype&&Object.getPrototypeOf(m)!==null&&!Array.isArray(m)&&Ze("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))&&Ze("JSON 数据不能包含访问器"),n(k.value,h+1,g)}Array.isArray(m)&&Object.keys(m).length!==m.length&&Ze("JSON 数组不能稀疏"),g.delete(m)}};n(e),n(t);let r=BC(structuredClone(t)),i=structuredClone(e),s={validatedNodes:r.nodes.length,validationActions:0,validationResultMaps:0,validationEntries:0,validationMaterializedEntries:0,materializedMaps:0,materializedEntries:0,hashBytes:0,logicalHashBytes:0},o=new Set,c=new Set,l=new Set,f=new Map;for(let m of r.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))||!ko(m.map,r.maps.length)||Object.keys(m).some(k=>!["path","map"].includes(k)))&&Ze("JSON 池绑定无效");let h=JSON.stringify(m.path);(c.has(h)||m.path.some((k,y)=>o.has(JSON.stringify(m.path.slice(0,y+1)))))&&Ze("JSON 池绑定重复或重叠"),o.add(h),m.path.forEach((k,y)=>c.add(JSON.stringify(m.path.slice(0,y+1))));let g=i;for(let k of m.path.slice(0,-1))(!g||typeof g!="object"||!Object.hasOwn(g,k))&&Ze("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)&&Ze("JSON 池绑定必须替换空对象"),Object.defineProperty(g,w,{value:mD({pool:r,root:r.maps[m.map],stats:s,checked:l,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=jr.get(m),w=y=>{if(y===null)return 0;let R=d.get(y);if(R!==void 0)return R;let C=r.nodes[y],A=Math.max(1+p(r.values[C.value]),w(C.left),w(C.right));return d.set(y,A),A},k=g?w(g.root):Object.values(m).reduce((y,R)=>Math.max(y,1+p(R)),0);return a.set(m,k),k};p(i)>64&&Ze("JSON 逻辑数据嵌套超过 64 层"),sc(r),sc(i);let u=m=>{if(!(!m||typeof m!="object"||jr.has(m)||ic.has(m))){ic.set(m,s);for(let h of Object.values(m))u(h)}};return u(i),{value:i,stats:s,materialize:(m=[])=>an(m.reduce((h,g)=>h?.[g],i)),hash:()=>jt(i)}}function sc(e){let t=new WeakSet,n=r=>{if(!(!r||typeof r!="object"||jr.has(r)||t.has(r))){t.add(r);for(let i of Object.values(r))n(i);Object.freeze(r)}};return n(e),e}function an(e){if(e===null||typeof e!="object")return e;let t=jr.get(e);if(t){t.stats.materializedMaps++;let n=[...nd(t)];return t.stats.materializedEntries+=n.length,Object.fromEntries(n.map(([r,i])=>[r,an(i)]))}return Array.isArray(e)?e.map(an):Object.fromEntries(Object.entries(e).map(([n,r])=>[n,an(r)]))}function rd(e,t){let n=jr.get(e);if(!n){for(let[i,s]of Object.entries(e))t(i,s);return}n.stats.validationResultMaps++;let r=i=>{if(i===null||n.checked.has(i))return;let s=n.pool.nodes[i];r(s.left),t(s.key,n.pool.values[s.value]),n.stats.validationEntries++,r(s.right),n.checked.add(i)};r(n.root)}function id(e,t,n){let r=jr.get(e),i=(c,l)=>{let f=l.sequence;return t.get(f)!==c&&Ze("WorkflowRun 结果来源不一致"),f};if(!r){for(let[c,l]of Object.entries(e))i(c,l)>=n&&Ze("WorkflowRun 结果序号无效");return}let s=r.origins.get(t);s||(s=new Map,r.origins.set(t,s));let o=c=>{if(c===null)return 0;let l=s.get(c);if(l!==void 0)return l;let f=r.pool.nodes[c],a=Math.max(i(f.key,r.pool.values[f.value]),o(f.left),o(f.right));return s.set(c,a),a};o(r.root)>=n&&Ze("WorkflowRun 结果序号无效")}function gD(e){return Object.keys(e).sort((t,n)=>{let r=i=>String(Number(i))===i&&Number.isInteger(Number(i))&&Number(i)>=0&&Number(i)<4294967295;return r(t)||r(n)?r(t)&&r(n)?Number(t)-Number(n):r(t)?-1:1:t<n?-1:t>n?1:0})}var MC=new WeakMap;function jt(e,t={}){let n=dD("sha256"),r=e&&typeof e=="object"?ic.get(e):void 0,i=f=>{if(!f||typeof f!="object")return;let a=jr.get(f)?.stats??ic.get(f);if(a)return a;for(let d of Object.values(f)){let p=i(d);if(p)return p}};r??=i(e);let s=r&&t.cachePrefixes!==!1?MC.get(r):void 0;r&&!s&&t.cachePrefixes!==!1&&(s={root:{hash:n.copy(),next:new Map},size:0},MC.set(r,s));let o=s?.root,c=f=>{let a=Buffer.byteLength(f);r&&(r.logicalHashBytes+=a);let d=o?.next.get(f);if(d){n=d.hash.copy(),o=d;return}if(n.update(f),r&&(r.hashBytes+=a),o&&s&&s.size<1e5){let p={hash:n.copy(),next:new Map};o.next.set(f,p),o=p,s.size++}else o=void 0},l=f=>{if(f===null||typeof f!="object"){c(JSON.stringify(f));return}if(Array.isArray(f)){c("["),f.forEach((a,d)=>{d&&c(","),l(a)}),c("]");return}c("{"),gD(f).forEach((a,d)=>{d&&c(","),c(JSON.stringify(a)+":"),l(f[a])}),c("}")};return l(e),n.digest("hex")}function oc(e){return ic.get(e)??jr.get(e)?.stats}function sd(e,t,n=!0){let r=hD(e,t);return n?r.materialize():r.value}function yt(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new b("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function hr(e){return xn(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function Ch(e,t,n){if(t!==e.attempt||n!==e.inputHash)throw new b("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Sh(e){return["succeeded","failed","cancelled"].includes(e.status)}function VC(e){return UC(e,e.input)}function UC(e,t,n){for(let o of["id","runId","stepId","type"])yt(e[o],o);e.ref!==void 0&&yt(e.ref,"ref");let r=e.attempt??1;if(!Number.isSafeInteger(r)||r<1)throw new b("INVALID_ACTION","attempt 必须是正安全整数");let i=e.retry??"manual";if(!["idempotent","reconcile","manual"].includes(i))throw new b("INVALID_ACTION","retry 策略无效");let s=e.requiredCapabilities??[];for(let o of s)yt(o,"requiredCapabilities");return{protocolVersion:1,id:e.id,runId:e.runId,stepId:e.stepId,type:e.type,...e.ref===void 0?{}:{ref:e.ref},attempt:r,input:t,inputHash:n??j(t),status:"pending",retry:i,requiredCapabilities:[...new Set(s)],receipts:[],reconciliations:[]}}function KC(e,t){Ch(e,t.attempt,t.inputHash),yt(t.executorId,"executorId"),yt(t.token,"token"),t.sessionId!==void 0&&yt(t.sessionId,"sessionId");let n={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if(j(e.claim)===j(n)&&e.status==="running")return hr(e);throw new b("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new b("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...hr(e),claim:n,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Eh(e,t){if(t=od(t),yt(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new b("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&yt(t.event,"event");let n=j(t),r=e.rejectedOutcomes?.find(s=>s.outcome.outcomeId===t.outcomeId);if(r)throw j(r.outcome)!==n?new b("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken"):new b(r.code,r.reason);let i=e.receipts.find(s=>s.outcomeId===t.outcomeId);if(i){if(i.hash!==n)throw new b("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken");return{action:hr(e),duplicate:!0}}if(Ch(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new b("STALE_ACTION","结果不属于当前 Action");if(Sh(e))throw new b("ACTION_TERMINAL","Action 已终止,不能接受新结果");if(!e.claim||!["running","unknown"].includes(e.status))throw new b("ACTION_NOT_RUNNING","Action 尚未交给执行者");if(t.claimToken!==e.claim.token)throw new b("STALE_ACTION","结果不属于当前执行者的领取记录");for(let s of t.artifacts??[])if(yt(s.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(s.sha256))throw new b("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...hr(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:n}]},duplicate:!1}}function zC(e,t){if(yt(t,"reason"),!["running","unknown"].includes(e.status))throw new b("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...hr(e),status:"unknown",reason:t}}function JC(e,t){if(e.rejectedOutcomes?.some(r=>r.outcome.attempt===e.attempt))throw new b("OUTCOME_ALREADY_RECORDED","当前执行尝试已记录结果,不能声明未执行并重试;请核对并修正同一次结果");if(!["failed","unknown"].includes(e.status))throw new b("ACTION_ACTIVE","仅失败或待核对的 Action 可以重试");if((e.retry!=="idempotent"||e.status==="unknown")&&!t)throw new b("RECONCILIATION_REQUIRED","先核对外部执行结果;不能把断连当作未执行");let n=hr(e);if(t){if(t.resolution!=="not-executed"||t.evidence===null)throw new b("RECONCILIATION_REQUIRED","需要明确的未执行结论与核对证据");n.reconciliations.push({attempt:e.attempt,resolution:"not-executed",evidence:Ye(t.evidence)})}if(!Number.isSafeInteger(e.attempt+1))throw new b("INVALID_ACTION","执行尝试次数溢出");return n.attempt+=1,n.status="pending",delete n.claim,delete n.executionOrigin,delete n.executionStop,delete n.cancellation,delete n.outcome,delete n.reason,n}function Ah(e,t){return yt(t,"reason"),Sh(e)?hr(e):{...hr(e),status:"cancelled",reason:t}}function GC(e,t){Gn(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let n of["actionId","inputHash","claimToken","evidence"])yt(t[n],n);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new b("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(Ch(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new b("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function xh(e,t){if(GC(e,t),e.status!=="cancelled")throw new b("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&j(e.cancellation)!==j(t))throw new b("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...hr(e),cancellation:structuredClone(t)}}function Ih(e,t){if(GC(e,t),!Sh(e))throw new b("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&j(e.executionStop)!==j(t))throw new b("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...hr(e),executionStop:structuredClone(t)}}function Gn(e,t,n="INVALID_ACTION"){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(r=>!t.includes(r)))throw new b(n,"执行记录包含无效结构或未知字段")}function od(e){let t=Ye(e),n=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(Gn(t,[...n,"artifacts","summary","event"],"INVALID_OUTCOME"),n.some(r=>!Object.hasOwn(t,r)))throw new b("INVALID_OUTCOME","执行结果缺少身份、绑定或 output 字段");for(let r of["actionId","inputHash","claimToken","outcomeId"])if(typeof t[r]!="string"||!t[r].trim()||t[r].length>4096)throw new b("INVALID_OUTCOME",`${r} 必须是非空字符串`);if(typeof t.attempt!="number"||!Number.isSafeInteger(t.attempt)||t.attempt<1)throw new b("INVALID_OUTCOME","attempt 必须是正安全整数");if(t.status!=="succeeded"&&t.status!=="failed")throw new b("INVALID_OUTCOME","status 必须是 succeeded 或 failed");for(let r of["summary","event"])if(t[r]!==void 0&&(typeof t[r]!="string"||!t[r].trim()||t[r].length>4096))throw new b("INVALID_OUTCOME",`${r} 必须是非空字符串`);if(t.artifacts!==void 0){if(!Array.isArray(t.artifacts))throw new b("INVALID_OUTCOME","产物引用必须是数组");for(let r of t.artifacts)if(Gn(r,["uri","sha256"],"INVALID_OUTCOME"),typeof r.uri!="string"||!r.uri.trim()||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new b("INVALID_OUTCOME","产物引用必须包含 URI 与 SHA-256")}return t}function ad(e,t){if(Gn(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 b("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Action 协议版本");if(!Array.isArray(e.requiredCapabilities)||!Array.isArray(e.receipts)||!Array.isArray(e.reconciliations))throw new b("INVALID_ACTION","Action 缺少能力、结果或核对记录");let n=e,r=UC(n,n.input,t);if(n.inputHash!==r.inputHash||n.retry!==r.retry||n.attempt!==r.attempt)throw new b("INVALID_ACTION","Action 输入绑定或执行参数不完整");if(!["pending","running","unknown","succeeded","failed","cancelled"].includes(n.status))throw new b("INVALID_ACTION","Action 状态无效");if(n.reason!==void 0&&yt(n.reason,"reason"),n.claim!==void 0&&(Gn(n.claim,["executorId","sessionId","token"]),yt(n.claim.executorId,"executorId"),yt(n.claim.token,"token"),n.claim.sessionId!==void 0&&yt(n.claim.sessionId,"sessionId")),n.status==="pending"&&n.claim||["running","unknown","succeeded","failed"].includes(n.status)&&!n.claim)throw new b("INVALID_ACTION","Action 状态与执行归属不一致");if(n.executionOrigin!==void 0&&(Gn(n.executionOrigin,["workflow"]),Gn(n.executionOrigin.workflow,["id","version","hash"]),yt(n.executionOrigin.workflow.id,"executionOrigin.workflow.id"),yt(n.executionOrigin.workflow.version,"executionOrigin.workflow.version"),!n.claim||!/^[a-f0-9]{64}$/u.test(n.executionOrigin.workflow.hash)))throw new b("INVALID_ACTION","执行来源必须包含领取记录和有效工作流摘要");n.cancellation!==void 0&&xh({...n,input:null},n.cancellation),n.executionStop!==void 0&&Ih({...n,input:null},n.executionStop);let i=new Set;for(let o of n.receipts){if(Gn(o,["outcomeId","hash"]),yt(o.outcomeId,"outcomeId"),!/^[a-f0-9]{64}$/.test(o.hash)||i.has(o.outcomeId))throw new b("INVALID_ACTION","结果记录的标识或摘要无效");i.add(o.outcomeId)}if(n.rejectedOutcomes!==void 0){if(!Array.isArray(n.rejectedOutcomes))throw new b("INVALID_ACTION","Action 的拒绝结果记录必须是数组");let o=new Set;for(let c of n.rejectedOutcomes){if(Gn(c,["outcome","code","reason"]),!["OUTPUT_INVALID","OUTCOME_REJECTED","OUTCOME_PROCESSING_ERROR"].includes(c.code))throw new b("INVALID_ACTION","Action 的拒绝结果代码无效");if(typeof c.reason!="string"||!c.reason.trim())throw new b("INVALID_ACTION","Action 的拒绝结果缺少原因");let l=od(c.outcome),f=n.receipts.find(a=>a.outcomeId===l.outcomeId);if(o.has(l.outcomeId)||!f||f.hash!==j(l)||l.actionId!==n.id||l.inputHash!==n.inputHash||l.attempt>n.attempt||l.attempt===n.attempt&&n.claim?.token!==l.claimToken)throw new b("INVALID_ACTION","Action 的拒绝结果与当前执行记录不一致");o.add(l.outcomeId)}}let s=new Set;for(let o of n.reconciliations){if(Gn(o,["attempt","resolution","evidence"]),!Number.isSafeInteger(o.attempt)||o.attempt<1||o.attempt>=n.attempt||s.has(o.attempt)||o.resolution!=="not-executed"||o.evidence===null||o.evidence===void 0)throw new b("INVALID_ACTION","核对记录与执行尝试不一致");s.add(o.attempt)}if(n.status==="succeeded"||n.status==="failed"){if(Gn(n.outcome,["actionId","attempt","inputHash","claimToken","outcomeId","status","output","artifacts","summary","event"]),n.outcome.status!==n.status||n.outcome.output===void 0)throw new b("INVALID_ACTION","终态 Action 缺少匹配的结果");let o=n.receipts.find(c=>c.outcomeId===n.outcome.outcomeId);if(!o||o.hash!==j(n.outcome))throw new b("INVALID_ACTION","终态结果与已接受摘要不一致");Eh({...n,input:null,status:"running",receipts:[]},n.outcome)}else if(n.outcome!==void 0)throw new b("INVALID_ACTION","非执行终态不能保存当前执行结果");return n}function _h(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}var ZC=new WeakSet,eS=new WeakSet,Ph=new WeakSet,YC=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"];function Q(e){throw new b("INVALID_RUN",e)}function ut(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Q(`${t} 必须是 JSON 对象`),e}function Pn(e,t,n){for(let r of Object.keys(e))t.includes(r)||Q(`${n} 包含不支持的字段:${r}`)}function Te(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&Q(`${t} 必须是非空字符串且不超过 4096 字符`),e}function bo(e,t,n=0){return(!Number.isSafeInteger(e)||e<n)&&Q(`${t} 必须是大于等于 ${n} 的安全整数`),e}function vi(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&Q(`${t} 必须是 SHA-256 摘要`),e}function XC(e,t,n=!1){let r=ut(e,t);Pn(r,n?["id","version","hash"]:["id","version"],t);let i={id:Te(r.id,`${t}.id`),version:Te(r.version,`${t}.version`)};return n&&(i.hash=vi(r.hash,`${t}.hash`)),i}function ac(e,t,n){let r=ut(e,t);if(!n&&xn(r)&&eS.has(r))return r;let i=(s,o)=>{Te(s,`${t} step id`);let c=ut(o,`${t}.${s}`);Pn(c,["sequence","value"],`${t}.${s}`),(!Object.hasOwn(c,"sequence")||!Object.hasOwn(c,"value"))&&Q(`${t}.${s} 缺少 sequence 或 value`),bo(c.sequence,`${t}.${s}.sequence`,1)};if(n)n.visitResults(r,i);else for(let[s,o]of Object.entries(r))i(s,o);return r}function QC(e,t,n){let r=ut(e,t);return Pn(r,["from","to","results","activation"],t),(!Object.hasOwn(r,"from")||!Object.hasOwn(r,"to")||!Object.hasOwn(r,"results"))&&Q(`${t} 缺少 from、to 或 results`),{from:r.from===null?null:Te(r.from,`${t}.from`),to:Te(r.to,`${t}.to`),results:ac(r.results,`${t}.results`,n),...Object.hasOwn(r,"activation")?{activation:r.activation}:{}}}function cd(e,t,n,r){let i=`${t}:`;e.startsWith(i)||Q(`${n} 不属于当前 Run`);let s=e.slice(i.length);/^[1-9][0-9]*$/.test(s)||Q(`${n} 的步骤序号无效`);let o=Number(s);return(!Number.isSafeInteger(o)||o>r)&&Q(`${n} 的步骤序号超出 Run 范围`),o}function wD(e,t,n,r){let i=ut(e,"Wait");Pn(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)||Q(`Wait 缺少 ${d}`);let s=Te(i.id,"Wait.id"),o=Te(i.stepId,"Wait.stepId"),c=bo(i.sequence,"Wait.sequence",1);(c>n||cd(s,t,"Wait.id",n)!==c)&&Q("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||Q("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&Q("Wait.choices 必须是非空数组");let l=i.choices.map(d=>Te(d,"Wait.choices"));new Set(l).size!==l.length&&Q("Wait.choices 不能重复");let f=vi(i.proposalHash,"Wait.proposalHash");j(i.proposal)!==f&&Q("Wait.proposal 与 proposalHash 不一致");let a={id:s,stepId:o,sequence:c,status:i.status,proposal:i.proposal,proposalHash:f,choices:l,results:ac(i.results,"Wait.results",r)};if(i.decision!==void 0){let d=ut(i.decision,"Wait.decision");Pn(d,["id","choice","proposalHash","reason"],"Wait.decision"),d.reason!==void 0&&!_h(d.reason)&&Q("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let p={id:Te(d.id,"Wait.decision.id"),choice:Te(d.choice,"Wait.decision.choice"),proposalHash:vi(d.proposalHash,"Wait.decision.proposalHash"),...d.reason===void 0?{}:{reason:d.reason}};(i.status!=="resolved"||!l.includes(p.choice)||p.proposalHash!==f)&&Q("Wait.decision 与 Wait 状态、选择或提案不一致"),a.decision=p}else i.status==="resolved"&&Q("已解决的 Wait 必须保存对应 decision");return a}function yD(e,t,n,r){let i=ut(e,"EvidenceWait");Pn(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let s=Te(i.id,"EvidenceWait.id"),o=bo(i.sequence,"EvidenceWait.sequence",1);(o>n||cd(s,t,"EvidenceWait.id",n)!==o)&&Q("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||Q("EvidenceWait.status 无效");let c={id:s,stepId:Te(i.stepId,"EvidenceWait.stepId"),sequence:o,kind:Te(i.kind,"EvidenceWait.kind"),status:i.status,results:ac(i.results,"EvidenceWait.results",r)};if(i.receipt!==void 0){let l=ut(i.receipt,"EvidenceWait.receipt");Pn(l,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),c.receipt={ref:Te(l.ref,"EvidenceWait.receipt.ref"),contentHash:vi(l.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:Te(l.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let l=ut(i.invalidation,"EvidenceWait.invalidation");Pn(l,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),c.invalidation={ref:Te(l.ref,"EvidenceWait.invalidation.ref"),contentHash:vi(l.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:Te(l.submissionId,"EvidenceWait.invalidation.submissionId"),reason:Te(l.reason,"EvidenceWait.invalidation.reason")}}return(c.status==="resolved"!=!!c.receipt||c.status==="invalidated"!=!!c.invalidation)&&Q("EvidenceWait.receipt 与状态不一致"),c}function Ro(e,t){let n=ut(Ye(e),"WorkflowRun");return ud(n,t)}function tS(e,t){if(e&&typeof e=="object"&&Ph.has(e)&&xn(e)){let n=e;return t!==void 0&&n.runId!==t&&Q("WorkflowRun.runId 与存储键不一致"),n}return In(e),nS(ud(ut(structuredClone(e),"WorkflowRun"),t))}function cc(e,t,n){return ud(ut(e,"WorkflowRun"),t,void 0,n)}function ld(e,t){return In(e),ud(ut(e,"WorkflowRun"),e.runId,t&&Ph.has(t)&&xn(t)?t:void 0),nS(e)}function nS(e){as(e),Ph.add(e);for(let n of e.actions)ZC.add(n);let t=n=>eS.add(n);for(let n of Object.values(e.actionContexts))t(n.results);for(let n of e.waits)t(n.results);for(let n of e.evidenceWaits??[])t(n.results);for(let n of e.ready)t(n.results);for(let n of Object.values(e.joins))for(let r of Object.values(n))for(let i of r)t(i.results);return t(e.outputs),e}function ud(e,t,n,r){Pn(e,YC,"WorkflowRun");for(let I of YC.filter(V=>V!=="reason"&&V!=="state"&&V!=="evidenceWaits"&&V!=="initialStateHash"&&V!=="commands"))Object.hasOwn(e,I)||Q(`WorkflowRun 缺少 ${I}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new b("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=Te(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&Q("WorkflowRun.runId 与存储键不一致");let s=bo(e.revision,"WorkflowRun.revision",1),o=bo(e.sequence,"WorkflowRun.sequence"),c=XC(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||Q("WorkflowRun.status 无效"),e.reason!==void 0&&Te(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||Q("WorkflowRun 缺少 input");let l=ut(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(l).length===0&&Q("WorkflowRun.definitionHashes 不能为空");for(let[I,V]of Object.entries(l)){let re;try{re=JSON.parse(I)}catch{Q("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(re)||re.length!==2||typeof re[0]!="string"||typeof re[1]!="string"||JSON.stringify(re)!==I)&&Q("WorkflowRun.definitionHashes 包含非规范的工作流引用"),vi(V,`WorkflowRun.definitionHashes.${I}`)}let f=JSON.stringify([c.id,c.version]);l[f]!==c.hash&&Q("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&Q("WorkflowRun.lineage 必须是最多 32 层的数组");let a=e.lineage.map(I=>Te(I,"WorkflowRun.lineage"));(new Set(a).size!==a.length||a.includes(i))&&Q("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&Q("WorkflowRun.actions 和 waits 必须是数组");let d=e.actions.map(I=>{let V;try{V=I&&typeof I=="object"&&ZC.has(I)&&xn(I)?I:ad(I,r?.hash(I.input))}catch(re){if(re instanceof b&&re.code==="UNSUPPORTED_PROTOCOL")throw re;Q(`WorkflowRun.actions 包含无效 Action:${re.message}`)}return V.executionOrigin&&V.executionOrigin.workflow.id!==c.id&&Q("Action 执行来源不属于当前工作流"),V.runId!==i&&Q(`Action ${V.id} 不属于当前 Run`),new Set(V.requiredCapabilities).size!==V.requiredCapabilities.length&&Q(`Action ${V.id} 的 requiredCapabilities 不能重复`),V}),p=new Map(d.map(I=>[I.id,I]));e.commands!==void 0&&!Array.isArray(e.commands)&&Q("WorkflowRun.commands 必须是数组");let u=e.commands?.map(I=>{let V=ut(I,"WorkflowRun.commands item");Pn(V,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let re={id:Te(V.id,"WorkflowRun.commands.id"),name:Te(V.name,"WorkflowRun.commands.name"),inputHash:vi(V.inputHash,"WorkflowRun.commands.inputHash"),actionId:Te(V.actionId,"WorkflowRun.commands.actionId")};return p.has(re.actionId)||Q("WorkflowRun.commands 指向不存在的 Action"),re});u&&new Set(u.map(I=>I.id)).size!==u.length&&Q("WorkflowRun.commands 标识不能重复");let m=e.waits.map(I=>wD(I,i,o,r));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&Q("WorkflowRun.evidenceWaits 必须是数组");let h=e.evidenceWaits?.map(I=>yD(I,i,o,r))??[],g=new Map;for(let I of d){let V=cd(I.id,i,"Action.id",o);g.has(V)&&Q("WorkflowRun 的步骤序号不能重复"),g.set(V,I.stepId)}for(let I of m)g.has(I.sequence)&&Q("WorkflowRun 的步骤序号不能重复"),g.set(I.sequence,I.stepId);for(let I of h)g.has(I.sequence)&&Q("WorkflowRun 的步骤序号不能重复"),g.set(I.sequence,I.stepId);g.size!==o&&Q("WorkflowRun.sequence 与已激活步骤数量不一致");let w=ut(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(w).length!==d.length&&Q("WorkflowRun.actionContexts 必须与 actions 一一对应");let k=new Map,y=n?new Map([...n.actions.map(I=>[n.actionContexts[I.id].sequence,I.stepId]),...n.waits.map(I=>[I.sequence,I.stepId]),...(n.evidenceWaits??[]).map(I=>[I.sequence,I.stepId])]):void 0;if(n&&y&&n.runId===i&&[...y].every(([I,V])=>g.get(I)===V)){let I=(V,re)=>k.set(V,Math.min(k.get(V)??1/0,re));for(let V of Object.values(n.actionContexts))I(V.results,V.sequence);for(let V of n.waits)I(V.results,V.sequence);for(let V of n.evidenceWaits??[])I(V.results,V.sequence);for(let V of n.ready)I(V.results,n.sequence+1);for(let V of Object.values(n.joins))for(let re of Object.values(V))for(let He of re)I(He.results,n.sequence+1);I(n.outputs,n.sequence+1)}let R=new Map;function C(I,V){let re=V??o+1;if(r){r.validateOrigins(I,g,re);return}let He=k.get(I);if(!(He!==void 0&&re>=He&&xn(I))&&!((R.get(I)??1/0)<=re)){R.set(I,re);for(let[E,$]of Object.entries(I))($.sequence>=(V??o+1)||g.get($.sequence)!==E)&&Q(`WorkflowRun 结果 ${E} 的序号或来源不一致`)}}for(let I of d){Object.hasOwn(w,I.id)||Q(`Action ${I.id} 缺少上下文`);let V=ut(w[I.id],`actionContexts.${I.id}`);Pn(V,["sequence","results"],`actionContexts.${I.id}`);let re=bo(V.sequence,`actionContexts.${I.id}.sequence`,1);re!==cd(I.id,i,"Action.id",o)&&Q(`Action ${I.id} 的上下文序号不一致`);let He=ac(V.results,`actionContexts.${I.id}.results`,r);C(He,re)}for(let I of m)C(I.results,I.sequence);for(let I of h)C(I.results,I.sequence);Array.isArray(e.ready)||Q("WorkflowRun.ready 必须是数组");let A=e.ready.map(I=>QC(I,"WorkflowRun.ready token",r));for(let I of A)C(I.results);let q=ut(e.joins,"WorkflowRun.joins"),D=Object.fromEntries(Object.entries(q).map(([I,V])=>{Te(I,"WorkflowRun.joins step id");let re=ut(V,`WorkflowRun.joins.${I}`),He=Object.fromEntries(Object.entries(re).map(([E,$])=>{Te(E,"WorkflowRun.joins parent id"),Array.isArray($)||Q(`WorkflowRun.joins.${I}.${E} 必须是数组`);let T=$.map(F=>{let U=QC(F,`WorkflowRun.joins.${I}.${E}`,r);return(U.to!==I||U.from!==E)&&Q(`WorkflowRun.joins.${I}.${E} 包含错误来源的 token`),C(U.results),U});return[E,T]}));return[I,He]})),K=ac(e.outputs,"WorkflowRun.outputs",r);C(K),Array.isArray(e.children)||Q("WorkflowRun.children 必须是数组");let L=e.children.map(I=>{let V=ut(I,"WorkflowRun.children item");Pn(V,["actionId","runId","workflow"],"WorkflowRun.children item");let re=XC(V.workflow,"WorkflowRun.children.workflow"),He=Te(V.actionId,"WorkflowRun.children.actionId"),E=Te(V.runId,"WorkflowRun.children.runId"),$=p.get(He);return(!$||$.type!=="child_workflow"||$.ref!==`${re.id}@${re.version}`||E!==`child-${j(He)}`||!Object.hasOwn(l,JSON.stringify([re.id,re.version])))&&Q("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:He,runId:E,workflow:re}});(new Set(L.map(I=>I.actionId)).size!==L.length||d.filter(I=>I.type==="child_workflow").length!==L.length)&&Q("每个子工作流 Action 必须恰好对应一个 Child Run");let Y=d.some(I=>["pending","running","unknown"].includes(I.status)),fe=m.some(I=>I.status==="pending"),z=h.some(I=>I.status==="pending"),ne=Object.values(D).some(I=>Object.values(I).some(V=>V.length>0));return e.status==="running"&&!Y&&A.length===0&&Q("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(Y||!fe&&!z&&!ne||A.length>0)&&Q("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(Y||fe||z||ne||A.length>0)&&Q("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&Q(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:s,workflow:c,definitionHashes:l,...e.initialStateHash===void 0?{}:{initialStateHash:vi(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:o,actions:d,...u===void 0?{}:{commands:u},actionContexts:w,waits:m,...e.evidenceWaits===void 0?{}:{evidenceWaits:h},ready:A,joins:D,outputs:K,children:L,lineage:a,...e.reason===void 0?{}:{reason:e.reason}}}var rS=new WeakMap;async function Co(e,t){let n=await(e.readProjection?e.readProjection(t):e.read(t));if(!n)throw new b("RUN_NOT_FOUND",`找不到工作流实例:${t}`);oc(n)||(In(n),n=structuredClone(n),sc(n));let r="run"in n?n.run:n;if(!r||r.runId!==n.runId||r.revision!==n.revision)throw new b("INVALID_RUN","Run 与存储 envelope 身份不一致");let i;try{i=cc(r,t,{hash:jt,visitResults:rd,validateOrigins:id})}catch(c){throw c instanceof b?c:new b("INVALID_RUN",c instanceof Error?c.message:String(c))}sc(i);let s=oc(n);s&&(s.validationActions=i.actions.length,s.validationMaterializedEntries=s.materializedEntries);let o=e.queryScope??rS.get(e);return o||(o=vD(),rS.set(e,o)),Object.freeze({record:n,run:i,scope:o,stats:s,materialize:(c=[])=>an(c.reduce((l,f)=>l?.[f],i)),hash:()=>jt(i)})}var ki=e=>{throw new b("INVALID_REQUEST",e)};function Oh(e,t){let{run:n,scope:r}=e;["current","summary","history","action","artifact"].includes(t.view)||ki("query.view 无效");let i={runId:n.runId,revision:n.revision,status:n.status,workflow:n.workflow,sequence:n.sequence},s={actions:n.actions.length,waits:n.waits.length,evidenceWaits:n.evidenceWaits?.length??0},o=n.actions.filter(p=>["pending","running","unknown"].includes(p.status)||p.status==="cancelled"&&p.claim&&!p.executionStop&&!p.cancellation);if(t.view==="summary")return an({...i,history:s,pending:{actions:o.length,waits:n.waits.filter(p=>p.status==="pending").length,evidenceWaits:(n.evidenceWaits??[]).filter(p=>p.status==="pending").length}});if(t.view==="current")return an({...i,input:n.input,...n.state===void 0?{}:{state:n.state},...n.reason===void 0?{}:{reason:n.reason},actions:o,waits:n.waits.filter(p=>p.status==="pending"),evidenceWaits:(n.evidenceWaits??[]).filter(p=>p.status==="pending"),outputs:n.outputs,history:s});if(t.view==="action"||t.view==="artifact"){let p=n.actions.find(h=>h.id===t.actionId);if(p||ki("query.actionId 不属于当前 Run"),t.view==="action")return an({...i,action:p,context:n.actionContexts[p.id]});let u=(p.outcome?.artifacts??[]).map(h=>({...h,artifactId:j({actionId:p.id,...h})})),m=t.artifactId===void 0?u:u.filter(h=>h.artifactId===t.artifactId);return t.artifactId!==void 0&&!m.length&&ki("query.artifactId 不属于所选 Action"),an({...i,actionId:p.id,artifacts:m})}let c=t.limit??25;(!Number.isSafeInteger(c)||c<1||c>100)&&ki("query.limit 必须在 1–100 之间");let l=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(l)||ki("query.filter 无效");let f=j({scope:r,runId:n.runId,revision:n.revision,filter:l}),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(u=>!["binding","offset"].includes(u)))&&ki("query.cursor 与当前存储、版本或筛选不匹配"),a=p.offset}catch{ki("query.cursor 无效或已经过期")}let d=[...l==="all"||l==="actions"?n.actions.map((p,u)=>({kind:"action",sequence:n.actionContexts[p.id].sequence,path:["actions",String(u)]})):[],...l==="all"||l==="waits"?n.waits.map((p,u)=>({kind:"wait",sequence:p.sequence,path:["waits",String(u)]})):[],...l==="all"||l==="evidenceWaits"?(n.evidenceWaits??[]).map((p,u)=>({kind:"evidenceWait",sequence:p.sequence,path:["evidenceWaits",String(u)]})):[]].sort((p,u)=>u.sequence-p.sequence);return a>d.length&&ki("query.cursor 超出历史范围"),{...an(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 xw}from"node:crypto";import{types as Pw}from"node:util";var Sw=Rt(UA(),1);var at=Rt(Lg(),1),mF=(()=>{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"},n=new RegExp("^[0-9a-f]{40}(?:[0-9a-f]{24})?$","u"),r=at.default.default??at.default;function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.action===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"action"},message:"must have required property 'action'"};a===null?a=[p]:a.push(p),d++}if(s.targetBranch===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};a===null?a=[p]:a.push(p),d++}if(s.commit===void 0){let p={instancePath:o,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 s)if(!(p==="action"||p==="commit"||p==="prUrl"||p==="remote"||p==="targetBranch")){let u={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[u]:a.push(u),d++}if(s.action!==void 0){let p=s.action;if(!(p==="local"||p==="push"||p==="pr")){let u={instancePath:o+"/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=[u]:a.push(u),d++}}if(s.commit!==void 0){let p=s.commit;if(typeof p=="string"){if(!n.test(p)){let u={instancePath:o+"/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=[u]:a.push(u),d++}}else{let u={instancePath:o+"/commit",schemaPath:"#/properties/commit/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.prUrl!==void 0){let p=s.prUrl;if(typeof p=="string"){if(r(p)<1){let u={instancePath:o+"/prUrl",schemaPath:"#/properties/prUrl/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/prUrl",schemaPath:"#/properties/prUrl/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.remote!==void 0){let p=s.remote;if(typeof p=="string"){if(r(p)<1){let u={instancePath:o+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.targetBranch!==void 0){let p=s.targetBranch;if(typeof p=="string"){if(r(p)<1){let u={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}}else{let p={instancePath:o,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})(),hF=(()=>{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"},n=Object.prototype.hasOwnProperty,r=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[u]:a.push(u),d++}if(s.language===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[u]:a.push(u),d++}if(s.phase===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[u]:a.push(u),d++}if(s.contextCompression===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[u]:a.push(u),d++}if(s.buildMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[u]:a.push(u),d++}if(s.buildPause===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[u]:a.push(u),d++}if(s.subagentDispatch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[u]:a.push(u),d++}if(s.tddMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[u]:a.push(u),d++}if(s.reviewMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[u]:a.push(u),d++}if(s.isolation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[u]:a.push(u),d++}if(s.boundBranch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[u]:a.push(u),d++}if(s.verifyMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[u]:a.push(u),d++}if(s.baseRef===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[u]:a.push(u),d++}if(s.designDoc===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[u]:a.push(u),d++}if(s.plan===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[u]:a.push(u),d++}if(s.verifyResult===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[u]:a.push(u),d++}if(s.verifyFailures===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[u]:a.push(u),d++}if(s.verificationReport===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[u]:a.push(u),d++}if(s.branchStatus===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[u]:a.push(u),d++}if(s.createdAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[u]:a.push(u),d++}if(s.verifiedAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[u]:a.push(u),d++}if(s.archiveConfirmation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[u]:a.push(u),d++}if(s.archived===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[u]:a.push(u),d++}if(s.directOverride===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[u]:a.push(u),d++}if(s.handoffContext===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[u]:a.push(u),d++}if(s.handoffHash===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[u]:a.push(u),d++}if(s.classicProfile===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[u]:a.push(u),d++}if(s.classicMigration===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[u]:a.push(u),d++}for(let u in s)if(!n.call(t.properties,u)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(s.archiveConfirmation!==void 0){let u=s.archiveConfirmation;if(!(u===null||u==="pending"||u==="confirmed")){let m={instancePath:o+"/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(s.archived!==void 0&&typeof s.archived!="boolean"){let u={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition!==void 0){let u=s.autoTransition;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/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(s.baseRef!==void 0){let u=s.baseRef;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.boundBranch!==void 0){let u=s.boundBranch;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.branchStatus!==void 0){let u=s.branchStatus;if(!(u===null||u==="pending"||u==="handled")){let m={instancePath:o+"/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(s.buildMode!==void 0){let u=s.buildMode;if(!(u===null||u==="subagent-driven-development"||u==="executing-plans"||u==="direct"||u==="autonomous")){let m={instancePath:o+"/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(s.buildPause!==void 0){let u=s.buildPause;if(!(u===null||u==="plan-ready")){let m={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"};a===null?a=[m]:a.push(m),d++}}if(s.checkEpoch!==void 0){let u=s.checkEpoch;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.classicMigration!==void 0){let u=s.classicMigration;if(!(u===null||u===1)){let m={instancePath:o+"/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(s.classicProfile!==void 0){let u=s.classicProfile;if(!(u===null||u==="full"||u==="hotfix"||u==="tweak")){let m={instancePath:o+"/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(s.contextCompression!==void 0){let u=s.contextCompression;if(!(u===null||u==="off"||u==="beta")){let m={instancePath:o+"/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(s.createdAt!==void 0){let u=s.createdAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.designDoc!==void 0){let u=s.designDoc;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.directOverride!==void 0){let u=s.directOverride;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/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(s.handoffContext!==void 0){let u=s.handoffContext;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.handoffHash!==void 0){let u=s.handoffHash,m=d,h=!1,g=d;if(u!==null){let w={instancePath:o+"/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 u=="string"){if(!r.test(u)){let y={instancePath:o+"/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=[y]:a.push(y),d++}}else{let y={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[y]:a.push(y),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(s.isolation!==void 0){let u=s.isolation;if(!(u===null||u==="current"||u==="branch"||u==="worktree")){let m={instancePath:o+"/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(s.language!==void 0){let u=s.language;if(!(u===null||u==="en"||u==="zh-CN")){let m={instancePath:o+"/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(s.phase!==void 0){let u=s.phase;if(!(u==="open"||u==="design"||u==="build"||u==="verify"||u==="archive")){let m={instancePath:o+"/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(s.plan!==void 0){let u=s.plan;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.reviewMode!==void 0){let u=s.reviewMode;if(!(u===null||u==="off"||u==="standard"||u==="thorough")){let m={instancePath:o+"/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(s.subagentDispatch!==void 0){let u=s.subagentDispatch;if(!(u===null||u==="confirmed")){let m={instancePath:o+"/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(s.tddMode!==void 0){let u=s.tddMode;if(!(u===null||u==="tdd"||u==="direct")){let m={instancePath:o+"/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(s.verificationReport!==void 0){let u=s.verificationReport;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.verifiedAt!==void 0){let u=s.verifiedAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.verifyFailures!==void 0){let u=s.verifyFailures;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.verifyMode!==void 0){let u=s.verifyMode;if(!(u===null||u==="light"||u==="full")){let m={instancePath:o+"/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(s.verifyResult!==void 0){let u=s.verifyResult;if(!(u==="pending"||u==="pass"||u==="fail")){let m={instancePath:o+"/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(s.workflow!==void 0&&s.workflow!=="full"){let u={instancePath:o+"/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=[u]:a.push(u),d++}}else{let u={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}return i.errors=a,d===0}return e.exports})(),gF=(()=>{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"},n=Object.prototype.hasOwnProperty,r=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[u]:a.push(u),d++}if(s.language===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[u]:a.push(u),d++}if(s.phase===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[u]:a.push(u),d++}if(s.contextCompression===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[u]:a.push(u),d++}if(s.buildMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[u]:a.push(u),d++}if(s.buildPause===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[u]:a.push(u),d++}if(s.subagentDispatch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[u]:a.push(u),d++}if(s.tddMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[u]:a.push(u),d++}if(s.reviewMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[u]:a.push(u),d++}if(s.isolation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[u]:a.push(u),d++}if(s.boundBranch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[u]:a.push(u),d++}if(s.verifyMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[u]:a.push(u),d++}if(s.baseRef===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[u]:a.push(u),d++}if(s.designDoc===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[u]:a.push(u),d++}if(s.plan===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[u]:a.push(u),d++}if(s.verifyResult===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[u]:a.push(u),d++}if(s.verifyFailures===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[u]:a.push(u),d++}if(s.verificationReport===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[u]:a.push(u),d++}if(s.branchStatus===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[u]:a.push(u),d++}if(s.createdAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[u]:a.push(u),d++}if(s.verifiedAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[u]:a.push(u),d++}if(s.archiveConfirmation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[u]:a.push(u),d++}if(s.archived===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[u]:a.push(u),d++}if(s.directOverride===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[u]:a.push(u),d++}if(s.handoffContext===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[u]:a.push(u),d++}if(s.handoffHash===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[u]:a.push(u),d++}if(s.classicProfile===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[u]:a.push(u),d++}if(s.classicMigration===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[u]:a.push(u),d++}for(let u in s)if(!n.call(t.properties,u)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(s.archiveConfirmation!==void 0){let u=s.archiveConfirmation;if(!(u===null||u==="pending"||u==="confirmed")){let m={instancePath:o+"/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(s.archived!==void 0&&typeof s.archived!="boolean"){let u={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition!==void 0){let u=s.autoTransition;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/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(s.baseRef!==void 0){let u=s.baseRef;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.boundBranch!==void 0){let u=s.boundBranch;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.branchStatus!==void 0){let u=s.branchStatus;if(!(u===null||u==="pending"||u==="handled")){let m={instancePath:o+"/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(s.buildMode!==void 0){let u=s.buildMode;if(!(u===null||u==="subagent-driven-development"||u==="executing-plans"||u==="direct"||u==="autonomous")){let m={instancePath:o+"/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(s.buildPause!==void 0){let u=s.buildPause;if(!(u===null||u==="plan-ready")){let m={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"};a===null?a=[m]:a.push(m),d++}}if(s.checkEpoch!==void 0){let u=s.checkEpoch;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.classicMigration!==void 0){let u=s.classicMigration;if(!(u===null||u===1)){let m={instancePath:o+"/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(s.classicProfile!==void 0){let u=s.classicProfile;if(!(u===null||u==="full"||u==="hotfix"||u==="tweak")){let m={instancePath:o+"/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(s.contextCompression!==void 0){let u=s.contextCompression;if(!(u===null||u==="off"||u==="beta")){let m={instancePath:o+"/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(s.createdAt!==void 0){let u=s.createdAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.designDoc!==void 0){let u=s.designDoc;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.directOverride!==void 0){let u=s.directOverride;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/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(s.handoffContext!==void 0){let u=s.handoffContext;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.handoffHash!==void 0){let u=s.handoffHash,m=d,h=!1,g=d;if(u!==null){let w={instancePath:o+"/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 u=="string"){if(!r.test(u)){let y={instancePath:o+"/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=[y]:a.push(y),d++}}else{let y={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[y]:a.push(y),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(s.isolation!==void 0){let u=s.isolation;if(!(u===null||u==="current"||u==="branch"||u==="worktree")){let m={instancePath:o+"/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(s.language!==void 0){let u=s.language;if(!(u===null||u==="en"||u==="zh-CN")){let m={instancePath:o+"/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(s.phase!==void 0){let u=s.phase;if(!(u==="open"||u==="design"||u==="build"||u==="verify"||u==="archive")){let m={instancePath:o+"/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(s.plan!==void 0){let u=s.plan;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.reviewMode!==void 0){let u=s.reviewMode;if(!(u===null||u==="off"||u==="standard"||u==="thorough")){let m={instancePath:o+"/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(s.subagentDispatch!==void 0){let u=s.subagentDispatch;if(!(u===null||u==="confirmed")){let m={instancePath:o+"/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(s.tddMode!==void 0){let u=s.tddMode;if(!(u===null||u==="tdd"||u==="direct")){let m={instancePath:o+"/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(s.verificationReport!==void 0){let u=s.verificationReport;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.verifiedAt!==void 0){let u=s.verifiedAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.verifyFailures!==void 0){let u=s.verifyFailures;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.verifyMode!==void 0){let u=s.verifyMode;if(!(u===null||u==="light"||u==="full")){let m={instancePath:o+"/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(s.verifyResult!==void 0){let u=s.verifyResult;if(!(u==="pending"||u==="pass"||u==="fail")){let m={instancePath:o+"/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(s.workflow!==void 0){let u=s.workflow;if(!(u==="hotfix"||u==="full")){let m={instancePath:o+"/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 u={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}return i.errors=a,d===0}return e.exports})(),wF=(()=>{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"},n=Object.prototype.hasOwnProperty,r=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[u]:a.push(u),d++}if(s.language===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[u]:a.push(u),d++}if(s.phase===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[u]:a.push(u),d++}if(s.contextCompression===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[u]:a.push(u),d++}if(s.buildMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[u]:a.push(u),d++}if(s.buildPause===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[u]:a.push(u),d++}if(s.subagentDispatch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[u]:a.push(u),d++}if(s.tddMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[u]:a.push(u),d++}if(s.reviewMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[u]:a.push(u),d++}if(s.isolation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[u]:a.push(u),d++}if(s.boundBranch===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[u]:a.push(u),d++}if(s.verifyMode===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[u]:a.push(u),d++}if(s.baseRef===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[u]:a.push(u),d++}if(s.designDoc===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[u]:a.push(u),d++}if(s.plan===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[u]:a.push(u),d++}if(s.verifyResult===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[u]:a.push(u),d++}if(s.verifyFailures===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[u]:a.push(u),d++}if(s.verificationReport===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[u]:a.push(u),d++}if(s.branchStatus===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[u]:a.push(u),d++}if(s.createdAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[u]:a.push(u),d++}if(s.verifiedAt===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[u]:a.push(u),d++}if(s.archiveConfirmation===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[u]:a.push(u),d++}if(s.archived===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[u]:a.push(u),d++}if(s.directOverride===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[u]:a.push(u),d++}if(s.handoffContext===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[u]:a.push(u),d++}if(s.handoffHash===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[u]:a.push(u),d++}if(s.classicProfile===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[u]:a.push(u),d++}if(s.classicMigration===void 0){let u={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[u]:a.push(u),d++}for(let u in s)if(!n.call(t.properties,u)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(s.archiveConfirmation!==void 0){let u=s.archiveConfirmation;if(!(u===null||u==="pending"||u==="confirmed")){let m={instancePath:o+"/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(s.archived!==void 0&&typeof s.archived!="boolean"){let u={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[u]:a.push(u),d++}if(s.autoTransition!==void 0){let u=s.autoTransition;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/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(s.baseRef!==void 0){let u=s.baseRef;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.boundBranch!==void 0){let u=s.boundBranch;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.branchStatus!==void 0){let u=s.branchStatus;if(!(u===null||u==="pending"||u==="handled")){let m={instancePath:o+"/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(s.buildMode!==void 0){let u=s.buildMode;if(!(u===null||u==="subagent-driven-development"||u==="executing-plans"||u==="direct"||u==="autonomous")){let m={instancePath:o+"/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(s.buildPause!==void 0){let u=s.buildPause;if(!(u===null||u==="plan-ready")){let m={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"};a===null?a=[m]:a.push(m),d++}}if(s.checkEpoch!==void 0){let u=s.checkEpoch;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.classicMigration!==void 0){let u=s.classicMigration;if(!(u===null||u===1)){let m={instancePath:o+"/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(s.classicProfile!==void 0){let u=s.classicProfile;if(!(u===null||u==="full"||u==="hotfix"||u==="tweak")){let m={instancePath:o+"/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(s.contextCompression!==void 0){let u=s.contextCompression;if(!(u===null||u==="off"||u==="beta")){let m={instancePath:o+"/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(s.createdAt!==void 0){let u=s.createdAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.designDoc!==void 0){let u=s.designDoc;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.directOverride!==void 0){let u=s.directOverride;if(typeof u!="boolean"&&u!==null){let m={instancePath:o+"/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(s.handoffContext!==void 0){let u=s.handoffContext;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.handoffHash!==void 0){let u=s.handoffHash,m=d,h=!1,g=d;if(u!==null){let w={instancePath:o+"/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 u=="string"){if(!r.test(u)){let y={instancePath:o+"/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=[y]:a.push(y),d++}}else{let y={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[y]:a.push(y),d++}var p=w===d;h=h||p}if(h)d=m,a!==null&&(m?a.length=m:a=null);else{let w={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};a===null?a=[w]:a.push(w),d++}}if(s.isolation!==void 0){let u=s.isolation;if(!(u===null||u==="current"||u==="branch"||u==="worktree")){let m={instancePath:o+"/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(s.language!==void 0){let u=s.language;if(!(u===null||u==="en"||u==="zh-CN")){let m={instancePath:o+"/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(s.phase!==void 0){let u=s.phase;if(!(u==="open"||u==="design"||u==="build"||u==="verify"||u==="archive")){let m={instancePath:o+"/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(s.plan!==void 0){let u=s.plan;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.reviewMode!==void 0){let u=s.reviewMode;if(!(u===null||u==="off"||u==="standard"||u==="thorough")){let m={instancePath:o+"/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(s.subagentDispatch!==void 0){let u=s.subagentDispatch;if(!(u===null||u==="confirmed")){let m={instancePath:o+"/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(s.tddMode!==void 0){let u=s.tddMode;if(!(u===null||u==="tdd"||u==="direct")){let m={instancePath:o+"/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(s.verificationReport!==void 0){let u=s.verificationReport;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.verifiedAt!==void 0){let u=s.verifiedAt;if(typeof u!="string"&&u!==null){let m={instancePath:o+"/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(s.verifyFailures!==void 0){let u=s.verifyFailures;if(!(typeof u=="number"&&!(u%1)&&!isNaN(u)&&isFinite(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};a===null?a=[m]:a.push(m),d++}if(typeof u=="number"&&isFinite(u)&&(u<0||isNaN(u))){let m={instancePath:o+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};a===null?a=[m]:a.push(m),d++}}if(s.verifyMode!==void 0){let u=s.verifyMode;if(!(u===null||u==="light"||u==="full")){let m={instancePath:o+"/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(s.verifyResult!==void 0){let u=s.verifyResult;if(!(u==="pending"||u==="pass"||u==="fail")){let m={instancePath:o+"/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(s.workflow!==void 0){let u=s.workflow;if(!(u==="tweak"||u==="full")){let m={instancePath:o+"/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 u={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}return i.errors=a,d===0}return e.exports})(),yF=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={additionalProperties:!1,properties:{archiveDirectory:{minLength:1,type:"string"}},required:["archiveDirectory"],type:"object"},n=at.default.default??at.default;function r(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.archiveDirectory===void 0){let d={instancePath:s,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:s,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(n(d)<1){let p={instancePath:s+"/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:s+"/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:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return r.errors=f,a===0}return e.exports})(),vF=(()=>{let e={exports:{}};e.exports=s,e.exports.default=s;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"},n=new RegExp("^[0-9a-f]{40}(?:[0-9a-f]{24})?$","u"),r=new RegExp("^[0-9a-f]{64}$","u"),i=at.default.default??at.default;function s(o,{instancePath:c="",parentData:l,parentDataProperty:f,rootData:a=o}={}){let d=null,p=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.deliveryAction===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"deliveryAction"},message:"must have required property 'deliveryAction'"};d===null?d=[u]:d.push(u),p++}if(o.targetBranch===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};d===null?d=[u]:d.push(u),p++}if(o.verifiedBranch===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedBranch"},message:"must have required property 'verifiedBranch'"};d===null?d=[u]:d.push(u),p++}if(o.baseCommit===void 0){let u={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseCommit"},message:"must have required property 'baseCommit'"};d===null?d=[u]:d.push(u),p++}for(let u in o)if(!(u==="baseCommit"||u==="deliveryAction"||u==="deliveryPaths"||u==="prBaseBranch"||u==="remote"||u==="remoteIdentity"||u==="targetBranch"||u==="verifiedBranch")){let m={instancePath:c,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};d===null?d=[m]:d.push(m),p++}if(o.baseCommit!==void 0){let u=o.baseCommit;if(typeof u=="string"){if(!n.test(u)){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(o.deliveryAction!==void 0){let u=o.deliveryAction;if(!(u==="local"||u==="push"||u==="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(o.deliveryPaths!==void 0){let u=o.deliveryPaths;if(Array.isArray(u)){let m=u.length;for(let h=0;h<m;h++){let g=u[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(o.prBaseBranch!==void 0){let u=o.prBaseBranch;if(typeof u=="string"){if(i(u)<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(o.remote!==void 0){let u=o.remote;if(typeof u=="string"){if(i(u)<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(o.remoteIdentity!==void 0){let u=o.remoteIdentity;if(typeof u=="string"){if(!r.test(u)){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(o.targetBranch!==void 0){let u=o.targetBranch;if(typeof u=="string"){if(i(u)<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(o.verifiedBranch!==void 0){let u=o.verifiedBranch;if(typeof u=="string"){if(i(u)<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 u={instancePath:c,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[u]:d.push(u),p++}return s.errors=d,p===0}return e.exports})(),kF=(()=>{let e={exports:{}};e.exports=n,e.exports.default=n;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 n(r,{instancePath:i="",parentData:s,parentDataProperty:o,rootData:c=r}={}){let l=null,f=0;if(r&&typeof r=="object"&&!Array.isArray(r)){if(r.buildMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};l===null?l=[a]:l.push(a),f++}if(r.tddMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};l===null?l=[a]:l.push(a),f++}if(r.reviewMode===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};l===null?l=[a]:l.push(a),f++}if(r.isolation===void 0){let a={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};l===null?l=[a]:l.push(a),f++}for(let a in r)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"};l===null?l=[d]:l.push(d),f++}if(r.boundBranch!==void 0){let a=r.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"};l===null?l=[d]:l.push(d),f++}}if(r.buildMode!==void 0){let a=r.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"};l===null?l=[d]:l.push(d),f++}}if(r.directOverride!==void 0&&typeof r.directOverride!="boolean"){let a={instancePath:i+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};l===null?l=[a]:l.push(a),f++}if(r.isolation!==void 0){let a=r.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"};l===null?l=[d]:l.push(d),f++}}if(r.reviewMode!==void 0){let a=r.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"};l===null?l=[d]:l.push(d),f++}}if(r.subagentDispatch!==void 0){let a=r.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"};l===null?l=[d]:l.push(d),f++}}if(r.tddMode!==void 0){let a=r.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"};l===null?l=[d]:l.push(d),f++}}}else{let a={instancePath:i,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};l===null?l=[a]:l.push(a),f++}return n.errors=l,f===0}return e.exports})(),bF=(()=>{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"},n=at.default.default??at.default,r=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.event===void 0){let p={instancePath:o,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 s)if(!(p==="checks"||p==="checksReason"||p==="event"||p==="proposal"||p==="requirementsEvidence")){let u={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[u]:a.push(u),d++}if(s.checks!==void 0){let p=s.checks;if(Array.isArray(p)){let u=p.length;for(let m=0;m<u;m++){let h=p[m];if(h&&typeof h=="object"&&!Array.isArray(h)){if(h.name===void 0){let g={instancePath:o+"/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:o+"/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:o+"/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(n(g)<1){let w={instancePath:o+"/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:o+"/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(n(g)<1){let w={instancePath:o+"/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:o+"/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:o+"/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:o+"/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 u={instancePath:o+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};a===null?a=[u]:a.push(u),d++}}if(s.checksReason!==void 0){let p=s.checksReason;if(typeof p=="string"){if(n(p)<1){let u={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.event!==void 0){let p=s.event;if(!(p==="build-complete"||p==="escalation-requested")){let u={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"};a===null?a=[u]:a.push(u),d++}}if(s.proposal!==void 0){let p=s.proposal;if(typeof p=="string"){if(n(p)<1){let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.requirementsEvidence!==void 0){let p=s.requirementsEvidence;if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.ref===void 0){let u={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"ref"},message:"must have required property 'ref'"};a===null?a=[u]:a.push(u),d++}if(p.contentHash===void 0){let u={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};a===null?a=[u]:a.push(u),d++}for(let u in p)if(!(u==="contentHash"||u==="ref")){let m={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),d++}if(p.contentHash!==void 0){let u=p.contentHash;if(typeof u=="string"){if(!r.test(u)){let m={instancePath:o+"/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:o+"/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 u=p.ref;if(typeof u=="string"){if(n(u)<1){let m={instancePath:o+"/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:o+"/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 u={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[u]:a.push(u),d++}}}else{let p={instancePath:o,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})(),RF=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;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"},n=at.default.default??at.default;function r(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let d={instancePath:s,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:s,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 u=0;u<p;u++){let m=d[u];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:s+"/checks/"+u,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:s+"/checks/"+u,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:s+"/checks/"+u,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(n(h)<1){let g={instancePath:s+"/checks/"+u+"/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:s+"/checks/"+u+"/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(n(h)<1){let g={instancePath:s+"/checks/"+u+"/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:s+"/checks/"+u+"/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:s+"/checks/"+u+"/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:s+"/checks/"+u,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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return r.errors=f,a===0}return e.exports})(),CF=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={additionalProperties:!1,properties:{contentHash:{pattern:"^[a-f0-9]{64}$",type:"string"}},required:["contentHash"],type:"object"},n=new RegExp("^[a-f0-9]{64}$","u");function r(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.contentHash===void 0){let d={instancePath:s,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:s,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(!n.test(d)){let p={instancePath:s+"/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:s+"/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:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return r.errors=f,a===0}return e.exports})(),SF=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;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"},n=at.default.default??at.default;function r(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.targetBranch===void 0){let d={instancePath:s,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:s,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:s,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 u=0;u<p;u++){let m=d[u];if(typeof m=="string"){if(n(m)<1){let h={instancePath:s+"/deliveryPaths/"+u,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:s+"/deliveryPaths/"+u,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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return r.errors=f,a===0}return e.exports})(),EF=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={properties:{buildPause:{enum:["plan-ready"]},plan:{minLength:1,type:"string"}},required:["plan"],type:"object"},n=at.default.default??at.default;function r(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.plan===void 0){let d={instancePath:s,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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return r.errors=f,a===0}return e.exports})(),AF=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;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"},n=at.default.default??at.default;function r(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let d={instancePath:s,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 u=0;u<p;u++){let m=d[u];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:s+"/checks/"+u,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:s+"/checks/"+u,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:s+"/checks/"+u,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(n(h)<1){let g={instancePath:s+"/checks/"+u+"/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:s+"/checks/"+u+"/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(n(h)<1){let g={instancePath:s+"/checks/"+u+"/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:s+"/checks/"+u+"/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:s+"/checks/"+u+"/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:s+"/checks/"+u,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:s+"/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(n(d)<1){let p={instancePath:s+"/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:s+"/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:s+"/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:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return r.errors=f,a===0}return e.exports})(),xF=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={properties:{designDoc:{minLength:1,type:"string"}},required:["designDoc"],type:"object"},n=at.default.default??at.default;function r(i,{instancePath:s="",parentData:o,parentDataProperty:c,rootData:l=i}={}){let f=null,a=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.designDoc===void 0){let d={instancePath:s,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(n(d)<1){let p={instancePath:s+"/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:s+"/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:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[d]:f.push(d),a++}return r.errors=f,a===0}return e.exports})(),IF=(()=>{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"},n=at.default.default??at.default,r=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,d=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.proposal===void 0){let p={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"proposal"},message:"must have required property 'proposal'"};a===null?a=[p]:a.push(p),d++}if(s.handoffContext!==void 0){let p=s.handoffContext;if(typeof p=="string"){if(n(p)<1){let u={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.handoffHash!==void 0){let p=s.handoffHash;if(typeof p=="string"){if(!r.test(p)){let u={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}if(s.proposal!==void 0){let p=s.proposal;if(typeof p=="string"){if(n(p)<1){let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[u]:a.push(u),d++}}else{let u={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[u]:a.push(u),d++}}}else{let p={instancePath:o,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})(),KA=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"}',mF],['{"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"}',hF],['{"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"}',gF],['{"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"}',wF],['{"additionalProperties":false,"properties":{"archiveDirectory":{"minLength":1,"type":"string"}},"required":["archiveDirectory"],"type":"object"}',yF],['{"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"}',vF],['{"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"}',kF],['{"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"}',bF],['{"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"}',RF],['{"additionalProperties":false,"properties":{"contentHash":{"pattern":"^[a-f0-9]{64}$","type":"string"}},"required":["contentHash"],"type":"object"}',CF],['{"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"}',SF],['{"properties":{"buildPause":{"enum":["plan-ready"]},"plan":{"minLength":1,"type":"string"}},"required":["plan"],"type":"object"}',EF],['{"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"}',AF],['{"properties":{"designDoc":{"minLength":1,"type":"string"}},"required":["designDoc"],"type":"object"}',xF],['{"properties":{"handoffContext":{"minLength":1,"type":"string"},"handoffHash":{"pattern":"^[a-f0-9]{64}$","type":"string"},"proposal":{"minLength":1,"type":"string"}},"required":["proposal"],"type":"object"}',IF]]);var _F=128,zA=1024*1024,Ss=new Map,Cw=0;function Jd(e){let t=Nr(e),n=Ss.get(t);if(n)return Ss.delete(t),Ss.set(t,n),n;let i=KA.get(t)??new Sw.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),s={validate:i,errorsText:()=>Sw.Ajv.prototype.errorsText(i.errors)};if(t.length<=zA){for(;Ss.size>=_F||Cw+t.length>zA;){let o=Ss.keys().next().value;Ss.delete(o),Cw-=o.length}Ss.set(t,s),Cw+=t.length}return s}var PF=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];function dt(e){throw new b("INVALID_WORKFLOW",e)}function Ii(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&dt(`${t} 必须是 JSON 对象`),e}function Lc(e,t,n){for(let r of Object.keys(e))t.includes(r)||dt(`${n} 包含不支持的字段:${r}`)}function Mt(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&dt(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Ew(e,t,n=!1){(!Array.isArray(e)||!n&&e.length===0)&&dt(`${t} 必须是${n?"":"非空"}字符串数组`);let r=e.map(i=>Mt(i,t));return new Set(r).size!==r.length&&dt(`${t} 不能包含重复值`),r}function Aw(e,t){return Ew(typeof e=="string"?[e]:e,t)}function Wc(e,t){let n=Ii(e,t);return Lc(n,["id","version"],t),{id:Mt(n.id,`${t}.id`),version:Mt(n.version,`${t}.version`)}}function GA(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))GA(t);Object.freeze(e)}return e}function YA(e,t){try{let n=typeof e=="boolean"?e:Ii(e,t);typeof n!="boolean"&&n.$async===!0&&dt(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),Jd(n)}catch(n){dt(`${t} 不是受支持的 JSON Schema:${n.message}`)}}function OF(e){let t=Ii(e,"step"),n=Mt(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(n)||dt(`不支持的步骤类型:${n}`);let r=n==="ask_user"?["proposalFrom","choices"]:n==="child_workflow"?["workflow"]:n==="await_evidence"?["kind"]:[];Lc(t,[...PF,...r],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&dt("step.retry 必须是 manual、idempotent 或 reconcile");let s={...t.ref===void 0?{}:{ref:Mt(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:Wc(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:Ew(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:Ew(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&YA(t.outputSchema,"outputSchema"),n==="ask_user"?{...s,type:n,proposalFrom:Aw(t.proposalFrom,"step.proposalFrom"),choices:Aw(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:n==="child_workflow"?{...s,type:n,workflow:Wc(t.workflow,"step.workflow")}:n==="await_evidence"?(s.validator||dt("await_evidence 必须声明验证器"),{...s,type:n,kind:Mt(t.kind,"step.kind"),validator:s.validator}):{...s,type:n,ref:Mt(t.ref,"step.ref")}}var JA=new WeakSet;function er(e){if(JA.has(e))return e;let t=Ii(Ye(e),"workflow");Lc(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let n=Mt(t.id,"workflow.id"),r=Mt(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&dt("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&dt("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&YA(t.stateSchema,"stateSchema");let i=Ii(t.steps,"workflow.steps");Object.keys(i).length===0&&dt("workflow.steps 必须至少包含一个步骤");let s=Object.fromEntries(Object.entries(i).map(([h,g])=>(Mt(h,"step id"),[h,OF(g)])));function o(h,g){Object.hasOwn(s,h)||dt(`${g} 引用了不存在的步骤:${h}`)}let c=Aw(t.entry,"workflow.entry");for(let h of c)o(h,"workflow.entry");let l=t.commands===void 0?{}:Ii(t.commands,"workflow.commands"),f={};for(let[h,g]of Object.entries(l)){Mt(h,"workflow command name");let w=typeof g=="string"?{stepId:Mt(g,`workflow.commands.${h}`)}:Ii(g,`workflow.commands.${h}`);Lc(w,["stepId","validator"],`workflow.commands.${h}`);let k=Mt(w.stepId,`workflow.commands.${h}.stepId`);o(k,`workflow.commands.${h}`);let y=s[k];(y.join||!["invoke_skill","call_tool","handoff"].includes(y.type))&&dt(`workflow.commands.${h} 必须指向不带 join 的执行步骤`),Object.defineProperty(f,h,{value:{stepId:k,...w.validator===void 0?{}:{validator:Wc(w.validator,`workflow.commands.${h}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let a=t.transitions===void 0?[]:t.transitions;Array.isArray(a)||dt("workflow.transitions 必须是数组");let d=new Set,p=a.map(h=>{let g=Ii(h,"transition");Lc(g,["from","to","on"],"transition");let w=Mt(g.from,"transition.from"),k=Mt(g.to,"transition.to"),y=Mt(g.on===void 0?"succeeded":g.on,"transition.on");o(w,"transition.from"),o(k,"transition.to");let R=JSON.stringify([w,k,y]);return d.has(R)&&dt(`重复的状态转移:${w} -> ${k} (${y})`),d.add(R),{from:w,to:k,on:y}});for(let[h,g]of Object.entries(s)){if(g.join){let w=new Set(p.filter(k=>k.to===h).map(k=>k.from));for(let k of g.join)o(k,`${h}.join`),w.has(k)||dt(`${h}.join 依赖缺少对应的进入边:${k}`);w.size!==g.join.length&&dt(`${h}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let w of g.proposalFrom)o(w,`${h}.proposalFrom`)}let u=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof u!="number"||!Number.isSafeInteger(u)||u<1)&&dt("workflow.maxTransitions 必须是正安全整数");let m=GA({id:n,version:r,entry:c,steps:s,...t.commands===void 0?{}:{commands:f},transitions:p,maxTransitions:u,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:Wc(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:Wc(t.transitionHandler,"workflow.transitionHandler")}});return JA.add(m),m}function Mc(e,t,n){Object.defineProperty(e,t,{value:n,configurable:!0,enumerable:!0,writable:!0})}function Gd(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.value]))}function TF(e){let t={};for(let n of e)for(let[r,i]of Object.entries(n.results))(!Object.hasOwn(t,r)||i.sequence>t[r].sequence)&&Mc(t,r,i);return t}function Mr(e,t){if(e.status==="cancelled"||e.status==="failed")return;for(;e.ready.length>0;){let s=e.ready.shift(),o=t.steps[s.to],c=s.results;if(o.join?.length){if(s.from===null||!o.join.includes(s.from))throw new b("INVALID_JOIN","join 必须由其声明的父节点触发");Object.hasOwn(e.joins,s.to)||Mc(e.joins,s.to,Object.fromEntries(o.join.map(p=>[p,[]])));let d=e.joins[s.to];if(d[s.from].push(s),o.join.some(p=>d[p].length===0))continue;c=TF(o.join.map(p=>d[p].shift()))}if(e.sequence>=t.maxTransitions){e.ready.unshift(s),e.status="failed",e.reason="TRANSITION_LIMIT: 工作流已达到允许的步骤激活次数";return}let l=++e.sequence,f=`${e.runId}:${l}`,a={input:o.input===void 0?e.input:o.input,outputs:Gd(c),...s.activation===void 0?{}:{activation:s.activation}};if(o.type==="ask_user"){let d=Object.fromEntries(o.proposalFrom.map(u=>{if(!Object.hasOwn(c,u))throw new b("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${u}`);return[u,c[u].value]})),p={input:a.input,outputs:d,...s.activation===void 0?{}:{activation:s.activation}};e.waits.push({id:f,stepId:s.to,sequence:l,status:"pending",proposal:p,proposalHash:j(p),choices:[...o.choices],results:c})}else if(o.type==="await_evidence")e.evidenceWaits??=[],e.evidenceWaits.push({id:f,stepId:s.to,sequence:l,kind:o.kind,status:"pending",results:c});else{let d=o.type==="child_workflow"?`${o.workflow.id}@${o.workflow.version}`:o.ref,p=VC({id:f,runId:e.runId,stepId:s.to,type:o.type,ref:d,input:a,retry:o.retry,requiredCapabilities:o.requiredCapabilities});e.actions.push(p),Mc(e.actionContexts,f,{sequence:l,results:c}),o.type==="child_workflow"&&e.children.push({actionId:f,runId:`child-${j(f)}`,workflow:o.workflow})}}let n=e.actions.some(s=>["pending","running","unknown"].includes(s.status)),r=e.waits.some(s=>s.status==="pending")||(e.evidenceWaits?.some(s=>s.status==="pending")??!1),i=Object.values(e.joins).some(s=>Object.values(s).some(o=>o.length>0));e.status=n?"running":r||i?"waiting":"completed"}function Wo(e,t,n,r,i,s,o,c){let l={sequence:r,value:s},f={...i};Mc(f,n,l),(!Object.hasOwn(e.outputs,n)||e.outputs[n].sequence<=r)&&Mc(e.outputs,n,l);let a=t.transitions.filter(u=>u.from===n),d=a.filter(u=>u.on===o),p=c??d.map(u=>u.to);if(p.length===0&&o==="failed"){e.status="failed",e.reason=`ACTION_FAILED: ${n}`;return}if(p.length===0&&c===void 0&&a.length>0)throw new b("TRANSITION_UNAVAILABLE",`步骤 ${n} 未声明 ${o} 的后续转换`);for(let u of p){let m=typeof u=="string"?u:u.stepId;if(!d.some(h=>h.to===m))throw new b("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:n,to:m,results:f,...typeof u=="string"?{}:{activation:u.input}})}}function XA(e){return Oe({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 Ke(e){return JSON.stringify([e.id,e.version])}function wn(e){if(e===void 0)return;if(!e||typeof e!="object"||Pw.isProxy(e))throw new b("INVALID_JSON","context 必须是普通对象");let t={},n;for(let i of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!s.enumerable||!("value"in s))throw new b("INVALID_JSON","context 必须使用普通数据属性");i==="signal"?n=s.value:s.value!==void 0&&Object.defineProperty(t,i,{value:s.value,enumerable:!0})}let r=Ye(t);if(n!==void 0){if(!(n instanceof AbortSignal))throw new b("INVALID_JSON","signal 必须是 AbortSignal");r.signal=n}return r}function Ow(e,t=new Set){if(e===null||typeof e!="object")return e;if(Pw.isProxy(e))throw new b("INVALID_JSON","请求不能包含代理对象");if(t.size>64)throw new b("INVALID_JSON","请求数据嵌套超过 64 层");if(t.has(e))throw new b("INVALID_JSON","请求包含循环引用");let n=Object.getPrototypeOf(e);if(!Array.isArray(e)&&n!==Object.prototype&&n!==null)throw new b("INVALID_JSON","请求必须使用普通数据对象");t.add(e);let r=Array.isArray(e)?[]:{};for(let i of Reflect.ownKeys(e)){if(Array.isArray(e)&&i==="length")continue;let s=Object.getOwnPropertyDescriptor(e,i);if(typeof i!="string"||!s.enumerable||!("value"in s))throw new b("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(r,i,{enumerable:!0,writable:!0,configurable:!0,value:Ow(s.value,t)})}return t.delete(e),r}function Iw(e){if(e===null||typeof e!="object")return e;if(Pw.isProxy(e))throw new b("INVALID_JSON","请求不能包含代理对象");let t={};for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);if(typeof n!="string"||!r.enumerable||!("value"in r))throw new b("INVALID_JSON","请求必须使用普通数据属性");Object.defineProperty(t,n,{enumerable:!0,writable:!0,configurable:!0,value:n==="context"?wn(r.value):Ow(r.value)})}return t}function Es(e){let t=Ow(e),n=Ye(t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)):t);if(!n||typeof n.accepted!="boolean"||n.reason!==void 0&&typeof n.reason!="string"||"allowCompleted"in n&&typeof n.allowCompleted!="boolean"||"allowFailed"in n&&typeof n.allowFailed!="boolean")throw new b("INVALID_VALIDATION","验证器必须返回布尔 accepted 和有效原因");return n}function _w(e,t){let n=e.supports(Oe(t));if(typeof n!="boolean")throw new b("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return n}function vr(e){if(e?.signal?.aborted)throw new b("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function As(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 n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>Object.hasOwn(t,r)&&As(e[r],t[r]))}function QA(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,n])=>[t,Object.fromEntries(Object.entries(n).map(([r,i])=>[r,[...i]]))])),outputs:{...e.outputs},children:[...e.children],lineage:[...e.lineage]}}var ZA=new WeakMap;function xs(e){let t=new Map,n=new Map;for(let v of e.workflows){let S=er(v),P=Ke(S);if(t.has(P))throw new b("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set(P,S);let x=ZA.get(S);x===void 0&&(x=j(S),ZA.set(S,x)),n.set(S,x)}let r=new Map;for(let v of e.validators??[]){let S=Ke(v);if(r.has(S))throw new b("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");r.set(S,v)}let i=new Map;for(let v of e.stateValidators??[]){let S=Ke(v);if(i.has(S))throw new b("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(S,v)}let s=new Map;function o(v){let S=s.get(v);return S||(S=Jd(v),s.set(v,S)),S}let c=new Map,l=new Map;for(let v of e.transitionHandlers??[]){let S=Ke(v);if(l.has(S))throw new b("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");l.set(S,v)}let f=new Map;for(let v of e.evidenceValidators??[]){let S=Ke(v);if(f.has(S))throw new b("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");f.set(S,v)}let a=new Map;for(let v of e.commandValidators??[]){let S=Ke(v);if(a.has(S))throw new b("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");a.set(S,v)}for(let v of e.executors??[]){if(c.has(v.id))throw new b("DUPLICATE_EXECUTOR","不能重复注册同一执行器");c.set(v.id,v)}function d(v){let S=t.get(Ke(v));if(!S)throw new b("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(v.hash!==void 0&&v.hash!==n.get(S))throw new b("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return S}function p(v){if(v.transitionHandler&&!l.has(Ke(v.transitionHandler)))throw new b("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function u(v){if(v.stateValidator&&!i.has(Ke(v.stateValidator)))throw new b("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function m(v){for(let S of Object.values(v.steps))if(S.type==="await_evidence"&&!f.has(Ke(S.validator)))throw new b("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function h(v){for(let S of Object.values(v.commands??{}))if(S.validator&&!a.has(Ke(S.validator)))throw new b("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(v,S,P){if(v.stateSchema!==void 0){let x=o(v.stateSchema);if(!x.validate(S))throw new b(P,x.errorsText())}if(v.stateValidator){let x=i.get(Ke(v.stateValidator));if(!x)throw new b("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let O=Es(x.validate({state:Ye(S)}));if(!O.accepted)throw new Error(O.reason??"业务状态未通过验证")}catch(O){throw new b(P,O instanceof Error?O.message:String(O))}}}function w(v,S,P,x){if(!S.transitionHandler)return;let O=l.get(Ke(S.transitionHandler));if(!O)throw new b("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let H=Ye(O.apply({run:Oe(v),event:Oe(P)})),B=Ye(H.state);g(S,B,"TRANSITION_STATE_INVALID");let J=new Set(S.transitions.filter(ee=>ee.from===P.stepId&&ee.on===x).map(ee=>ee.to));if(!Array.isArray(H.next))throw new b("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let W=[],G=new Set;for(let ee of H.next){let N;if(typeof ee=="string")N=ee;else if(ee!==null&&typeof ee=="object"&&!Array.isArray(ee)){let me=Object.keys(ee);if(me.length!==2||!me.includes("stepId")||!me.includes("input")||typeof ee.stepId!="string")throw new b("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");N={stepId:ee.stepId,input:Ye(ee.input)}}else throw new b("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let ae=typeof N=="string"?N:N.stepId,X=j(N);if(!J.has(ae)||G.has(X))throw new b("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");G.add(X),W.push(N)}return v.state=B,W}function k(v,S=j){if(t.size>0)for(let[P,x]of Object.entries(v.definitionHashes)){let[O,H]=JSON.parse(P),B=d({id:O,version:H,hash:x});if(p(B),u(B),m(B),h(B),O===v.workflow.id&&H===v.workflow.version){let J=new Map(v.actions.map(W=>[W.id,W]));for(let W of v.commands??[]){let G=J.get(W.actionId),ee=Object.hasOwn(B.commands??{},W.name),N=G&&!ee&&!Object.hasOwn(B.steps,G.stepId)&&["succeeded","failed","cancelled"].includes(G.status);if(!G||!N&&(!ee||B.commands?.[W.name].stepId!==G.stepId)||G.input===null||typeof G.input!="object"||!Object.hasOwn(G.input,"activation")||S(G.input.activation)!==W.inputHash)throw new b("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(B.stateSchema!==void 0&&B.initialState===void 0&&v.initialStateHash===void 0)throw new b("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(B,v.state,"RUN_STATE_INVALID");for(let W of v.ready){let G=()=>{throw new b("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(B.steps,W.to)||G(),W.from===null){(!B.entry.includes(W.to)||Object.keys(W.results).length>0||v.sequence!==0&&!(v.status==="failed"&&v.reason?.startsWith("TRANSITION_LIMIT:")))&&G();continue}let ee=W.results[W.from];ee||G();let N=v.actions.find(Gt=>Gt.stepId===W.from&&v.actionContexts[Gt.id].sequence===ee.sequence),ae=v.waits.find(Gt=>Gt.stepId===W.from&&Gt.sequence===ee.sequence),X=v.evidenceWaits?.find(Gt=>Gt.stepId===W.from&&Gt.sequence===ee.sequence),me=N?.outcome?N.outcome.status==="failed"?"failed":N.outcome.event??"succeeded":ae?.decision?.choice??(X?.invalidation?"invalidated":X?.receipt?"succeeded":void 0),ze=N?v.actionContexts[N.id].results:ae?.results??X?.results,ta=N?.outcome?N.outcome.output:ae?.decision?{choice:ae.decision.choice,proposal:ae.proposal}:X?.invalidation?{ref:X.invalidation.ref,contentHash:X.invalidation.contentHash,reason:X.invalidation.reason}:X?.receipt?{ref:X.receipt.ref,contentHash:X.receipt.contentHash}:void 0;(!me||!ze||N&&!["succeeded","failed"].includes(N.status)||ae&&ae.status!=="resolved"||X&&!["resolved","invalidated"].includes(X.status)||ta===void 0||S(W.results)!==S({...ze,[W.from]:{sequence:ee.sequence,value:ta}})||!B.transitions.some(Gt=>Gt.from===W.from&&Gt.to===W.to&&Gt.on===me))&&G()}for(let W of v.evidenceWaits??[]){let G=B.steps[W.stepId];if(!(!G&&W.status!=="pending")&&(!G||G.type!=="await_evidence"||G.kind!==W.kind))throw new b("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function y(v){let S=await e.store.read(v);if(!S)throw new b("RUN_NOT_FOUND",`找不到工作流实例:${v}`);let P=tS(S,v);return k(P),as(P)}async function R(v,S,P){for(let x=0;x<32;x+=1){vr(v.context);let O=x===0&&P?P:await y(v.runId),H=d(O.workflow);if(v.expectedRevision!==void 0&&v.expectedRevision!==O.revision)throw new b("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let B=QA(O);if(await S(B,H),In(B),As(B,O))return O;if(B.revision=O.revision+1,ld(B,O),k(B),as(B),vr(v.context),await e.store.compareAndSwap(v.runId,O.revision,B))return B}throw new b("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function C(v,S){let P=v.actions.find(x=>x.id===S);if(!P)throw new b("ACTION_NOT_FOUND","Run 不包含此 Action");return P}function A(v){if(v.status==="cancelled")throw new b("RUN_CANCELLED","Run 已取消,不能继续推进")}function q(v,S={}){let P=Ke(v);if(Object.hasOwn(S,P))return S;S[P]=n.get(v);for(let x of Object.values(v.steps))x.type==="child_workflow"&&q(d(x.workflow),S);return S}async function D(v,S){if(vr(v.context),S.length>32)throw new b("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let P=d(v.workflow);p(P),u(P),m(P),h(P);let x=Object.hasOwn(v,"initialState");if(x&&P.initialState!==void 0)throw new b("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let O=x?Ye(v.initialState):P.initialState;if(P.stateSchema!==void 0&&O===void 0)throw new b("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");O!==void 0&&g(P,O,"INITIAL_STATE_INVALID");let H=O===void 0?void 0:j(O),B=v.runId??xw(),J=Ye(v.input),W={id:P.id,version:P.version,hash:n.get(P)},G=await e.store.read(B);if(G){if(j(G.workflow)!==j(W)||j(G.input)!==j(J)||j(G.lineage)!==j(S)||(G.initialStateHash??(P.initialState===void 0?void 0:j(P.initialState)))!==H)throw new b("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return y(B)}let ee={protocolVersion:1,schemaVersion:1,runId:B,revision:1,workflow:W,definitionHashes:q(P),input:J,...O===void 0?{}:{state:Ye(O),initialStateHash:H},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:P.entry.map(N=>({from:null,to:N,results:{}})),joins:{},outputs:{},children:[],lineage:S};return Mr(ee,P),as(ee),vr(v.context),ld(ee),k(ee),await e.store.compareAndSwap(B,null,ee)?Oe(ee):D({...v,runId:B},S)}async function K(v){return D(v,[])}async function L(v){let S=Ye(v.input),P=j(S);if(!v.commandId.trim()||v.commandId.length>4096||!v.name.trim()||v.name.length>4096)throw new b("INVALID_COMMAND","命令标识和名称不能为空");for(let x=0;x<32;x+=1){vr(v.context);let O=await y(v.runId),H=O.commands?.find(X=>X.id===v.commandId);if(H){if(H.name!==v.name||H.inputHash!==P)throw new b("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return O}if(v.expectedRevision!==O.revision)throw new b("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let B=d(O.workflow),J=Object.hasOwn(B.commands??{},v.name)?B.commands?.[v.name]:void 0;if(!J)throw new b("COMMAND_NOT_FOUND","工作流未声明此命令");let W=J.stepId;if(O.status==="cancelled")throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(O.actions.some(X=>["running","unknown"].includes(X.status)))throw new b("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let G=!1,ee=!1;if(J.validator){let X=a.get(Ke(J.validator));if(!X)throw new b("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let me;try{me=Es(await X.validate({run:Oe(O),name:v.name,input:Oe(S),context:wn(v.context)}))}catch(ze){throw new b("COMMAND_VALIDATION_ERROR",ze instanceof Error?ze.message:String(ze))}if(G=me.accepted&&me.allowCompleted===!0,ee=me.accepted&&me.allowFailed===!0,O.status==="failed"&&!ee)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(O.status==="completed"&&!G)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!me.accepted)throw new b("COMMAND_REJECTED",me.reason??"命令未通过当前工作流状态验证")}if(O.status==="completed"&&!G)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(O.status==="failed"&&!ee)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");let N=Oe(O);O.status==="failed"&&(N.status="running",delete N.reason),N.actions=N.actions.map(X=>X.status==="pending"?Ah(X,`命令 ${v.name} 已取代待执行 Action`):X);for(let X of N.waits)X.status==="pending"&&(X.status="cancelled");for(let X of N.evidenceWaits??[])X.status==="pending"&&(X.status="cancelled");N.ready=[{from:null,to:W,results:{},activation:S}],N.joins={},Mr(N,B);let ae=N.actions.at(-1);if(!ae||ae.stepId!==W||ae.status!=="pending")throw new b("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if(N.commands=[...N.commands??[],{id:v.commandId,name:v.name,inputHash:P,actionId:ae.id}],N.revision=O.revision+1,ld(N,O),k(N),as(N),vr(v.context),await e.store.compareAndSwap(v.runId,O.revision,N))return Oe(N)}throw new b("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function Z(v){for(let S of v.children)await e.store.read(S.runId)&&await T({runId:S.runId,reason:v.reason??"父工作流已取消"})}function Y(v,S,P){let x=d(v.workflow),O=Object.hasOwn(x.steps,P.stepId)?x.steps[P.stepId]:void 0;if(!O||O.type!=="child_workflow"||Ke(O.workflow)!==Ke(S.workflow)||P.type!==O.type||P.ref!==`${O.workflow.id}@${O.workflow.version}`||P.attempt!==1||P.retry!==O.retry||!As(P.requiredCapabilities,O.requiredCapabilities??[])||P.claim&&(P.claim.executorId!=="comet-child-workflow"||P.claim.sessionId!==void 0||![S.runId,`portable-${j(S.runId)}`].includes(P.claim.token)))throw new b("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let H=P.input;if(!H||typeof H!="object"||Array.isArray(H)||!As(H,{input:O.input===void 0?v.input:O.input,outputs:Gd(v.actionContexts[P.id].results),...Object.hasOwn(H,"activation")?{activation:H.activation}:{}}))throw new b("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let B=d({...S.workflow,hash:v.definitionHashes[Ke(S.workflow)]});if(Object.entries(q(B)).some(([J,W])=>v.definitionHashes[J]!==W))throw new b("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return B}function fe(v,S,P,x,O){let H=x.initialState===void 0?void 0:j(x.initialState);if(O.runId!==S.runId||Ke(O.workflow)!==Ke(S.workflow)||O.workflow.hash!==v.definitionHashes[Ke(S.workflow)]||!As(O.definitionHashes,q(x))||!As(O.input,P.input)||!As(O.lineage,[...v.lineage,v.runId])||(O.initialStateHash??H)!==H)throw new b("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function z(v){let S=await R(v,(P,x)=>Mr(P,x));if(S.status==="cancelled")return await Z(S),S;if(S.status==="failed"||S.children.length===0)return S;for(let P of S.children){let x=C(S,P.actionId);if(!["pending","running","unknown"].includes(x.status))continue;let O=Y(S,P,x);x.status==="pending"&&(S=await ne({runId:S.runId,actionId:x.id,attempt:x.attempt,inputHash:x.inputHash,executorId:"comet-child-workflow",claimToken:P.runId,capabilities:["child-workflow"],context:wn(v.context)},!0),x=C(S,P.actionId));let H=x.status==="unknown"?await y(P.runId):await D({runId:P.runId,workflow:P.workflow,input:x.input,context:wn(v.context)},[...S.lineage,S.runId]);fe(S,P,x,O,H);let B=await y(S.runId);if(B.status==="cancelled")return await Z(B),B;let J=await z({runId:P.runId,context:v.context});fe(S,P,x,O,J),["completed","failed","cancelled"].includes(J.status)&&(S=await I({runId:S.runId,context:wn(v.context),outcome:{actionId:x.id,attempt:x.attempt,inputHash:x.inputHash,claimToken:x.claim.token,outcomeId:`${P.runId}:${J.revision}`,status:J.status==="completed"?"succeeded":"failed",output:Gd(J.outputs)}},!0))}return y(S.runId)}async function ne(v,S=!1,P){let x=v.claimToken??(v.context?.requestId?j({runId:v.runId,actionId:v.actionId,attempt:v.attempt,executorId:v.executorId,requestId:v.context.requestId}):xw());return R(v,async O=>{if(A(O),O.status==="failed")throw new b("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let H=C(O,v.actionId);if(H.type==="child_workflow"&&!S)throw new b("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let B=KC(H,{executionOrigin:{workflow:{...O.workflow}},attempt:v.attempt,inputHash:v.inputHash,executorId:v.executorId,token:x,...v.sessionId===void 0?{}:{sessionId:v.sessionId}});if(!H.claim){let J=new Set(v.capabilities??[]);if(H.requiredCapabilities.some(G=>!J.has(G)))throw new b("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let W=c.get(v.executorId);if(W&&_w(W,H)){if(H.requiredCapabilities.some(G=>!W.capabilities.includes(G)))throw new b("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await W.preflight?.(Oe(H),wn(v.context),W.includeRun===!1?void 0:Oe(O)),vr(v.context)}}O.actions[O.actions.indexOf(H)]=B},P)}async function Le(v){return ne(v)}async function I(v,S=!1,P){let x,O;try{x=od(v.outcome)}catch(J){O=J}v={...v,outcome:x};let H,B=await R(v,async(J,W)=>{if(H=void 0,A(J),!x)throw O;let G=C(J,v.outcome.actionId);if(G.type==="child_workflow"&&!S)throw new b("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let ee=Eh(G,v.outcome);if(ee.duplicate)return;let N=ee.action.outcome,ae=J.actions.indexOf(G);try{if(e.validateOutcome){let me=Es(await e.validateOutcome({run:Oe(J),action:Oe(G),outcome:Oe(N),context:wn(v.context)}));me.accepted||(H={code:"OUTCOME_REJECTED",reason:me.reason??"应用结果契约拒绝此结果"})}let X=W.steps[G.stepId];if(!H&&N.status==="succeeded"&&X.outputSchema!==void 0){let me=o(X.outputSchema);me.validate(N.output)||(H={code:"OUTPUT_INVALID",reason:me.errorsText()})}if(!H&&X.validator){let me=r.get(Ke(X.validator));if(!me)throw new b("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let ze=Es(await me.validate({run:Oe(J),action:Oe(G),outcome:Oe(N),context:wn(v.context)}));ze.accepted||(H={code:"OUTCOME_REJECTED",reason:ze.reason?.trim()?ze.reason:"结果未满足业务验收条件"})}if(!H){let me=QA(J);me.actions[ae]=ee.action;let ze=me.actionContexts[G.id],ta=N.status==="failed"?"failed":N.event??"succeeded",Gt=w(me,W,{kind:"action-outcome",stepId:G.stepId,outcome:N},ta);Wo(me,W,G.stepId,ze.sequence,ze.results,N.output,ta,Gt),Mr(me,W),Object.assign(J,me)}}catch(X){H={code:"OUTCOME_PROCESSING_ERROR",reason:X instanceof Error&&X.message.trim()?X.message:"结果处理失败,请检查验证器或工作流定义"}}H&&(J.actions[ae]={...G,receipts:ee.action.receipts,rejectedOutcomes:[...G.rejectedOutcomes??[],{outcome:ee.action.outcome,...H}]})},P);if(H)throw new b(H.code,H.reason);return B}async function V(v){return I(v)}async function re(v){if(v.reason!==void 0&&!_h(v.reason))throw new b("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return R(v,(S,P)=>{A(S);let x=S.waits.find(H=>H.id===v.waitId);if(!x)throw new b("WAIT_NOT_FOUND","Run 不包含此等待项");if(x.decision){if(x.decision.id!==v.decisionId||x.decision.choice!==v.choice||x.decision.proposalHash!==v.proposalHash||x.decision.reason!==v.reason)throw new b("DECISION_CONFLICT","等待项已经接受了不同的决定");return}if(x.status!=="pending"||x.proposalHash!==v.proposalHash)throw new b("STALE_PROPOSAL","提案已改变或等待项已终止,请重新审阅");if(!v.decisionId.trim()||!x.choices.includes(v.choice))throw new b("INVALID_DECISION","决定标识或选择不符合当前等待项");x.status="resolved",x.decision={id:v.decisionId,choice:v.choice,proposalHash:v.proposalHash,...v.reason===void 0?{}:{reason:v.reason}};let O=w(S,P,{kind:"wait-resolved",stepId:x.stepId,choice:v.choice,proposalHash:v.proposalHash,decisionId:v.decisionId},v.choice);Wo(S,P,x.stepId,x.sequence,x.results,{choice:v.choice,proposal:x.proposal},v.choice,O),Mr(S,P)})}async function He(v){return R(v,async(S,P)=>{if(A(S),S.status==="failed")throw new b("RUN_FAILED","Run 已因失败停止,不能提交证据");let x=S.evidenceWaits?.find(W=>W.id===v.evidenceId);if(!x)throw new b("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(x.status!=="pending")throw new b("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(x.kind!==v.kind)throw new b("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!v.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(v.ref)||v.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(v.contentHash)||!v.submissionId.trim())throw new b("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let O=P.steps[x.stepId];if(!O||O.type!=="await_evidence"||O.kind!==v.kind)throw new b("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let H=f.get(Ke(O.validator));if(!H)throw new b("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let B=Es(await H.validate({run:Oe(S),kind:v.kind,ref:v.ref,contentHash:v.contentHash,context:wn(v.context)}));if(!B.accepted||B.actualHash!==v.contentHash)throw new b("EVIDENCE_REJECTED",B.reason??"证据未通过验证或内容已改变");x.status="resolved",x.receipt={ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId};let J=w(S,P,{kind:"evidence-recorded",stepId:x.stepId,evidenceKind:v.kind,ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId},"succeeded");Wo(S,P,x.stepId,x.sequence,x.results,{ref:v.ref,contentHash:v.contentHash},"succeeded",J),Mr(S,P)})}async function E(v){return R(v,async(S,P)=>{if(A(S),S.status==="failed")throw new b("RUN_FAILED","Run 已因失败停止,不能使证据失效");let x=S.evidenceWaits?.find(G=>G.id===v.evidenceId);if(!x)throw new b("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(x.status!=="pending")throw new b("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(x.kind!==v.kind)throw new b("EVIDENCE_KIND_MISMATCH","证据种类与等待项不一致");if(!v.ref.trim()||/^(?:[a-zA-Z]:|[\\/~])/u.test(v.ref)||v.ref.split(/[\\/]/u).includes("..")||!/^[a-f0-9]{64}$/u.test(v.contentHash)||!v.submissionId.trim())throw new b("INVALID_EVIDENCE","证据引用、摘要或提交标识无效");let O=P.steps[x.stepId];if(!O||O.type!=="await_evidence"||O.kind!==v.kind)throw new b("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!P.transitions.some(G=>G.from===x.stepId&&G.on==="invalidated"))throw new b("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let H=f.get(Ke(O.validator));if(!H)throw new b("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let B=Es(await H.validate({run:Oe(S),kind:v.kind,ref:v.ref,contentHash:v.contentHash,context:wn(v.context)}));if(B.accepted&&B.actualHash===v.contentHash)throw new b("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let J=(B.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);x.status="invalidated",x.invalidation={ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId,reason:J};let W=w(S,P,{kind:"evidence-invalidated",stepId:x.stepId,evidenceKind:v.kind,ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId,reason:J},"invalidated");Wo(S,P,x.stepId,x.sequence,x.results,{ref:v.ref,contentHash:v.contentHash,reason:J},"invalidated",W),Mr(S,P)})}async function $(v){return R(v,S=>{A(S);let P=S.waits.find(x=>x.id===v.waitId);if(!P||P.status!=="pending"||P.proposalHash!==v.proposalHash)throw new b("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");P.proposal=Ye(v.proposal),P.proposalHash=j(P.proposal)})}async function T(v){let S=await R(v,P=>{if(P.status==="completed"){if(v.stoppedActions?.length)throw new b("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let x=P.status==="cancelled";if(x||(P.actions=P.actions.map(O=>Ah(O,v.reason))),v.stoppedActions!==void 0){if(!Array.isArray(v.stoppedActions))throw new b("INVALID_ACTION","stoppedActions 必须是停止确认数组");let O=new Set;for(let H of v.stoppedActions){if(!H||typeof H!="object"||O.has(H.actionId))throw new b("INVALID_ACTION","停止确认重复或无效");O.add(H.actionId);let B=C(P,H.actionId);P.actions[P.actions.indexOf(B)]=xh(B,H)}}if(!x){for(let O of P.waits)O.status==="pending"&&(O.status="cancelled");for(let O of P.evidenceWaits??[])O.status==="pending"&&(O.status="cancelled");P.ready=[],P.status="cancelled",P.reason=v.reason}});return S.status==="cancelled"&&await Z(S),S}async function F(v){return R(v,S=>{if(!Array.isArray(v.stoppedActions)||!v.stoppedActions.length)throw new b("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let P=new Set;for(let x of v.stoppedActions){if(!x||typeof x!="object"||P.has(x.actionId))throw new b("INVALID_ACTION","停止确认重复或无效");P.add(x.actionId);let O=C(S,x.actionId);S.actions[S.actions.indexOf(O)]=Ih(O,x)}})}async function U(v){return R(v,S=>{A(S);let P=C(S,v.actionId);if(P.attempt!==v.attempt)throw new b("STALE_ACTION","Action 执行尝试已经改变");S.actions[S.actions.indexOf(P)]=zC(P,v.reason)})}async function se(v){return R(v,async(S,P)=>{A(S);let x=C(S,v.actionId);if(x.attempt!==v.attempt)throw new b("STALE_ACTION","Action 执行尝试已经改变");if(x.type==="child_workflow")throw new b("CHILD_MANAGED","子工作流由 Runtime 管理,不支持通过通用 retry 重置父 Action;保留原有子 Run 和执行记录");if(x.status==="succeeded"&&e.validateRecovery){if(v.expectedRevision===void 0)throw new b("REVISION_CONFLICT","恢复已提交结果必须绑定当前 Run 版本");if(v.reconciliation!==void 0)throw new b("OUTCOME_ALREADY_RECORDED","已提交结果不能声明未执行;请使用应用的语义恢复");if(typeof v.proposalHash!="string"||!v.proposalHash.trim())throw new b("INVALID_REQUEST","恢复已提交结果必须绑定当前应用决定");if(S.actions.some(W=>["running","unknown"].includes(W.status)))throw new b("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(S.status!=="completed"||S.ready.length>0||S.actions.some(W=>W.status==="pending")||S.waits.some(W=>W.status==="pending")||S.evidenceWaits?.some(W=>W.status==="pending")||Object.values(S.joins).some(W=>Object.values(W).some(G=>G.length>0))||!x.outcome||x.outcome.status!=="succeeded")throw new b("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let O=Es(await e.validateRecovery({run:Oe(S),action:Oe(x),outcome:Oe(x.outcome),context:wn(v.context),proposalHash:v.proposalHash}));if(!O.accepted)throw new b("ACTION_TERMINAL",O.reason??"应用拒绝恢复此结果");let H=x.outcome.event??"succeeded",B=w(S,P,{kind:"action-outcome",stepId:x.stepId,outcome:x.outcome},H);if(B?.length===0||B===void 0&&!P.transitions.some(W=>W.from===x.stepId&&W.on===H))throw new b("ACTION_TERMINAL","应用未声明可恢复的后续工作");let J=S.actionContexts[x.id];Wo(S,P,x.stepId,J.sequence,J.results,x.outcome.output,H,B),Mr(S,P);return}if(x.status==="failed"){let O=S.actionContexts[x.id].sequence,H=J=>Object.hasOwn(J,x.stepId)&&J[x.stepId].sequence===O;if(Object.values(S.actionContexts).some(J=>H(J.results))||S.waits.some(J=>H(J.results))||S.evidenceWaits?.some(J=>H(J.results))||S.ready.some(J=>H(J.results))||Object.values(S.joins).some(J=>Object.values(J).some(W=>W.some(G=>H(G.results)))))throw new b("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}S.actions[S.actions.indexOf(x)]=JC(x,v.reconciliation),S.status="running",delete S.reason})}async function pe(v,S){let P=c.get(v.executorId);if(!P)throw new b("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let x=S??await y(v.runId),O=C(x,v.actionId);if(O.status!=="pending")throw new b("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!_w(P,O))throw new b("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");vr(v.context);let H=await ne({...v,attempt:O.attempt,inputHash:O.inputHash,claimToken:xw(),capabilities:P.capabilities},!1,x),B=C(H,v.actionId),J;try{vr(v.context),J=await P.execute(Oe(B),wn(v.context),P.includeRun===!1?void 0:Oe(H))}catch(G){let ee=await y(v.runId),N=C(ee,B.id);throw ee.status!=="cancelled"&&N.status==="running"&&N.attempt===B.attempt&&await U({runId:v.runId,actionId:B.id,attempt:B.attempt,reason:G instanceof Error?G.message:String(G)}),new b("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let W=`${B.id}:${B.attempt}:executor-result`;try{return await I({runId:v.runId,context:wn(v.context),outcome:{...J,actionId:B.id,attempt:B.attempt,inputHash:B.inputHash,claimToken:B.claim.token,outcomeId:W}},!1,H)}catch(G){let ee=await y(v.runId),N=C(ee,B.id);if(N.receipts.some(ae=>ae.outcomeId===W)){if(N.rejectedOutcomes?.some(ae=>ae.outcome.outcomeId===W))throw G;if(N.outcome?.outcomeId===W)return ee}throw ee.status!=="cancelled"&&N.status==="running"&&N.attempt===B.attempt&&await U({runId:v.runId,actionId:B.id,attempt:B.attempt,reason:G instanceof Error?G.message.slice(0,4096):"执行结果无法提交"}),new b("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function Be(v){let S=v.maxActions??100;if(!Number.isSafeInteger(S)||S<1)throw new b("INVALID_REQUEST","maxActions 必须是正安全整数");let P=c.get(v.executorId);if(!P)throw new b("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let x=0,O=await y(v.runId),H=J=>({reason:J,run:O,actionsExecuted:x}),B=J=>{if(O.status==="completed"||O.status==="failed"||O.status==="cancelled")return O.status;if(O.actions.some(W=>W.status==="unknown"&&(!J||W.type!=="child_workflow")))return"execution-unknown";if(O.actions.some(W=>W.status==="running"&&(!J||W.type!=="child_workflow")))return"action-in-flight";if(O.waits.some(W=>W.status==="pending"))return"approval-required";if(O.evidenceWaits?.some(W=>W.status==="pending"))return"evidence-required"};for(;;){vr(v.context);let J=B(!0);if(J)return H(J);(O.ready.length||O.children.length)&&(O=await z({runId:v.runId,context:v.context}));let W=B(!1);if(W)return H(W);let G=O.actions.find(ee=>ee.status==="pending");if(!G)return H("idle");if(x>=S)return H("action-limit");if(!_w(P,G)||G.requiredCapabilities.some(ee=>!P.capabilities.includes(ee)))return H("executor-required");x++;try{O=await pe({...v,actionId:G.id},O)}catch(ee){if(!(ee instanceof b)||ee.code!=="EXECUTION_UNKNOWN"||(O=await y(v.runId),!O.actions.some(N=>N.status==="unknown")))throw ee;return H("execution-unknown")}}}async function tt(v){let S=await Co(e.store,v);return k(S.run,jt),S}async function hn(v){return Oh(await tt(v.runId),v)}function Ae(v){return async(...S)=>{let P=S.map(x=>Iw(x));return Oe(await v(...P))}}return{start:Ae(K),dispatchCommand:Ae(L),inspect:Ae(y),inspectProjection:tt,query:Ae(hn),inspectCurrent:async v=>await hn({runId:v,view:"current"}),executeCurrent:async v=>XA(await pe(Iw(v))),runUntilBlockedCurrent:async v=>{let S=await Be(Iw(v));return{...S,run:XA(S.run)}},next:Ae(z),claim:Ae(Le),recordOutcome:Ae(V),resolveWait:Ae(re),recordEvidence:Ae(He),invalidateEvidence:Ae(E),reviseWait:Ae($),cancel:Ae(T),acknowledgeStopped:Ae(F),markUnknown:Ae(U),retry:Ae(se),execute:Ae(v=>pe(v)),runUntilBlocked:Ae(Be)}}Ta();Xi();cx();Ht();ve();import{createHash as fx,randomUUID as N3}from"node:crypto";import{types as WF}from"node:util";import{promises as jn}from"node:fs";import ft from"node:path";Sn();var lx=new WeakMap;function ux(e){return Qd(e).encoded}function Qd(e){let t=new WeakMap,n=new Map,r=a=>{if(typeof a=="string"){let m=n.get(a);return m===void 0&&(m=JSON.stringify(a).length,n.set(a,m)),m}if(a===null||typeof a!="object")return JSON.stringify(a).length;let d=lx.get(a)??t.get(a);if(d!==void 0)return d;let p=Object.entries(a),u=2+Math.max(0,p.length-1)+p.reduce((m,[h,g])=>m+(Array.isArray(a)?0:r(h)+1)+r(g),0);return t.set(a,u),xn(a)&&lx.set(a,u),u},i=r(e),s=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return s();let o=[],c=(a,d)=>{if(!a||typeof a!="object")return;let p=a;if(!(p.protocolVersion!==1||!Array.isArray(p.actions)||!p.actionContexts)){for(let[u,m]of p.actions.entries())m.input&&typeof m.input=="object"&&Object.hasOwn(m.input,"outputs")&&o.push({path:[...d,"actions",String(u),"input","outputs"],group:"outputs"});for(let[u,m]of Object.entries(p.actionContexts))m?.results&&o.push({path:[...d,"actionContexts",u,"results"],group:"results"});p.outputs&&o.push({path:[...d,"outputs"],group:"results"});for(let u of["ready","waits","evidenceWaits"])for(let[m,h]of(p[u]??[]).entries())h.results&&o.push({path:[...d,u,String(m),"results"],group:"results"})}};if(c(e,[]),c(e.run,["run"]),!o.length)return s();let l=HC(e,o,xn),f=JSON.stringify(l);return f.length<i*.9?{encoded:l,json:f}:s()}function Is(e){if(typeof e!="string"||e.trim().length===0)throw new b("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function MF(e){return Is(e),fx("sha256").update(JSON.stringify(e)).digest("hex")}function Zd(e){if(!Number.isSafeInteger(e)||e<1)throw new b("STORE_INVALID_REVISION","revision 必须是正安全整数")}function FF(e,t,n,r=!0){if(Is(e),WF.isProxy(n))throw new b("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&Zd(t),In(n);let i=r?structuredClone(n):n;if(!i||typeof i!="object"||Array.isArray(i)||i.runId!==e)throw new b("STORE_INVALID_RUN_ID","next.runId 必须与目标 runId 一致");if(Zd(i.revision),i.revision!==(t??0)+1)throw new b("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}var dx="comet.runtime-store-checkpoint.v1";function HF(e,t,n){let r=Ye(n);if(Is(e),!r||r.runId!==e)throw new b("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(Zd(r.revision),t!==null&&t!==1||r.revision<=(t??0))throw new b("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(r)}function px(e,t,n){let r=Ye(e);r.revision=t;for(let i of n){let s=r;for(let o of i.slice(0,-1))s=s[o];s[i.at(-1)]=t}return r}function BF(e,t,n,r=[]){return(e?.revision??null)===t&&(e===null||Nr(e)===Nr(px(n,1,r)))}function pn(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new b("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(E=>{if(E!=="run.revision")throw new b("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function n(E){for(let $ of t){let T=E;for(let F of $){if(!T||typeof T!="object"||Array.isArray(T)||!Object.hasOwn(T,F))throw new b("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");T=T[F]}if(T!==E.revision)throw new b("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let r=ft.resolve(e.rootDir),i=ft.parse(r).root,s=ft.relative(i,r).replaceAll("\\","/");if(!s)throw new b("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let o={label:"RuntimeStore root",expected:"directory"},c=MF,l="checkpoint.json",f="comet.runtime-store-format.v2",a=".runtime-store-v2",d=E=>`${a}/${c(E)}`,p=E=>`.runtime-store-history/${c(E)}`,u="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(E,$){let T=await ce(r,E?`${E}/${$}`:$,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let F=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(T.bytes));return In(F),F}catch{throw new b("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function y(E,$,T){if(!E||typeof E!="object"||Array.isArray(E)||E.runId!==$||E.revision!==T||!Number.isSafeInteger(T)||T<1)throw new b("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");n(E)}async function R(E,$=!1,T=c(E),F=!0){if(Is(E),!(await M(i,s,o)).exists)return w();let U=await M(r,T,{label:"RuntimeStore run",expected:"directory"});if(!U.exists)return w();let se=await jn.lstat(U.target),pe=await jn.readdir(U.target,{withFileTypes:!0}),Be=await jn.lstat(U.target);if(await M(i,`${s}/${T}`,o),!se.isDirectory()||se.isSymbolicLink()||!Be.isDirectory()||Be.isSymbolicLink()||!Cn({dev:se.dev,ino:se.ino,birthtime:se.birthtimeMs},{dev:Be.dev,ino:Be.ino,birthtime:Be.birthtimeMs}))throw new b("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let tt=new Set,hn=[],Ae=0;for(let N of pe){if((N.name===`${h}.contenders`||N.name==="legacy"&&T===d(E))&&N.isDirectory()&&!N.isSymbolicLink())continue;if(!N.isFile()||N.isSymbolicLink())throw new b("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)||(tt.add(N.name),N.name===l))continue;if(!g.test(N.name))throw new b("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);let ae=Number(N.name.slice(0,-5));if(!Number.isSafeInteger(ae)||ae<1)throw new b("STORE_INVALID_ENTRY",`版本文件无效:${N.name}`);hn.push(N.name),Ae=Math.max(Ae,ae)}let v=!1;if([d(E),p(E)].includes(T)&&hn.length>0)throw new b("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(tt.has(l)){if(![d(E),p(E)].includes(T))throw new b("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let N=await k(T,l),ae=N?.record,X=N?.legacyRevision;if(!N||![m,"comet.runtime-store-snapshot.v3"].includes(String(N.schema))||!ae||Object.keys(N).some(ze=>!["schema","record","hash","legacyRevision",...N.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(ze))||X!==null&&(!Number.isSafeInteger(X)||X<1||X>ae.revision)||N.hash!==j({record:ae,legacyRevision:X,...N.schema==="comet.runtime-store-snapshot.v3"?{pool:N.pool}:{}}))throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let me;try{me=N.schema==="comet.runtime-store-snapshot.v3"?sd(ae,N.pool,F):ae}catch(ze){throw new b("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${ze instanceof Error?ze.message:String(ze)}`)}return y(me,E,me.revision),{record:me,compacted:!0,legacyRevision:X,formatPresent:v}}if(!Ae)return w();let S=new Map,P=N=>`${String(N).padStart(16,"0")}.json`,x=N=>tt.has(P(N));async function O(N){if(S.has(N))return S.get(N);let ae=await k(T,P(N));return(N<=2||N===Ae)&&S.set(N,ae),ae}async function H(N,ae=0,X=Ae){if(y(N,E,X),$)for(let me of hn){let ze=Number(me.slice(0,-5));ze!==ae&&y(await O(ze),E,ze)}return{record:N,compacted:!1,legacyRevision:N.revision,formatPresent:!1}}let B=await O(Ae);if(Ae===hn.length&&(B?.schema!==dx||B?.runId!==void 0))return H(B);if(!x(1))throw new b("STORE_MISSING_REVISION","版本历史缺少 revision 1");let J=null;for(let N of[1,2]){if(!x(N))break;let ae=await O(N);if(ae?.schema!==dx||"runId"in ae)continue;let X=ae.record;if(X&&n(X),!X||X.runId!==E||!Number.isSafeInteger(X.revision)||X.revision<N||ae.hash!==j(X)||Object.keys(ae).some(me=>!["schema","record","hash"].includes(me))||N===2&&Nr(await O(1))!==Nr(px(X,1,t)))throw new b("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");J={slot:N,record:X};break}let W=J?.record.revision??0,G=J?.slot??0,ee=Ae===G?W:Ae;if(ee<W||hn.length!==ee-W+G||hn.some(N=>{let ae=Number(N.slice(0,-5));return ae>G&&ae<=W})){let N=W+1;for(;x(N);)N+=1;throw new b("STORE_MISSING_REVISION",`版本历史缺少 revision ${N}`)}return H(J&&Ae===J.slot?J.record:B,G,J&&Ae===J.slot?J.record.revision:Ae)}async function C(E){let $=await M(r,c(E),{label:"RuntimeStore format",expected:"any"}),T=await M(r,`${d(E)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if($.kind==="directory"&&T.exists&&($=await M(r,c(E),{label:"RuntimeStore format",expected:"any"})),$.kind==="directory"&&T.exists)throw new b("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let F=null;if($.kind==="file"){let U=await k("",c(E));if(!U||U.runId!==E||(U.schema===f?!["pending","ready"].includes(U.state)||Object.keys(U).some(se=>!["schema","runId","state","writerProtocol"].includes(se)):U.schema!==u||!["closing","closed","reopening"].includes(U.state)||!Number.isSafeInteger(U.revision)||U.revision<1||typeof U.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(U.recordHash)||Object.keys(U).some(se=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(se))))throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(U.writerProtocol!==void 0&&U.writerProtocol!=="application-holder-v1")throw new b("STORE_WRITER_FENCED","存储协议版本不受支持");F=U}return{original:$,staged:T,marker:F}}function A(E){return oc(E)?jt(E,{cachePrefixes:!1}):j(E)}async function q(E,$){let T=await R(E,!1,d(E),!1),F=await R(E,!1,p(E),!1);if(!T.record&&!F.record||$.state==="closed"&&(T.record||!F.record))throw new b("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(T.record&&F.record){let se=await jn.lstat(ft.join(r,d(E),l)),pe=await jn.lstat(ft.join(r,p(E),l)),Be={dev:se.dev,ino:se.ino,birthtime:se.birthtimeMs},tt={dev:pe.dev,ino:pe.ino,birthtime:pe.birthtimeMs};if(!gu(Be,tt)||!Cn(Be,tt))throw new b("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let U=F.record??T.record;if(U.revision!==$.revision||A(U)!==$.recordHash||T.record&&T.record!==U&&A(T.record)!==$.recordHash)throw new b("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:U,active:!!T.record,history:!!F.record}}async function D(E){if(Is(E),!(await M(i,s,o)).exists)return"missing";let $=await C(E),T=await M(r,`${d(E)}/${l}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),F=await M(r,`${p(E)}/${l}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if($.marker?.schema===u){if(!T.exists&&!F.exists||$.marker.state==="closed"&&(T.exists||!F.exists))throw new b("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return $.marker.state}if(F.exists)throw new b("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return $.marker||T.exists||$.original.kind==="directory"||$.staged.exists?"active":"missing"}async function K(E,$,T){await $e(ft.join(r,c(E)),JSON.stringify({schema:u,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:E,state:$,revision:T.revision,recordHash:A(T)})+`
|
|
173
|
+
`,{containedRoot:r,requireAtomicPublication:!0})}async function L(E){let $=(await C(E)).marker;if(!$||!["closing","reopening"].includes($.state))return;let T=$.state==="closing",F=(await q(E,$)).record,U=await q(E,$),se=T?d(E):p(E),pe=T?p(E):d(E);await St(r,pe,{label:"RuntimeStore 历史目标"});let Be=ft.join(r,se,l),tt=ft.join(r,pe,l),hn=T?U.active:U.history;(T?U.history:U.active)||(await M(r,`${se}/${l}`,{label:"RuntimeStore 历史源",expected:"file"}),await M(r,pe,{label:"RuntimeStore 历史目标",expected:"directory"}),await jn.link(Be,tt),await q(E,$)),await ne(ft.dirname(tt)),await ne(ft.dirname(ft.dirname(tt))),await ne(r),hn&&(await q(E,$),await lr(Be,{containedRoot:r,beforeRemove:async()=>{await q(E,$)}}),await ne(ft.dirname(Be))),T?await K(E,"closed",F):await z(E,"ready",!1);let v=await Y(E,!1);if(!v||v.revision!==F.revision||A(v)!==A(F))throw new b("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function Z(E,$,T){return Is(E),Zd($),Le(E,async()=>{await L(E);let F=(await C(E)).marker,U;if(F?.schema===u){if(T&&F.state==="reopening")throw new b("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!T&&F.state==="closing")throw new b("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(U=(await q(E,F)).record,U.revision!==$)return!1;if(T&&F.state==="closed")return!0}else{if(U=(await re(E,!1)).record,!U||U.revision!==$)return!1;if(!T)return!0}return await K(E,T?"closing":"reopening",U),await L(E),!0})}async function Y(E,$=!0){if(Is(E),!(await M(i,s,o)).exists)return null;let T=await C(E);if(T.marker?.schema===u){let{record:se}=await q(E,T.marker);return $?an(se):se}if((await R(E,!1,p(E),!1)).record)throw new b("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let U=await R(E,!1,d(E),$);if(U.record){if(!T.marker&&!(await C(E)).marker)throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return U.record}if(T.original.kind==="directory"){let se=(await R(E)).record;if(!se&&(await C(E)).original.kind!=="directory")throw new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return se}if(T.marker?.state==="ready")throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(T.staged.exists){let se;try{se=(await R(E,!1,`${d(E)}/legacy`)).record}catch(pe){throw(await C(E)).marker?.state==="ready"?new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):pe}if(!se){let pe=await C(E);if(!pe.staged.exists||pe.marker?.state==="ready")throw new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return se}return null}async function fe(E,$=!0){for(let T=0;;T+=1)try{return await Y(E,$)}catch(F){let U=F instanceof Ot&&F.reason==="changed",se=["ENOENT","ENOTDIR"].includes(F.code??""),pe=F instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(F.message);if(!U&&!se&&!pe||T>=15)throw F}}async function z(E,$,T){await $e(ft.join(r,c(E)),JSON.stringify({schema:f,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:E,state:$})+`
|
|
174
|
+
`,{containedRoot:r,exclusive:T,requireAtomicPublication:!0})}async function ne(E){let $;try{$=await jn.open(E,"r"),await $.sync()}catch(T){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(T.code??""))throw T}finally{await $?.close()}}async function Le(E,$){if(await St(i,s,o),(await M(r,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new b("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await St(r,d(E),{label:"RuntimeStore run"}),await ne(ft.join(r,a)),await ne(r);try{return e.singleWriter?await $():await ax(ft.join(r,d(E),h),$)}catch(F){throw["ENOTSUP","EOPNOTSUPP"].includes(F.code??"")?new b("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):F}}async function I(E,$,T,F=Qd($)){let U=ft.join(r,d(E)),se=T.legacyRevision,{encoded:pe,json:Be}=F,tt=pe.pool?{record:pe.record,legacyRevision:se,pool:pe.pool}:{record:$,legacyRevision:se},hn=pe.pool?"comet.runtime-store-snapshot.v3":m,Ae=`{"schema":${JSON.stringify(hn)},${Be.slice(1,-1)},"legacyRevision":${JSON.stringify(se)},"hash":${JSON.stringify(j(tt))}}
|
|
175
|
+
`;await $e(ft.join(U,l),Ae,{containedRoot:r,exclusive:!T.compacted,requireAtomicPublication:!0}),T.formatPresent||await z(E,"ready",!1)}async function V(E,$){if($===null)return;let T=`${d(E)}/legacy`,F=await M(r,T,{label:"RuntimeStore legacy",expected:"directory"});if(F.exists)try{for(let U of await jn.readdir(F.target,{withFileTypes:!0}))U.isFile()&&!U.isSymbolicLink()&&g.test(U.name)&&Number(U.name.slice(0,-5))<=$&&await lr(ft.join(F.target,U.name),{containedRoot:r});await M(r,T,{label:"RuntimeStore legacy",expected:"directory"}),await jn.rmdir(F.target).catch(U=>{if(U.code!=="ENOTEMPTY"&&U.code!=="EEXIST")throw U})}catch(U){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${U instanceof Error?U.message:String(U)}
|
|
176
|
+
`)}}async function re(E,$=!0){let T=(await C(E)).marker;if(T?.writerProtocol&&T.writerProtocol!==e.writerProtocol)throw new b("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await L(E);let F=await C(E);if(F.marker?.schema===u)throw new b("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await R(E,!1,p(E),!1)).record)throw new b("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let se=await R(E,!1,d(E),$);if(se.record&&!F.marker)throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(F.original.kind==="directory"){await R(E,!0);let Be=await jn.lstat(F.original.target);await M(i,`${s}/${c(E)}`,o),await M(r,d(E),o),await jn.rename(F.original.target,F.staged.target);let tt=await jn.lstat(F.staged.target);if(!tt.isDirectory()||tt.isSymbolicLink()||!Cn({dev:Be.dev,ino:Be.ino,birthtime:Be.birthtimeMs},{dev:tt.dev,ino:tt.ino,birthtime:tt.birthtimeMs}))throw new b("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await ne(ft.join(r,d(E))),await ne(r),F=await C(E)}if(!F.marker){try{await z(E,"pending",!0)}catch(Be){throw["EEXIST","EISDIR","ENOTDIR"].includes(Be.code??"")?new b("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):Be}F=await C(E)}let pe=se;if(!pe.record&&F.marker?.state==="ready")throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!pe.record&&F.staged.exists?(pe=await R(E,!0,`${d(E)}/legacy`),pe.record&&(await I(E,pe.record,pe),pe={...pe,compacted:!0,formatPresent:!0})):pe.record&&F.marker?.state==="pending"&&await z(E,"ready",!1),pe.record&&(pe.formatPresent=!0,await V(E,pe.legacyRevision)),pe}return{queryScope:`file:${fx("sha256").update(r).digest("hex")}`,read:fe,readProjection:E=>fe(E,!1),readPartitionMetadata:D,settleRun:E=>ci(async()=>await D(E)==="missing"?"missing":Le(E,async()=>{await L(E);let $=(await C(E)).marker;return $&&e.writerProtocol&&$.writerProtocol!==e.writerProtocol&&await $e(ft.join(r,c(E)),JSON.stringify({...$,writerProtocol:e.writerProtocol})+`
|
|
177
|
+
`,{containedRoot:r,requireAtomicPublication:!0}),D(E)})),closeRun:(E,$)=>ci(()=>Z(E,$,!0)),reopenRun:(E,$)=>ci(()=>Z(E,$,!1)),async readDisposition(E){if(!await fe(E,!1))return"missing";let T=(await C(E)).marker;return T?.schema===u?T.state:"active"},async restoreCheckpoint(E,$,T){let F=JSON.parse(HF(E,$,T));return n(F),Le(E,async()=>{let U=await re(E);return BF(U.record,$,F,t)?(await I(E,F,U),!0):!1})},compareAndSwap:async(E,$,T)=>He(E,$,T)(),prepareCompareAndSwap:He};function He(E,$,T){FF(E,$,T,!1),n(T);let{json:F}=Qd(T),U=JSON.parse(F);return()=>Le(E,async()=>{let se=await re(E,!1);return(se.record?.revision??null)!==$?!1:(await I(E,U.record,se,{encoded:U,json:F}),!0)})}}ve();import{isDeepStrictEqual as mx}from"node:util";var It="run_checkpoint",Nw="comet.workflow-run-checkpoint.v1",VF=/^portable-[a-f0-9]{64}$/u;function ef(e){return VF.test(e)?e:`portable-${j(e)}`}function tf(e){let t=ux(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:j(t)}:e}function Hc(e,t){return mx(e,t)||mx(e,tf(t))}function hx(e){return{...e,revision:1,actions:e.actions.map(t=>{let n=new Set((t.rejectedOutcomes??[]).map(i=>i.outcome.outcomeId)),r={...t,receipts:t.receipts.filter(i=>!n.has(i.outcomeId)).map(i=>({...i}))};if(delete r.rejectedOutcomes,t.claim){let i=ef(t.claim.token);if(r.claim={...t.claim,token:i},t.executionStop&&(r.executionStop={...t.executionStop,claimToken:i}),t.cancellation&&(r.cancellation={...t.cancellation,claimToken:i}),t.outcome){r.outcome={...t.outcome,claimToken:i};let s=r.receipts.find(o=>o.outcomeId===t.outcome.outcomeId);s&&(s.hash=j(r.outcome))}}return t.status==="running"&&(r.status="unknown",r.reason="Portable recovery requires reconciliation of external execution"),r})}}var gx={hash:jt,visitResults:rd,validateOrigins:id};function UF(e){let t=cc(hx(e),e.runId,gx),n=jt(t);return{schema:Nw,hash:n,run:t,sourceRevision:e.revision,sourceHash:j({hash:n,sourceRevision:e.revision})}}function Pi(e){let t=Ro(hx(e),e.runId),n=j(t);return{schema:Nw,hash:n,run:t,sourceRevision:e.revision,sourceHash:j({hash:n,sourceRevision:e.revision})}}function wx(e,t,n={},r=!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`);In(e);let i=e;if(![Nw,"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"&&j({record:i.run,pool:i.pool})!==i.storageHash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let s=i.schema==="comet.workflow-run-checkpoint.v2"?sd(i.run,i.pool,!r):i.run;if((r?jt:j)(s)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=r?cc(s,t,gx):Ro(s,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==j({hash:i.hash,sourceRevision:i.sourceRevision}))throw new Error(`Portable Run checkpoint revision for ${t} is invalid or changed`);if(n.preserveSourceRevision)return{...o,revision:i.sourceRevision}}return o}function yn(e,t,n={}){return wx(e,t,n)}function nf(e,t,n={}){return wx(e,t,n,!0)}function _s(e,t){if(e===void 0)return!1;let n=nf(e,t.runId,{preserveSourceRevision:!0});if(!n)return!1;let r=e,i=UF(t);return r.hash===i.hash&&r.sourceRevision===i.sourceRevision&&r.sourceHash===i.sourceHash&&n.revision===t.revision}function Ps(e){let t=structuredClone(e);for(let n of t.actions)n.claim&&!n.executionOrigin&&(n.executionOrigin={workflow:{...e.workflow}});return t}function Bc(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:ef(t.claim.token)}}var yx=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],XF={"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 QF(e){return e.toISOString().slice(0,10)}function ye(e,t,n,r){let i=e[n];e[n]=r,i!==r&&t.push({field:n,from:i,to:r})}function bt(e,t,n={}){let r=XF[t];if(e.phase!==r.from)throw new Error(`Cannot apply ${t}: phase is '${e.phase}', expected '${r.from}'`);let i={...e},s=[],o=e.checkEpoch??0;if(!Number.isSafeInteger(o)||o<0||o===Number.MAX_SAFE_INTEGER)throw new Error("Invalid Classic check epoch");ye(i,s,"checkEpoch",o+1);let c=n.now??new Date;if(t==="open-complete")ye(i,s,"phase",i.workflow==="full"?"design":"build");else if(t==="design-complete")ye(i,s,"phase","build");else if(t==="build-complete"){let l=i.verifyResult==="fail";ye(i,s,"phase","verify"),ye(i,s,"verifyResult","pending"),ye(i,s,"branchStatus","pending"),l||ye(i,s,"verificationReport",null)}else if(t==="verify-pass")ye(i,s,"verifyResult","pass"),ye(i,s,"verifyFailures",0),ye(i,s,"phase","archive"),ye(i,s,"verifiedAt",QF(c)),ye(i,s,"archiveConfirmation","pending"),ye(i,s,"branchStatus","pending");else if(t==="verify-fail")ye(i,s,"verifyResult","fail"),ye(i,s,"verifyFailures",i.verifyFailures+1),ye(i,s,"phase","build"),ye(i,s,"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}'`);ye(i,s,"workflow","full"),ye(i,s,"classicProfile","full"),ye(i,s,"phase","design"),ye(i,s,"designDoc",null),ye(i,s,"buildPause",null),ye(i,s,"buildMode",null),ye(i,s,"subagentDispatch",null),ye(i,s,"tddMode",null),ye(i,s,"reviewMode",null),ye(i,s,"isolation",null),ye(i,s,"boundBranch",null),ye(i,s,"verifyMode",null),ye(i,s,"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`);ye(i,s,"archiveConfirmation","confirmed")}else if(t==="archive-reopen"){if(i.archived)throw new Error(`Cannot apply ${t}: already archived`);ye(i,s,"verifyResult","pending"),ye(i,s,"verifyFailures",0),ye(i,s,"phase","verify"),ye(i,s,"verifiedAt",null),ye(i,s,"archiveConfirmation",null),ye(i,s,"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`);ye(i,s,"archived",!0)}return{classic:i,effects:s,definition:r}}function rf(e){let t=e.state,n=[...e.actions].reverse().find(o=>o.stepId===t.workflow+".verify.run"),r=[...e.actions].reverse().find(o=>o.stepId===t.workflow+".verify.check"),i=e.evidenceWaits?.slice().reverse().find(o=>o.stepId===t.workflow+".verify.check.evidence");if(!n||!r||r.executionOrigin?.workflow.version!=="1"||r.status!=="succeeded"||r.outcome?.status!=="succeeded"||i?.status!=="resolved"||i.results[r.stepId]?.sequence!==e.actionContexts[r.id]?.sequence||e.actionContexts[r.id]?.results[n.stepId]?.sequence!==e.actionContexts[n.id]?.sequence)return null;let s=r.outcome.output;return s.scope!=="verify"||s.exitCode!==0||s.tier!=="full"||!Array.isArray(s.argv)||!s.argv.length||typeof s.receiptRef!="string"||typeof s.contentHash!="string"||i.receipt?.ref!==s.receiptRef||i.receipt.contentHash!==s.contentHash?null:{action:r,output:s}}function $w(e,t,n){let r=er(t),i=j(r);if(e.workflow.version===r.version&&e.workflow.hash===i)return e;if(e.workflow.version===r.version)throw new Error("Classic 当前 Run 的 definition hash 不匹配;不能作为旧业务数据重新绑定。");if(!["1","2"].includes(e.workflow.version)||e.workflow.id!==r.id)throw new Error("Classic Run 不属于可升级的内置协议");let s=Ps(e),o=d=>Object.hasOwn(r.steps,d),c=new Set;for(let d of s.actions)!o(d.stepId)&&["pending","running","unknown"].includes(d.status)&&(c.add(d.stepId),d.status="cancelled",d.reason="旧检查调度已移交 Agent 平台;原进程结果未确认,不代表已经停止或通过。");for(let d of[...s.waits,...s.evidenceWaits??[]])!o(d.stepId)&&d.status==="pending"&&(c.add(d.stepId),d.status="cancelled");let l=s.ready;s.ready=l.filter(d=>o(d.to)&&(d.from===null||o(d.from)));for(let d of l)(!o(d.to)||d.from!==null&&!o(d.from))&&c.add(d.to);if(e.status==="failed"&&e.reason?.startsWith("ACTION_FAILED: ")){let d=e.reason.slice(15);o(d)||c.add(d)}let f=s.state;if(e.workflow.version==="1"&&f.phase==="verify"&&s.evidenceWaits?.some(d=>d.status==="pending"&&d.stepId.endsWith(".verify.report.evidence")))for(let d of s.evidenceWaits)d.status==="pending"&&d.stepId.endsWith(".verify.report.evidence")&&(d.status="cancelled",c.add(d.stepId));let a=s.actions.some(d=>["pending","running","unknown"].includes(d.status))||s.waits.some(d=>d.status==="pending")||s.evidenceWaits?.some(d=>d.status==="pending");if(c.size&&!a&&!s.ready.length&&!["completed","cancelled"].includes(e.status)){let d=[...s.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"&&n?n.apply({run:s,event:{kind:"action-outcome",stepId:d.stepId,outcome:d.outcome}}):void 0;p?s.state=p.state:f.phase==="build"&&(s.state=bt(f,"build-complete").classic);let u=s.actionContexts[d.id];for(let m of p?.next??[f.workflow+".verify.run"])s.ready.push({from:d.stepId,to:typeof m=="string"?m:m.stepId,...typeof m=="string"?{}:{activation:m.input},results:{...u.results,[d.stepId]:{sequence:u.sequence,value:d.outcome.output}}});s.status="running",delete s.reason}s.workflow={id:r.id,version:r.version,hash:i};for(let d of Object.keys(s.definitionHashes))JSON.parse(d)[0]===r.id&&delete s.definitionHashes[d];return s.definitionHashes[JSON.stringify([r.id,r.version])]=i,s}import sB from"node:path";rn();rn();Ht();ve();import rB from"node:path";var ZF="@rpamis/comet",NY=`https://registry.npmjs.org/${ZF}/latest`;Fa();function Lw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ns=Lw();function Ax(e){Ns=e}var Os={exec:()=>null};function Fo(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function ke(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(i,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(Ft.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,t)};return r}var eH=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Ft={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:Fo(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Fo(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Fo(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Fo(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Fo(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Fo(e=>new RegExp(`^ {0,${e}}>`))},tH=/^(?:[ \t]*(?:\n|$))+/,nH=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,rH=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Kc=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,iH=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ww=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,xx=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ix=ke(xx).replace(/bull/g,Ww).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(),sH=ke(xx).replace(/bull/g,Ww).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(),Mw=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,oH=/^[^\n]+/,Fw=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,aH=ke(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Fw).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),cH=ke(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ww).getRegex(),lf="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",Hw=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,lH=ke("^ {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",Hw).replace("tag",lf).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),_x=e=>ke(Mw).replace("hr",Kc).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",lf).getRegex(),uH=_x(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),dH=_x(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),fH=ke(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",dH).getRegex(),Bw={blockquote:fH,code:nH,def:aH,fences:rH,heading:iH,hr:Kc,html:lH,lheading:Ix,list:cH,newline:tH,paragraph:uH,table:Os,text:oH},vx=ke("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Kc).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",lf).getRegex(),pH={...Bw,lheading:sH,table:vx,paragraph:ke(Mw).replace("hr",Kc).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",vx).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",lf).getRegex()},mH={...Bw,html:ke(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Hw).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:Os,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ke(Mw).replace("hr",Kc).replace("heading",` *#{1,6} *[^
|
|
178
|
+
]`).replace("lheading",Ix).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},hH=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,gH=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Px=/^( {2,}|\\)\n(?!\s*$)/,wH=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Fr=/[\p{P}\p{S}]/u,Ho=/[\s\p{P}\p{S}]/u,zc=/[^\s\p{P}\p{S}]/u,yH=ke(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ho).getRegex(),vH=/[\p{Pi}\p{Ps}"']/u,Ox=/(?!~)[\p{P}\p{S}]/u,kH=/(?!~)[\s\p{P}\p{S}]/u,bH=/(?:[^\s\p{P}\p{S}]|~)/u,RH=ke(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",eH?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Tx=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,CH=ke(Tx,"u").replace(/punct/g,Fr).getRegex(),SH=ke(Tx,"u").replace(/punct/g,Ox).getRegex(),EH=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,AH=ke(EH,"u").replace(/openQuote/g,vH).replace(/punct/g,Fr).getRegex(),Nx="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",xH=ke(Nx,"gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Ho).replace(/punct/g,Fr).getRegex(),IH=ke(Nx,"gu").replace(/notPunctSpace/g,bH).replace(/punctSpace/g,kH).replace(/punct/g,Ox).getRegex(),_H="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",PH=ke(_H,"gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Ho).replace(/punct/g,Fr).getRegex(),OH=ke("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Ho).replace(/punct/g,Fr).getRegex(),TH="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",NH=ke(TH,"gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Ho).replace(/punct/g,Fr).getRegex(),$H=ke(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Fr).getRegex(),jH="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",DH=ke(jH,"gu").replace(/notPunctSpace/g,zc).replace(/punctSpace/g,Ho).replace(/punct/g,Fr).getRegex(),qH=ke(/\\(punct)/,"gu").replace(/punct/g,Fr).getRegex(),LH=ke(/^<(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(),WH=ke(Hw).replace("(?:-->|$)","-->").getRegex(),MH=ke("^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",WH).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),of=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,FH=ke(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",of).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),$x=ke(/^!?\[(label)\]\[(ref)\]/).replace("label",of).replace("ref",Fw).getRegex(),jx=ke(/^!?\[(ref)\](?:\[\])?/).replace("ref",Fw).getRegex(),HH=ke("reflink|nolink(?!\\()","g").replace("reflink",$x).replace("nolink",jx).getRegex(),kx=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Vw={_backpedal:Os,anyPunctuation:qH,autolink:LH,blockSkip:RH,br:Px,code:gH,del:Os,delLDelim:Os,delRDelim:Os,emStrongLDelim:CH,emStrongRDelimAst:xH,emStrongRDelimUnd:OH,escape:hH,link:FH,nolink:jx,punctuation:yH,reflink:$x,reflinkSearch:HH,tag:MH,text:wH,url:Os},BH={...Vw,emStrongLDelim:AH,emStrongRDelimAst:PH,emStrongRDelimUnd:NH,link:ke(/^!?\[(label)\]\((.*?)\)/).replace("label",of).getRegex(),reflink:ke(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",of).getRegex()},jw={...Vw,emStrongRDelimAst:IH,emStrongLDelim:SH,delLDelim:$H,delRDelim:DH,url:ke(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",kx).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:ke(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",kx).getRegex()},VH={...jw,br:ke(Px).replace("{2,}","*").getRegex(),text:ke(jw.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},sf={normal:Bw,gfm:pH,pedantic:mH},Vc={normal:Vw,gfm:jw,breaks:VH,pedantic:BH},UH={"&":"&","<":"<",">":">",'"':""","'":"'"},bx=e=>UH[e];function kr(e,t){if(t){if(Ft.escapeTest.test(e))return e.replace(Ft.escapeReplace,bx)}else if(Ft.escapeTestNoEncode.test(e))return e.replace(Ft.escapeReplaceNoEncode,bx);return e}function Rx(e){try{e=encodeURI(e).replace(Ft.percentDecode,"%")}catch{return null}return e}function Cx(e,t){let n=e.replace(Ft.findPipe,(s,o,c)=>{let l=!1,f=o;for(;--f>=0&&c[f]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Ft.splitPipe),i=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),t)if(r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;i<r.length;i++)r[i]=r[i].trim().replace(Ft.slashPipe,"|");return r}function Oi(e,t,n){let r=e.length;if(r===0)return"";let i=0;for(;i<r;){let s=e.charAt(r-i-1);if(s===t&&!n)i++;else if(s!==t&&n)i++;else break}return e.slice(0,r-i)}function Sx(e){let t=e.split(`
|
|
179
|
+
`),n=t.length-1;for(;n>=0&&Ft.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
180
|
+
`)}function KH(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function zH(e,t=0){let n=t,r="";for(let i of e)if(i===" "){let s=4-n%4;r+=" ".repeat(s),n+=s}else r+=i,n++;return r}function Ex(e,t,n,r,i){let s=t.href,o=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!";r.state.inLink=!0;let f=r.state.linkEmitted,a=r.state.inRawBlock;r.state.linkEmitted=!1;let d=r.inlineTokens(c),p=r.state.linkEmitted;if(r.state.linkEmitted=f,r.state.inLink=!1,!l){if(p){r.state.inRawBlock=a;return}r.state.linkEmitted=!0}return{type:l?"image":"link",raw:n,href:s,title:o,text:c,tokens:d}}function JH(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
181
|
+
`).map(s=>{let o=s.match(n.other.beginningSpace);if(o===null)return s;let[c]=o;return c.length>=i.length?s.slice(i.length):s}).join(`
|
|
182
|
+
`)}var af=class{options;rules;lexer;constructor(e){this.options=e||Ns}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 n=this.options.pedantic?t[0]:Sx(t[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=JH(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=Oi(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:Oi(t[0],`
|
|
183
|
+
`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Oi(t[0],`
|
|
184
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Oi(t[0],`
|
|
185
|
+
`).split(`
|
|
186
|
+
`),r="",i="",s=[];for(;n.length>0;){let o=!1,c=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))c.push(n[l]),o=!0;else if(!o)c.push(n[l]);else break;n=n.slice(l);let f=c.join(`
|
|
187
|
+
`),a=f.replace(this.rules.other.blockquoteSetextReplace,`
|
|
188
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
189
|
+
${f}`:f,i=i?`${i}
|
|
190
|
+
${a}`:a;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(a,s,!0),this.lexer.state.top=d,n.length===0)break;let p=s.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let u=p,m=n.join(`
|
|
191
|
+
`),h=u.raw+`
|
|
192
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(h);s[s.length-1]=g,r=`${r}
|
|
193
|
+
${m}`,i=i.substring(0,i.length-u.text.length)+g.text;break}else if(p?.type==="list"){let u=p,m=u.raw+`
|
|
194
|
+
`+n.join(`
|
|
195
|
+
`),h=this.list(m);s[s.length-1]=h,r=r.substring(0,r.length-p.raw.length)+h.raw,i=i.substring(0,i.length-u.raw.length)+h.raw,n=m.substring(s.at(-1).raw.length).split(`
|
|
196
|
+
`);continue}}return{type:"blockquote",raw:r,tokens:s,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),o=!1;for(;e;){let l=!1,f="",a="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;f=t[0],e=e.substring(f.length);let d=zH(t[2].split(`
|
|
197
|
+
`,1)[0],t[1].length),p=e.split(`
|
|
198
|
+
`,1)[0],u=!d.trim(),m=0;if(this.options.pedantic?(m=2,a=d.trimStart()):u?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),u&&this.rules.other.blankLine.test(p)&&(f+=p+`
|
|
199
|
+
`,e=e.substring(p.length+1),l=!0),!l){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),y=this.rules.other.htmlBeginRegex(m),R=this.rules.other.blockquoteBeginRegex(m);for(;e;){let C=e.split(`
|
|
200
|
+
`,1)[0],A;if(p=C,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),A=p):A=p.replace(this.rules.other.tabCharGlobal," "),w.test(p)||k.test(p)||y.test(p)||R.test(p)||h.test(p)||g.test(p))break;if(A.search(this.rules.other.nonSpaceChar)>=m||!p.trim())a+=`
|
|
201
|
+
`+A.slice(m);else{if(u||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||k.test(d)||g.test(d))break;a+=`
|
|
202
|
+
`+p}u=!p.trim(),f+=C+`
|
|
203
|
+
`,e=e.substring(C.length+1),d=A.slice(m)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(f)&&(o=!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 l of i.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!i.loose){let f=l.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 l of i.items){let f=l.tokens[0];if(l.task&&(f?.type==="text"||f?.type==="paragraph")){l.text=l.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(l.raw);if(a){let d={type:"checkbox",raw:a[0]+" ",checked:a[0]!=="[ ]"};l.checked=d.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1)}if(i.loose)for(let l of i.items){l.loose=!0;for(let f of l.tokens)f.type==="text"&&(f.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=Sx(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=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:n,raw:Oi(t[0],`
|
|
204
|
+
`),href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Cx(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
205
|
+
`):[],s={type:"table",raw:Oi(t[0],`
|
|
206
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let o of r)this.rules.other.tableAlignRight.test(o)?s.align.push("right"):this.rules.other.tableAlignCenter.test(o)?s.align.push("center"):this.rules.other.tableAlignLeft.test(o)?s.align.push("left"):s.align.push(null);for(let o=0;o<n.length;o++)s.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:s.align[o]});for(let o of i)s.rows.push(Cx(o,s.header.length).map((c,l)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:s.align[l]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:Oi(t[0],`
|
|
207
|
+
`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
|
|
208
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}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 n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=Oi(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=KH(t[2],"()");if(s===-2)return;if(s>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Ex(t,{href:r&&r.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 n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Ex(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,s,o,c=i,l=0,f=r[0][0],a=n===f,d=f==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.exec(t))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(o=[...s].length,r[3]||r[4]){c+=o;continue}else if(r[5]||r[6]){if(i%3&&!((i+o)%3)){l+=o;continue}if(a)break}if(c-=o,c>0)continue;o=Math.min(o,o+c+l);let p=[...r[0]][0].length,u=e.slice(0,i+r.index+p+o);if(Math.min(i,o)%2){let h=u.slice(1,-1);return{type:"em",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}let m=u.slice(2,-2);return{type:"strong",raw:u,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,s,o,c=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+i);(r=l.exec(t))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s||(o=[...s].length,o!==i))continue;if(r[3]||r[4]){c+=o;continue}if(c-=o,c>0)continue;o=Math.min(o,o+c);let f=[...r[0]][0].length,a=e.slice(0,i+r.index+f+o),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 n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Dn=class Dw{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ns,this.options.tokenizer=this.options.tokenizer||new af,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 n={other:Ft,block:sf.normal,inline:Vc.normal};this.options.pedantic?(n.block=sf.pedantic,n.inline=Vc.pedantic):this.options.gfm&&(n.block=sf.gfm,this.options.breaks?n.inline=Vc.breaks:n.inline=Vc.gfm),this.tokenizer.rules=n}static get rules(){return{block:sf,inline:Vc}}static lex(t,n){return new Dw(n).lex(t)}static lexInline(t,n){return new Dw(n).inlineTokens(t)}lex(t){t=t.replace(Ft.carriageReturn,`
|
|
209
|
+
`),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(Ft.tabCharGlobal," ").replace(Ft.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let s;if(this.options.extensions?.block?.some(c=>(s=c.call({lexer:this},t,n))?(t=t.substring(s.raw.length),n.push(s),!0):!1))continue;if(s=this.tokenizer.space(t)){t=t.substring(s.raw.length);let c=n.at(-1);s.raw.length===1&&c!==void 0?c.raw+=`
|
|
210
|
+
`:n.push(s);continue}if(s=this.tokenizer.code(t)){t=t.substring(s.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
211
|
+
`)?"":`
|
|
212
|
+
`)+s.raw,c.text+=`
|
|
213
|
+
`+s.text,this.inlineQueue.at(-1).src=c.text):n.push(s);continue}if(s=this.tokenizer.fences(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.heading(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.hr(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.blockquote(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.list(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.html(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.def(t)){t=t.substring(s.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
214
|
+
`)?"":`
|
|
215
|
+
`)+s.raw,c.text+=`
|
|
216
|
+
`+s.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},n.push(s));continue}if(s=this.tokenizer.table(t)){t=t.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.lheading(t)){t=t.substring(s.raw.length),n.push(s);continue}let o=t;if(this.options.extensions?.startBlock){let c=1/0,l=t.slice(1),f;this.options.extensions.startBlock.forEach(a=>{f=a.call({lexer:this},l),typeof f=="number"&&f>=0&&(c=Math.min(c,f))}),c<1/0&&c>=0&&(o=t.substring(0,c+1))}if(this.state.top&&(s=this.tokenizer.paragraph(o))){let c=n.at(-1);r&&c?.type==="paragraph"?(c.raw+=(c.raw.endsWith(`
|
|
217
|
+
`)?"":`
|
|
218
|
+
`)+s.raw,c.text+=`
|
|
219
|
+
`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(s),r=o.length!==t.length,t=t.substring(s.raw.length);continue}if(s=this.tokenizer.text(t)){t=t.substring(s.raw.length);let c=n.at(-1);c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
220
|
+
`)?"":`
|
|
221
|
+
`)+s.raw,c.text+=`
|
|
222
|
+
`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}linkInText(t){if(!t.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let r of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(r[0])&&t.charAt(r.index-1)!=="!")return!0;for(let r of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=r[0],s=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(s+1,-1)))&&!(s>1&&this.linkInText(i.slice(1,s-1))))return!0}return!1}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t;if(this.tokens.links&&t.includes("[")){let c=this.tokenizer.rules.inline.reflinkSearch,l=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,l)+"]["+"a".repeat(f.length-a-2)+"]"}return"["+"a".repeat(f.length-2)+"]"};r=r.replace(c,l)}r=r.replace(this.tokenizer.rules.inline.anyPunctuation,c=>"+".repeat(c.length)),r=r.replace(this.tokenizer.rules.inline.blockSkip,(c,l,f)=>{let a=f?f.length:0;return c.slice(0,a)+"["+"a".repeat(c.length-a-2)+"]"}),r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let i=!1,s="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(s=""),i=!1;let c;if(this.options.extensions?.inline?.some(f=>(c=f.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let f=n.at(-1);c.type==="text"&&f?.type==="text"?(f.raw+=c.raw,f.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,r,s)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,r,s)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let l=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&&(l=t.substring(0,f+1))}if(c=this.tokenizer.inlineText(l)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(s=c.raw.slice(-1)),i=!0;let f=n.at(-1);f?.type==="text"?(f.raw+=c.raw,f.text+=c.text):n.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(this.options.silent)console.error(n);else throw new Error(n)}},cf=class{options;parser;constructor(e){this.options=e||Ns}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(Ft.notSpaceStart)?.[0],i=e.replace(Ft.endingNewline,"")+`
|
|
223
|
+
`;return r?'<pre><code class="language-'+kr(r)+'">'+(n?i:kr(i,!0))+`</code></pre>
|
|
224
|
+
`:"<pre><code>"+(n?i:kr(i,!0))+`</code></pre>
|
|
225
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
226
|
+
${this.parser.parse(e)}</blockquote>
|
|
227
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
228
|
+
`}hr(e){return`<hr>
|
|
229
|
+
`}list(e){let t=e.ordered,n=e.start,r="";for(let o=0;o<e.items.length;o++){let c=e.items[o];r+=this.listitem(c)}let i=t?"ol":"ul",s=t&&n!==1?' start="'+n+'"':"";return"<"+i+s+`>
|
|
230
|
+
`+r+"</"+i+`>
|
|
231
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
232
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
233
|
+
`}table(e){let t="",n="";for(let i=0;i<e.header.length;i++)n+=this.tablecell(e.header[i]);t+=this.tablerow({text:n});let r="";for(let i=0;i<e.rows.length;i++){let s=e.rows[i];n="";for(let o=0;o<s.length;o++)n+=this.tablecell(s[o]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
|
|
234
|
+
<thead>
|
|
235
|
+
`+t+`</thead>
|
|
236
|
+
`+r+`</table>
|
|
237
|
+
`}tablerow({text:e}){return`<tr>
|
|
238
|
+
${e}</tr>
|
|
239
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
240
|
+
`}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>${kr(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Rx(e);if(i===null)return r;e=i;let s='<a href="'+e+'"';return t&&(s+=' title="'+kr(t)+'"'),s+=">"+r+"</a>",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Rx(e);if(i===null)return kr(n);e=i;let s=`<img src="${e}" alt="${kr(n)}"`;return t&&(s+=` title="${kr(t)}"`),s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:kr(e.text)}},Uw=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}},tr=class qw{options;renderer;textRenderer;constructor(t){this.options=t||Ns,this.options.renderer=this.options.renderer||new cf,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Uw}static parse(t,n){return new qw(n).parse(t)}static parseInline(t,n){return new qw(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let i=t[r];if(this.options.extensions?.renderers?.[i.type]){let o=i,c=this.options.extensions.renderers[o.type].call({parser:this},o);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){n+=c||"";continue}}let s=i;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let o='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let s=t[i];if(this.options.extensions?.renderers?.[s.type]){let c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(s.type)){r+=c||"";continue}}let o=s;switch(o.type){case"escape":{r+=n.text(o);break}case"html":{r+=n.html(o);break}case"link":{r+=n.link(o);break}case"image":{r+=n.image(o);break}case"checkbox":{r+=n.checkbox(o);break}case"strong":{r+=n.strong(o);break}case"em":{r+=n.em(o);break}case"codespan":{r+=n.codespan(o);break}case"br":{r+=n.br(o);break}case"del":{r+=n.del(o);break}case"text":{r+=n.text(o);break}default:{let c='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return r}},Uc=class{options;block;constructor(e){this.options=e||Ns}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?Dn.lex:Dn.lexInline}provideParser(e=this.block){return e?tr.parse:tr.parseInline}},GH=class{defaults=Lw();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=tr;Renderer=cf;TextRenderer=Uw;Lexer=Dn;Tokenizer=af;Hooks=Uc;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{let i=r;for(let s of i.header)n=n.concat(this.walkTokens(s.tokens,t));for(let s of i.rows)for(let o of s)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(s=>{let o=i[s].flat(1/0);n=n.concat(this.walkTokens(o,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...o){let c=i.renderer.apply(this,o);return c===!1&&(c=s.apply(this,o)),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 s=t[i.level];s?s.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)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new cf(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let o=s,c=n.renderer[o],l=i[o];i[o]=(...f)=>{let a=c.apply(i,f);return a===!1&&(a=l.apply(i,f)),a||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new af(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let o=s,c=n.tokenizer[o],l=i[o];i[o]=(...f)=>{let a=c.apply(i,f);return a===!1&&(a=l.apply(i,f)),a}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new Uc;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let o=s,c=n.hooks[o],l=i[o];Uc.passThroughHooks.has(s)?i[o]=f=>{if(this.defaults.async&&Uc.passThroughHooksRespectAsync.has(s))return(async()=>{let d=await c.call(i,f);return l.call(i,d)})();let a=c.call(i,f);return l.call(i,a)}:i[o]=(...f)=>{if(this.defaults.async)return(async()=>{let d=await c.apply(i,f);return d===!1&&(d=await l.apply(i,f)),d})();let a=c.apply(i,f);return a===!1&&(a=l.apply(i,f)),a}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(o){let c=[];return c.push(s.call(this,o)),i&&(c=c.concat(i.call(this,o))),c}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Dn.lex(e,t??this.defaults)}parser(e,t){return tr.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},s=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return s(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 s(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return s(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 o=i.hooks?await i.hooks.preprocess(t):t,c=await(i.hooks?await i.hooks.provideLexer(e):e?Dn.lex:Dn.lexInline)(o,i),l=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let f=await(i.hooks?await i.hooks.provideParser(e):e?tr.parse:tr.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(f):f})().catch(s);try{i.hooks&&(t=i.hooks.preprocess(t));let o=(i.hooks?i.hooks.provideLexer(e):e?Dn.lex:Dn.lexInline)(t,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(e):e?tr.parse:tr.parseInline)(o,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(o){return s(o)}}}onError(e,t){return n=>{if(n.message+=`
|
|
241
|
+
Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+kr(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Ts=new GH;function De(e,t){return Ts.parse(e,t)}De.options=De.setOptions=function(e){return Ts.setOptions(e),De.defaults=Ts.defaults,Ax(De.defaults),De};De.getDefaults=Lw;De.defaults=Ns;function YH(...e){return Ts.use(...e),De.defaults=Ts.defaults,Ax(De.defaults),De}De.use=YH;De.walkTokens=function(e,t){return Ts.walkTokens(e,t)};De.parseInline=Ts.parseInline;De.Parser=tr;De.parser=tr.parse;De.Renderer=cf;De.TextRenderer=Uw;De.Lexer=Dn;De.lexer=Dn.lex;De.Tokenizer=af;De.Hooks=Uc;De.parse=De;var jY=De.options,DY=De.setOptions,XH=De.walkTokens,qY=De.parseInline;var LY=tr.parse,WY=Dn.lex;ve();function Bo(e){throw new b("INVALID_WORKFLOW",`${e};请修正适配契约或恢复已固定的依赖后继续`)}Ht();ve();ve();ve();ve();function iB(e){return(typeof e!="string"||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e))&&Bo("应用身份必须是小写名称"),e}async function qx(e,t,n){return pn({rootDir:rB.join(lt(e),"applications",iB(t)),mirroredRevisionPaths:["run.revision"]}).readPartitionMetadata(n)}function Jc(e){return e.ref==="classic-archive"&&(e.status==="running"||e.status==="unknown"||e.status==="cancelled"&&!!e.claim&&!e.outcome)}function $s(e){return e.status==="cancelled"&&e.children.length===0&&e.actions.every(t=>!["pending","running","unknown"].includes(t.status)&&!Jc(t))&&e.waits.every(t=>t.status!=="pending")&&(e.evidenceWaits??[]).every(t=>t.status!=="pending")&&e.ready.length===0}async function Kw(e,t,n){let r=n??await pr(e,"classic",t.runId,{readOnly:!0}),i=r&&!["classic-full","classic-hotfix","classic-tweak"].includes(r.application)?await qx(e,r.application,t.runId):await pn({rootDir:sB.join(lt(e),"sdk-runs/classic")}).readPartitionMetadata(t.runId),s=["active","closed"].includes(i),o=t.actions.filter(l=>l.status==="unknown"||l.status==="running"&&(l.rejectedOutcomes?.length??0)>0||l.status==="cancelled"&&Jc(l)),c=[...t.status==="cancelled"&&!$s(t)&&o.length===0?[{code:"classic-cancellation-business-unresolved",runId:t.runId,message:"原关联子 Run 或业务结果仍待核对;普通平台任务不提交进程停止回执。"}]:[],...s?[]:[{code:"storage-transaction-pending",runId:t.runId,message:`Classic 存储状态为 ${i},尚未完成核对或收尾`}],...o.map(l=>({code:"classic-execution-unresolved",runId:t.runId,actionId:l.id,message:"原业务结果尚未核对,不能重放执行"}))];return{stateReadable:!0,executionReconciled:o.length===0,storageSettled:s,healthy:c.length===0,issues:c}}function Lx(e,t){if(e.workflow.id===`comet-classic-${t}`)return!0;let n=/^comet-classic-(hotfix|tweak)$/u.exec(e.workflow.id)?.[1];return t==="full"&&!!n&&Gc(e,n)}function Gc(e,t){let n=e.state;return(t==="hotfix"||t==="tweak")&&e.workflow.id===`comet-classic-${t}`&&n?.workflow==="full"&&n.classicProfile==="full"&&e.waits.some(r=>r.stepId===`${t}.build.escalation-confirm`&&r.status==="resolved"&&r.decision?.choice==="upgrade"&&r.decision.proposalHash===r.proposalHash)}import Vs from"node:path";ve();kt();rn();import{promises as WV}from"node:fs";var Ey=Rt(Pt(),1);import t_ from"node:path";ve();gn();import LV from"node:path";Xi();var ky=Rt(Pt(),1);Jw();import{execFileSync as Li}from"node:child_process";import Jt from"node:path";import{isDeepStrictEqual as vy}from"node:util";Qt();ve();Qa();function br(e){if(e.workflow!=="full")return{missingFields:[],invalidFields:[]};let t=[],n=[];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"&&n.push({field:"subagent_dispatch",reason:"subagent_dispatch=confirmed 仅适用于 build_mode=subagent-driven-development"}),e.buildMode!=="direct"&&e.directOverride===!0&&n.push({field:"direct_override",reason:"direct_override=true 仅适用于 build_mode=direct"}),e.buildMode==="autonomous"&&e.reviewMode==="off"&&n.push({field:"review_mode",reason:"autonomous full build requires review_mode=standard or thorough"}),e.buildMode==="direct"&&e.directOverride!==!0&&n.push({field:"direct_override",reason:"full workflow direct execution requires direct_override=true"}),{missingFields:t,invalidFields:n}}function Bx(e){let t=br(e);return t.missingFields.length===0&&t.invalidFields.length===0}function Yc(e){return e.stepId==="full.build.configure"&&e.type==="invoke_skill"&&e.ref==="comet-build"&&(e.status==="running"||e.status==="unknown")&&e.claim?.executorId==="comet-classic-state"&&!!e.rejectedOutcomes?.some(({outcome:t,code:n})=>(n==="OUTCOME_REJECTED"||n==="OUTPUT_INVALID")&&t.status==="succeeded"&&t.actionId===e.id&&t.attempt===e.attempt&&t.inputHash===e.inputHash&&t.claimToken===e.claim?.token)}Qa();Wa();Ue();import{randomUUID as aV}from"node:crypto";function Xc(e){return e==="zh-CN"?"zh-CN":"en"}function Gw(e,t,n){return e==="zh-CN"?n:t}function Vx(e){let{name:t,locale:n}=e;return{summary:Gw(n,`Handoff context for ${t} was written and recorded; the Build phase can resume from it.`,`需求 ${t} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}function Ux(e){let{name:t,stepsOk:n,stepsTotal:r,dryRun:i,locale:s}=e,o=n===r;return i?{summary:Gw(s,`Archive dry run for ${t}: ${o?`all ${r} steps would succeed`:`${r-n} of ${r} steps would fail`}.`,`需求 ${t} 归档预演:${o?`全部 ${r} 步均可成功`:`${r-n}/${r} 步会失败`}。`)}:{summary:Gw(s,o?`Change ${t} was archived successfully (${n}/${r} steps).`:`Archive for ${t} stopped: ${r-n} of ${r} steps failed.`,o?`需求 ${t} 归档成功(${n}/${r} 步)。`:`需求 ${t} 归档中止:${r-n}/${r} 步失败。`)}}gn();Qe();mi();import{promises as yI}from"fs";import vn from"path";import{fileURLToPath as vI}from"url";ve();import Ni from"path";ve();Qt();Ue();gn();import Qc from"path";function pB(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Kx(e,t,n,r){let i=nt(n,"Classic handoff artifact pointer");if((await M(e,i,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await Nt(e),c=`${qe(e,o.changesDir)}/`,f=(o.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];_r(d);let p=a.slice(2),u=Qc.resolve(t);if(Qc.dirname(u)!==Qc.resolve(o.archiveDir))return null;let m=Qc.basename(u),h=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(m);if(m!==d&&h?.[1]!==d)return null;await M(e,qe(e,u),{label:"Classic archived change directory",expected:"directory"});let g=Qc.join(u,".comet",...p),w=qe(e,g);try{return await ce(e,w,r,{label:"Historical Classic archived handoff artifact"}),w}catch(k){if(pB(k))return null;throw k}}Ue();gn();import js from"node:path";Ue();Qe();async function zx(e,t,n,r={}){if(n.workflow!=="full"||n.buildMode!=="autonomous")return[];let i=[];if(r.requirePlan!==!1){let s=br(n);s.missingFields.includes("tdd_mode")&&i.push("tdd_mode must be selected for autonomous full build"),s.missingFields.includes("review_mode")&&i.push("review_mode must be selected for autonomous full build"),s.invalidFields.some(({field:o})=>o==="review_mode")&&i.push("review_mode must be standard or thorough for autonomous full build"),n.isolation||i.push("isolation must be selected for autonomous full build")}return(!n.designDoc||!await Ir(e,n.designDoc,"Classic autonomous design"))&&i.push("design_doc must reference a nonempty technical design for autonomous full build"),r.requirePlan!==!1&&(await Ds(e,n.plan,{requireNonempty:!0})).status!=="ready"&&i.push("plan must reference a nonempty implementation plan in the configured plans directory"),i}async function Ds(e,t,n={}){if(!t||t==="null")return{status:"missing",recordedPath:null};let r=await Nt(e),i=js.resolve(e,t),s=js.relative(r.superpowersPlansDir,i);return js.isAbsolute(t)||!s||s.startsWith(`..${js.sep}`)||js.isAbsolute(s)||s.includes(js.sep)||js.extname(s).toLowerCase()!==".md"?{status:"broken",recordedPath:t}:await Ge(e,t,{label:`Classic build plan ${t}`,expected:"file"})&&(!n.requireNonempty||(await le(e,t,{label:`Classic build plan ${t}`})).trim().length>0)?{status:"ready",recordedPath:t}:{status:"broken",recordedPath:t}}Qe();var mB=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,hB=/\s*<!-- comet-task:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->\s*$/u;function nr(e){let t=[],n=new Set,r=null;for(let[i,s]of e.split(/\r?\n/u).entries()){let o=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(s);if(o){r?o[1][0]===r.marker&&o[1].length>=r.length&&!o[2].trim()&&(r=null):r={marker:o[1][0],length:o[1].length};continue}if(r)continue;let c=mB.exec(s);if(!c)continue;let l=hB.exec(c[4]),f=l?.[1]??null;if(c[4].includes("<!-- comet-task:")&&(!l||c[4].slice(0,l.index).includes("<!-- comet-task:")))throw new Error(`Malformed Classic task ID at line ${i+1}`);if(f&&n.has(f))throw new Error(`Duplicate Classic task ID: ${f}`);f&&n.add(f);let a=c[4].slice(0,l?.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 Jx(e,t){let n=nr(e),r=new Set(t.map(i=>i.id).filter(Boolean));return{total:n.length,unmapped:n.filter(i=>!i.id||!r.has(i.id))}}function df(e,t){return Ni.relative(e,t).split(Ni.sep).join("/")}async function Zc(e,t,n,r,i){if(!n)return{code:t,satisfied:!1};let s=n.replaceAll("\\","/");if(i)return{code:t,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${i instanceof Error?i.message:String(i)}`};try{if(r){let c=r.artifactLayout==="legacy"?"docs":"legacy",l=qe(e,ja(e,c).openSpecRoot);if((s===l||s.startsWith(`${l}/`))&&(await M(e,s,{label:`${t} artifact`,expected:"file"})).exists)return{code:t,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await Wm(e,s,{label:`${t} artifact`});return{code:t,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:t,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function gB(e,t,n,r){try{r??=await Nt(e)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let i=await Zc(e,"design.handoff",n,r);if(!n||i.satisfied||i.detail)return i;try{let s=await Kx(e,t,n,Number.MAX_SAFE_INTEGER);return s?{...i,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:i}catch(s){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function Yw(e,t,n){return Zc(e,t,df(e,n))}async function wB(e,t){let n=Ni.join(t,"specs"),r;try{r=await gi(e,n)}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:r.length>0,source:r[0]?df(e,r[0]):void 0,detail:`${r.length} delta spec${r.length===1?"":"s"}`}}async function yB(e,t){let n,r=df(e,t);try{n=(await ce(e,r,Number.MAX_SAFE_INTEGER,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:r,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let i;try{i=nr(n)}catch(o){return{code:"build.tasks-complete",satisfied:!1,source:r,detail:`malformed tasks.md: ${o instanceof Error?o.message:String(o)}`}}let s=i.filter(o=>o.completed).length;return{code:"build.tasks-complete",satisfied:i.length>0&&s===i.length,source:r,detail:`${s} of ${i.length} tasks complete`}}function Vo(e,t){return e.some(n=>n.code===t&&n.satisfied)}async function Uo(e,t){let n=await it(e),r=t.classic,i=Ni.join(e,"proposal.md"),s=Ni.join(e,"design.md"),o=Ni.join(e,"tasks.md"),c=t.run?Ni.resolve(e,t.run.checkpointRef):Ni.join(e,".comet","checkpoint.json"),l,f;try{l=await Nt(n)}catch(d){f=d}let a=await Promise.all([Yw(n,"openspec.proposal",i),Yw(n,"openspec.design",s),Yw(n,"openspec.tasks",o),wB(n,e),Zc(n,"design.document",r?.designDoc??null,l,f),(async()=>{let d=await Zc(n,"build.plan",r?.plan??null,l,f);if(!d.satisfied)return d;try{let p=await Ds(n,r?.plan??null,{requireNonempty:r?.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)}}})(),yB(n,o),Zc(n,"verification.report",r?.verificationReport??null,l,f),gB(n,e,r?.handoffContext??null,l),(async()=>{try{return{code:"run.checkpoint",source:df(n,c),satisfied:await Ir(n,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:r?.archiveConfirmation==="confirmed"}),a}kt();mi();import{createHash as zB,randomUUID as JB}from"crypto";import{promises as ty}from"fs";import Hr from"path";function vB(e){return e.classicProfile??e.workflow}function kB(e){return e.isolation!==null&&Bx(e)}function bB(e){return(e.buildMode==="direct"||e.buildMode==="autonomous")&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function RB(e,t,n){if(e!=="full"&&t.verifyResult==="fail")return`${e}.build.execute`;if(e==="full"){if(Vo(n,"build.plan")&&t.buildPause==="plan-ready")return"full.build.plan-ready";if(!kB(t))return"full.build.configure";if(!Vo(n,"build.plan"))return"full.build.plan";if(t.verifyResult==="fail")return"full.build.fix"}else if(!bB(t))throw new Error(`${e} build configuration is incomplete`);return Vo(n,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function CB(e,t,n){return t.verifyResult!=="pass"||!Vo(n,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function SB(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 ff(e,t){let n=vB(e);if(e.archived&&e.phase!=="archive")throw new Error("archived=true requires phase=archive");if(e.archived)return"completed";if(n!=="full"&&e.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(e.phase){case"open":return`${n}.open`;case"design":return Vo(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return RB(n,e,t);case"verify":return CB(n,e,t);case"archive":return SB(n,e)}}nn();function Gx(e,t,n){return{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:n,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 lI,randomUUID as HB}from"crypto";import{promises as vt}from"fs";import pt from"path";var Qx=Rt(Pt(),1);import{promises as Xw}from"fs";import qn from"path";var EB=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],AB=["deterministic","adaptive"],xB=["function","mcp","script","agent"],IB=["none","read","write","external"],_B=["progress","step","completion"],PB=["artifact_exists","state_equals"];function qs(e,t,n){return new Error(`${e}: ${t} ${n}`)}function mn(e,t,n="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw qs(t,n,"must be an object")}function $i(e,t,n){if(!Array.isArray(e))throw qs(t,n,"must be an array")}function zt(e,t,n){if(typeof e!="string")throw qs(t,n,"must be a string")}function rr(e,t,n,r){t in e&&zt(e[t],n,`${r}.${t}`)}function Zx(e,t,n,r){if(t in e&&typeof e[t]!="boolean")throw qs(n,`${r}.${t}`,"must be a boolean")}function ji(e,t,n,r){if(typeof e!="string"||!t.includes(e))throw qs(n,r,`must be one of ${t.join(", ")}`)}function pf(e,t,n){$i(e,t,n),e.forEach((r,i)=>{zt(r,t,`${n}[${i}]`)})}function Yx(e,t,n){mn(e,t,n),zt(e.name,t,`${n}.name`),zt(e.description,t,`${n}.description`),Zx(e,"required",t,n)}function OB(e,t,n){mn(e,t,n),zt(e.id,t,`${n}.id`),rr(e,"source",t,n),rr(e,"version",t,n)}function TB(e,t,n){mn(e,t,n),zt(e.id,t,`${n}.id`),zt(e.role,t,`${n}.role`),rr(e,"instructions",t,n)}function NB(e,t,n){mn(e,t,n),zt(e.id,t,`${n}.id`),ji(e.kind,xB,t,`${n}.kind`),zt(e.source,t,`${n}.source`),ji(e.sideEffect,IB,t,`${n}.sideEffect`),Zx(e,"requiresConfirmation",t,n)}function $B(e,t,n){mn(e,t,n),ji(e.type,EB,t,`${n}.type`),rr(e,"ref",t,n),rr(e,"prompt",t,n),rr(e,"question",t,n),"options"in e&&pf(e.options,t,`${n}.options`)}function jB(e,t,n){mn(e,t,n),zt(e.id,t,`${n}.id`),$B(e.action,t,`${n}.action`),rr(e,"next",t,n),"completionEvals"in e&&pf(e.completionEvals,t,`${n}.completionEvals`)}function DB(e,t){let n="goal";mn(e,t,n),zt(e.statement,t,`${n}.statement`),$i(e.inputs,t,`${n}.inputs`),e.inputs.forEach((r,i)=>{Yx(r,t,`${n}.inputs[${i}]`)}),$i(e.outputs,t,`${n}.outputs`),e.outputs.forEach((r,i)=>{Yx(r,t,`${n}.outputs[${i}]`)}),pf(e.success,t,`${n}.success`)}function qB(e,t){let n="orchestration";mn(e,t,n),ji(e.mode,AB,t,`${n}.mode`),rr(e,"entry",t,n),"steps"in e&&($i(e.steps,t,`${n}.steps`),e.steps.forEach((r,i)=>{jB(r,t,`${n}.steps[${i}]`)}))}function eI(e,t){return mn(e,t),ji(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),ji(e.kind,["Skill"],t,"kind"),mn(e.metadata,t,"metadata"),zt(e.metadata.name,t,"metadata.name"),zt(e.metadata.version,t,"metadata.version"),zt(e.metadata.description,t,"metadata.description"),DB(e.goal,t),qB(e.orchestration,t),$i(e.skills,t,"skills"),e.skills.forEach((n,r)=>{OB(n,t,`skills[${r}]`)}),$i(e.agents,t,"agents"),e.agents.forEach((n,r)=>{TB(n,t,`agents[${r}]`)}),$i(e.tools,t,"tools"),e.tools.forEach((n,r)=>{NB(n,t,`tools[${r}]`)}),e}function tI(e,t){mn(e,t);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in e&&pf(e[n],t,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in e&&(typeof e[n]!="number"||!Number.isFinite(e[n])))throw qs(t,n,"must be a finite number");return e}function LB(e,t){return mn(e,t),"runtime"in e&&nI(e.runtime,t,"runtime"),e}function nI(e,t,n){return $i(e,t,n),e.forEach((r,i)=>{let s=`${n}[${i}]`;mn(r,t,s),zt(r.id,t,`${s}.id`),ji(r.scope,_B,t,`${s}.scope`),ji(r.type,PB,t,`${s}.type`),rr(r,"artifact",t,s),rr(r,"field",t,s),rr(r,"equals",t,s)}),e}async function Qw(e){let t=await Xw.readFile(e,"utf8");try{return(0,Qx.parse)(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw qs(e,"document",r)}}async function WB(e){try{return await Qw(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Xx(e){try{return await Xw.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function MB(e){let t=qn.join(e,"checks.yaml"),n=qn.join(e,"evals.yaml"),[r,i]=await Promise.all([Xx(t),Xx(n)]);if(i)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return r?{document:LB(await Qw(t),t)}:{document:null}}async function rI(e){let t=qn.resolve(e.root),n=qn.resolve(e.controlRoot);e.requireSkillMarkdown&&await Xw.access(qn.join(t,"SKILL.md"));let r=qn.join(n,"skill.yaml"),i=qn.join(n,"guardrails.yaml"),s=eI(await Qw(r),r),o=await WB(i),c=o===null?null:tI(o,i),l=await MB(n),f={allowedSkills:s.skills.map(a=>a.id),allowedAgents:s.agents.map(a=>a.id),allowedTools:s.tools.map(a=>a.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(a=>a.requiresConfirmation).map(a=>a.id)};return{root:t,packageKind:e.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...f,...c},evals:l.document?.runtime??[]}}async function iI(e){let t=qn.resolve(e);return rI({root:t,controlRoot:qn.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function sI(e){let t=qn.resolve(e);return rI({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function oI(e,t,n=qn.join(t,"package.json")){mn(e,n);let r=e.packageKind==="runtime"?"runtime":void 0,i=eI(e.definition,n),s=tI(e.guardrails,n),o=nI(e.evals,n,"evals"),c={allowedSkills:i.skills.map(l=>l.id),allowedAgents:i.agents.map(l=>l.id),allowedTools:i.tools.map(l=>l.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:i.tools.filter(l=>l.requiresConfirmation).map(l=>l.id)};return{root:qn.resolve(t),packageKind:r,definition:i,guardrails:{...c,...s},evals:o}}import aI from"path";function FB(e,t,n,r){e.type==="invoke_skill"&&!t.definition.skills.some(i=>i.id===e.ref)&&n.push(`step ${r} references undeclared skill: ${e.ref??"(missing)"}`),e.type==="call_tool"&&!t.definition.tools.some(i=>i.id===e.ref)&&n.push(`step ${r} references undeclared tool: ${e.ref??"(missing)"}`),e.type==="handoff"&&!t.definition.agents.some(i=>i.id===e.ref)&&n.push(`step ${r} references undeclared agent: ${e.ref??"(missing)"}`),e.type==="ask_user"&&!e.question&&n.push(`step ${r} ask_user action requires question`)}function cI(e){let t=[],{definition:n,guardrails:r,evals:i}=e;n.apiVersion!=="comet/v1alpha1"&&t.push("unsupported apiVersion"),n.kind!=="Skill"&&t.push("kind must be Skill"),n.metadata.name||t.push("metadata.name is required"),n.goal.statement||t.push("goal.statement is required"),r.maxIterations<1&&t.push("maxIterations must be at least 1"),r.maxRetriesPerAction<0&&t.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&t.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let c of s)o.has(c.id)&&t.push(`duplicate step id: ${c.id}`),o.add(c.id),FB(c.action,e,t,c.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&t.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let c of s){c.next&&!o.has(c.next)&&t.push(`step ${c.id} has unknown next step: ${c.next}`);for(let l of c.completionEvals??[])i.some(f=>f.id===l)||t.push(`step ${c.id} references unknown eval: ${l}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let c=aI.posix.normalize(o.source.replaceAll("\\","/"));(aI.isAbsolute(o.source)||c===".."||c.startsWith("../"))&&t.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of r.allowedSkills)n.skills.some(c=>c.id===o)||t.push(`guardrails allow undeclared skill: ${o}`);for(let o of r.allowedAgents)n.agents.some(c=>c.id===o)||t.push(`guardrails allow undeclared agent: ${o}`);for(let o of r.allowedTools)n.tools.some(c=>c.id===o)||t.push(`guardrails allow undeclared tool: ${o}`);return t}function mf(e){return Array.isArray(e)?e.map(mf):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,mf(n)])):e}function BB(e){return mf({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function VB(e){return pt.posix.normalize(e.replaceAll("\\","/"))}function Ko(e,t,n){let r=pt.relative(e,t);if(!(r===""||!pt.isAbsolute(r)&&!r.startsWith(`..${pt.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function uI(e,t,n){let r=VB(t);if(pt.posix.isAbsolute(r)||r===".."||r.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let i=pt.resolve(e,...r.split("/"));Ko(e,i,n);let s;try{s=await vt.realpath(i)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${t}`,{cause:o}):o}if(Ko(e,s,n),!(await vt.stat(s)).isFile())throw new Error(`${n} is not a file: ${t}`);return{path:r,content:await vt.readFile(s)}}async function UB(e){let t=await vt.realpath(e.root),n=e.packageKind==="runtime"?[]:[await uI(t,"SKILL.md","SKILL.md")];for(let r of e.definition.tools)r.kind==="script"&&n.push(await uI(t,r.source,`Script tool ${r.id}`));return n.sort((r,i)=>r.path.localeCompare(i.path))}function KB(e,t){let n=t.map(r=>({path:r.path,sha256:lI("sha256").update(r.content).digest("hex")}));return lI("sha256").update(JSON.stringify(mf({package:e,files:n}))).digest("hex")}function pI(e){return JSON.stringify(e,null,2)+`
|
|
242
|
+
`}async function mI(e){let t=BB(e),n=await UB(e);return{document:t,files:n,hash:KB(t,n)}}async function hf(e){return(await mI(e)).hash}async function dI(e){try{return await vt.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function fI(e,t){try{if((await vt.readFile(pt.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await vt.readFile(pt.join(e,"package.json"),"utf8")!==pI(t.document))throw new Error("package mismatch");for(let i of t.files)if(!(await vt.readFile(pt.join(e,...i.path.split("/")))).equals(i.content))throw new Error(`file mismatch: ${i.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${t.hash}`,{cause:n})}}async function Zw(e,t){let n=await mI(e),r=pt.resolve(t,".comet","skill-snapshots"),i=pt.join(r,n.hash);if(await vt.mkdir(r,{recursive:!0}),await dI(i))return await fI(i,n),{hash:n.hash,snapshotDir:i};let s=pt.join(r,`.tmp-${HB()}`);Ko(r,s,"Temporary snapshot"),Ko(r,i,"Published snapshot");try{await vt.mkdir(s);for(let o of n.files){let c=pt.join(s,...o.path.split("/"));Ko(s,c,`Snapshot file ${o.path}`),await vt.mkdir(pt.dirname(c),{recursive:!0}),await vt.writeFile(c,o.content)}await vt.writeFile(pt.join(s,"package.json"),pI(n.document)),await vt.writeFile(pt.join(s,"sha256"),n.hash+`
|
|
243
|
+
`),await vt.rename(s,i)}catch(o){if(await dI(i)){try{await fI(i,n)}finally{await vt.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:i}}throw await vt.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:i}}async function ey(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let n=pt.resolve(e,".comet","skill-snapshots"),r=pt.join(n,t);Ko(n,r,"Skill snapshot");try{let i=(await vt.readFile(pt.join(r,"sha256"),"utf8")).trim();if(i!==t)throw new Error(`stored hash is ${i||"(empty)"}`);let s=pt.join(r,"package.json"),o=JSON.parse(await vt.readFile(s,"utf8")),c=oI(o,r,s),l=cI(c);if(l.length>0)throw new Error(l.map(a=>` - ${a}`).join(`
|
|
244
|
+
`));let f=await hf(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})}}Ue();Qe();nn();async function hI(e){try{return await ty.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function gI(e){return zB("sha256").update(e).digest("hex")}function GB(e){return gI(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function YB(e){return e.replaceAll(".","_").replaceAll("-","_")}async function XB(e,t){let n=await it(e),r=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[YB(o.code),o.source])),i=Hr.join(e,"subagent-progress.md");await hI(i)&&(r.subagent_progress=Hr.relative(n,i).split(Hr.sep).join("/"));let s=t.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(r.handoff_context=s.source),r}function QB(e,t,n){return[{sequence:1,timestamp:n,type:"run_started",runId:e.runId,data:{skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:e.runId,data:{kind:"classic",migrationVersion:is,profile:t,source:"pre-migration"}}]}async function ZB(e){await Promise.all(e.map(t=>ty.rm(t,{recursive:!0,force:!0})))}async function wI(e,t){return sn(e,()=>eV(e,t))}async function eV(e,t){let n=await it(e),r=await le(n,await ue(e),{label:"Classic migration state"});if(Et(r))throw new Error("Classic managed Run is owned by the SDK and cannot be migrated to compat");let i=await $t(e);if(!i.classic)throw new Error("Classic migration requires a legacy state projection");let s=i.classic,o=s.classicProfile??s.workflow;if(i.run){if(s.classicMigration!==is)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 hf(t.skillPackage)!==i.run.skillHash)return await ey(await Ce(e),i.run.skillHash),{classic:s,run:i.run,evidence:await Uo(e,i),migrated:!1,snapshotDir:Hr.join(await Ce(e),".comet","skill-snapshots",i.run.skillHash)};let m=await Zw(t.skillPackage,await Ce(e));return{classic:s,run:i.run,evidence:await Uo(e,i),migrated:!1,snapshotDir:m.snapshotDir}}let c=await Uo(e,i),l=ff(s,c);if(!t.skillPackage.definition.orchestration.steps?.some(u=>u.id===l))throw new Error(`Classic Skill package does not define resolved step: ${l}`);let f=await hf(t.skillPackage),a=Hr.join(await Ce(e),".comet","skill-snapshots",f),d=await hI(a),p=[];try{let u=await Zw(t.skillPackage,await Ce(e)),m=Gx(t.skillPackage,t.runId?.()??JB(),u.hash);m.currentStep=l,l==="completed"&&(m.status="completed");let h={...s,classicProfile:o,classicMigration:is},g=await XB(e,c),w=await it(e),k=c.find(A=>A.code==="design.handoff"&&A.satisfied),y=null;k?.source&&(y=await le(w,k.resolvedSource??k.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await Gu(e,m.contextRef,y),p.push(Hr.resolve(await Ce(e),m.contextRef))),await yo(e,m.artifactsRef,g),p.push(Hr.resolve(await Ce(e),m.artifactsRef));let R=(t.now?.()??new Date).toISOString(),C={runId:m.runId,stateVersion:1,trajectoryOffset:2,contextHash:y===null?null:gI(y),artifactsHash:GB(g),createdAt:R};await Qu(e,m.checkpointRef,C),p.push(Hr.resolve(await Ce(e),m.checkpointRef)),p.push(Hr.resolve(await Ce(e),m.trajectoryRef));for(let A of QB(m,o,R))await Or(e,m.trajectoryRef,A);return await $r(e,{classic:h,run:m,unknownKeys:i.unknownKeys}),{classic:h,run:m,evidence:c,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await ZB(p),d||await ty.rm(a,{recursive:!0,force:!0}),u}}nn();async function tV(e){try{return(await yI.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gf(e){try{return(await yI.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function nV(e){return await tV(e)?await gf(vn.join(e,"skill.yaml"))?!0:await gf(vn.join(e,"SKILL.md"))&&await gf(vn.join(e,"comet","skill.yaml")):!1}function rV(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 iV(){let e=vn.dirname(vI(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,vn.resolve(e,"..","runtime","classic"),vn.resolve(e,"..","..","comet","runtime","classic"),vn.resolve(e,"..","..","assets","skills","comet","runtime","classic"),vn.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,vn.resolve(e,"..","..","comet-classic"),vn.resolve(e,"..","..","assets","skills","comet-classic"),vn.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of t)if(await nV(n))return n;return null}async function sV(e){return await gf(vn.join(e,"skill.yaml"))?sI(e):iI(e)}async function wf(e){let t=await iV();return wI(e,{skillPackage:t?await sV(t):rV(vn.dirname(vI(import.meta.url)))})}async function yf(e,t,n,r){return sn(e,()=>oV(e,t,n,r))}async function oV(e,t,n,r){let i=await $t(e);if(!i.classic||!i.run)throw new Error("Classic transition requires synchronized Classic and Run projections");if(i.run.runId!==n.runId||i.run.iteration!==n.iteration||(t.checkEpoch??0)<(i.classic.checkEpoch??0))throw new Error("Classic transition became stale; reload the current state");let s=await Uo(e,{classic:t,run:n,unknownKeys:i.unknownKeys}),o=ff(t,s),c={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await $r(e,{classic:t,run:c,unknownKeys:i.unknownKeys});let l=await Tr(e,c.trajectoryRef);return await Or(e,c.trajectoryRef,{sequence:l.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:c.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...r}}),c}function cV(e,t,n,r){return["# Comet Design Handoff","","- Change: "+e,"- Phase: design","- Mode: "+t,"","Generated-by: comet handoff","","Read source files for current requirements and task completion.","",...r.flatMap(i=>["## "+i.reference,"","- Source: "+i.reference,"",i.content,""])].join(`
|
|
245
|
+
`)}async function ny(e){let{projectRoot:t,changeDir:n,change:r}=e,i=qe(t,n);if(e.run&&(e.run.input.change!==r||e.run.input.changeDir!==i))throw new Error("Classic Design context belongs to a different Run");let s=i+"/proposal.md";if(!(await le(t,s,{label:"Classic Design source"})).trim())throw new Error("Classic Design source is empty");return{handoffContext:s,handoffHash:e.run?.actions.at(-1)?.inputHash??null}}async function ry(e){let t=qe(e.projectRoot,e.changeDir),n=e.contextCompression==="beta"?"spec-context":"design-context";return[t+"/proposal.md",t+"/.comet/handoff/"+n+".json"].includes(e.handoffContext)?(await ny(e)).handoffContext===t+"/proposal.md":!1}async function lV(e){let{projectRoot:t,changeDir:n,change:r}=e,i=[],s=[...["proposal.md","design.md","tasks.md"].map(c=>n+"/"+c),...await gi(t,n+"/specs")];for(let c of s)await Ge(t,c,{label:"Classic handoff source",expected:"file"})&&i.push({reference:qe(t,c),content:await le(t,c,{label:"Classic handoff source"})});await hi(t,n+"/.comet/handoff","Classic handoff view directory");let o=n+"/.comet/handoff/design-context.md";return await wt(t,o,cV(r,"full","",i),{label:"Classic handoff view"}),qe(t,o)}var dQ=_u(async e=>{let[t,n,r,i]=e;if(n==="--hash-only")return{exitCode:64,stderr:`handoff --hash-only 已移除。由 Agent 读取实际文档并判断上下文是否需要更新。
|
|
246
|
+
`};if(n!=="design"||r!=="--write"||e.length!==3&&!(e.length===4&&i==="--full"))return{exitCode:64,stderr:`Usage: comet handoff <change-name> design --write [--full]
|
|
247
|
+
`};let s=Ya(t);if(s)return{exitCode:1,stderr:s};let o=Iu(),c=await Ar(o),l=await go(t,c.projectRoot);return!l.exists||!l.stateExists?{exitCode:1,stderr:"Classic change directory or state is missing"}:sn(l.directory,async()=>{let f=await $t(l.directory);if(!f.classic||!["design","build"].includes(f.classic.phase))throw new Error("Design handoff requires phase: design or build");let a=await Xa(o,l.directory);if(a.problems.length)throw new Error(a.problems.join(`
|
|
248
|
+
`));let d=await wf(l.directory),p=await Yu(l.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 u=await ny({projectRoot:o,changeDir:l.directory,change:t,contextCompression:d.classic.contextCompression}),m=u.handoffContext.replace(/\.json$/u,".md"),h=await le(o,m,{label:"Classic handoff"}),g=i==="--full"?await lV({projectRoot:o,changeDir:l.directory,change:t}):null;await Gu(l.directory,d.run.contextRef,h),await yo(l.directory,d.run.artifactsRef,{...await Za(l.directory,d.run.artifactsRef),handoff_context:u.handoffContext,handoff_markdown:m});let w={...d.classic,...u},k={...d.run,pending:null};if(k.currentStep==="full.design.handoff"&&(k=await yf(l.directory,w,k,{actionId:p?.id??aV(),kind:"classic-handoff"})),await $r(l.directory,{...f,classic:w,run:k}),p){let R=await Tr(l.directory,k.trajectoryRef);R.some(C=>C.type==="recovery_reconciled"&&C.data?.actionId===p.id)||await Or(l.directory,k.trajectoryRef,{sequence:R.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:k.runId,data:{kind:"classic-handoff",actionId:p.id}}),await Xu(l.directory,d.run.pendingRef)}let y=Vx({name:t,locale:Xc(w.language)});return{exitCode:0,envelope:y,stderr:y.summary+`
|
|
249
|
+
[HANDOFF] source `+u.handoffContext+(g?`
|
|
250
|
+
[HANDOFF] view `+g:"")+`
|
|
251
|
+
`}})});Ue();Qe();import uV from"node:path";async function iy(e,t,n){if(n!=="en"&&n!=="zh-CN")return"Classic change language is not set";let r=t.replaceAll("\\","/");for(let i of["proposal.md","tasks.md","design.md"]){let s=uV.posix.join(r,i);if(i==="design.md"&&!await Ge(e,s,{label:"Classic Open design"}))continue;let o=await le(e,s,{label:`Classic Open ${i}`});if(!o.trim())return i+" is empty";if(i==="tasks.md"&&nr(o).length===0)return"tasks.md has no task"}return null}Qe();function Fe(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic delivery recovery evidence is missing");return e}function Ls(e,t){let n=e.state.workflow,r=e.actions.slice().reverse().find(l=>l.stepId===`${n}.archive.execute`&&l.status==="succeeded"),i=e.actions.slice().reverse().find(l=>l.stepId===n+(e.workflow.version==="2"?".archive.preflight":".verify.check")&&l.status==="succeeded");if(!r?.outcome||!i?.outcome||t&&(t.archiveActionId!==r.id||t.checkActionId!==i.id))throw new Error("Classic delivery recovery requires its original Archive and Verify");let s=Fe(r.input).outputs,o=Fe(Fe(s)[`${n}.archive.preflight`]),c=Fe(r.outcome.output).archiveDirectory;if(typeof c!="string"||typeof o?.baseCommit!="string")throw new Error("Classic delivery recovery lacks its approved archive target");return{profile:n,archive:r,check:i,approved:{...o,baseCommit:o.baseCommit},archiveRef:c}}function Jo(e){return Fe(Fe(e.input).activation).deliveryRepair}function zo(e,t){let n=e.state;return n.archived&&n.phase==="archive"&&t.type==="call_tool"&&t.ref==="classic-check"&&t.stepId===`${n.workflow}.delivery.check`}function sy(e,t){let n=Ls(e,t),r=Fe(n.check.outcome.output),i=Array.isArray(r.deliveryPaths)?r.deliveryPaths:Object.keys(r.deliveryInputs??{}),s=new Set(t.excludedOutputPaths??Object.keys(t.excludedOutputs??{}));return i.filter(o=>!s.has(o))}function vf(e){let t=e.state,n=e.actions.filter(i=>i.status==="pending"),r=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 n.length===0&&r.length===0&&i?.status==="failed"&&zo(e,i)}return r.length?e.status==="waiting"&&n.length===0&&r.length===1&&r[0].stepId===`${t.workflow}.delivery.confirm`:e.status==="running"&&n.length===1&&!n[0].claim&&(n[0].stepId===`${t.workflow}.archive.deliver`||zo(e,n[0]))}function kI(e,t){if(e===void 0||t.state.archived!==!0)return!1;let n=j(e);return!!t.commands?.some(r=>{if(!["repair-delivery","continue-work"].includes(r.name))return!1;let i=t.actions.find(o=>o.id===r.actionId);if(!i||j(i.input)!==i.inputHash)return!1;let s=Fe(Fe(i.input).activation);if(r.name==="continue-work"){let o=t.actions.find(c=>c.id===s.interruptedActionId);return i.stepId==="classic.resume-work"&&typeof s.deliveryCheckpointHash=="string"&&j(s)===r.inputHash&&s.deliveryCheckpointHash===n&&!!(o?.status==="failed"&&ir(t,o))}return zo(t,i)&&j(s)===r.inputHash&&Fe(s.deliveryRepair).checkpointHash===n})}function ir(e,t){let n=e.state;if(!n.archived||t.type!=="invoke_skill"||t.stepId!==`${n.workflow}.archive.deliver`)return null;let r=Fe(t.input).activation,i=r===void 0?{}:Fe(r),s=i.deliveryRepairCheckId;if(s===void 0&&i.interruptedActionId!==void 0){let p=e.actions.find(g=>g.id===i.interruptedActionId),u=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||u===void 0||(e.actionContexts[p.id]?.sequence??1/0)>=u||h?.status!=="succeeded"||h.claim?.executorId!=="comet-classic-work-continuation"||j(h.outcome?.output)!==j({interruptedActionId:p.id,resumeStepId:p.stepId})||Fe(Fe(h.input).activation).interruptedActionId!==p.id||!e.commands?.some(g=>g.name==="continue-work"&&g.actionId===h.id&&g.inputHash===j(Fe(h.input).activation)))throw new Error("Classic delivery continuation is missing its original stopped Skill");return ir(e,p)}let o=Ls(e),c=e.actionContexts[o.archive.id]?.results[`${n.workflow}.archive.confirm`]?.sequence,l=e.waits.find(p=>p.stepId===`${n.workflow}.archive.confirm`&&p.sequence===c&&p.status==="resolved"),f={outputs:{...Fe(Fe(o.archive.input).outputs),[o.archive.stepId]:o.archive.outcome.output},archiveActionId:o.archive.id,approvalWaitIds:l?[l.id]:[]};if(s===void 0){let p=Fe(Fe(t.input).outputs);if(e.actionContexts[t.id]?.results[o.archive.stepId]?.sequence!==e.actionContexts[o.archive.id]?.sequence||j(p[`${n.workflow}.archive.preflight`])!==j(o.approved)||j(p[o.archive.stepId])!==j(o.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===s),d=e.waits.slice().reverse().find(p=>p.stepId===`${n.workflow}.delivery.confirm`&&p.results[`${n.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"||j(Fe(Fe(d.proposal).outputs)[a.stepId])!==j(a.outcome.output))throw new Error("Classic delivery repair is missing its current check and explicit approval");return Ls(e,Jo(a)),{...f,outputs:{...f.outputs,[a.stepId]:a.outcome.output},repairCheckId:a.id,approvalWaitIds:[...f.approvalWaitIds,d.id]}}function Ws(e,t){let n=ir(e,t);if(n){let f=e.actions.find(a=>a.id===n.archiveActionId);if(!f)throw new Error("Classic delivery recovery is missing its original Archive");return Ws(e,f)}let r=t.input.outputs??{};if(r["full.build.plan"]!==void 0)return{outputs:r,recovered:!1};let i=e.actionContexts[t.id]?.sequence;if(i===void 0)return{outputs:r,recovered:!1};let s=[...e.commands??[]].reverse().find(f=>f.actionId===t.id||(e.actionContexts[f.actionId]?.sequence??1/0)<i);if(!s||!["reopen-verification","continue-build"].includes(s.name))return{outputs:r,recovered:!1};let o=e.actionContexts[s.actionId].sequence,c=[...e.actions].reverse().filter(f=>f.stepId==="full.build.execute"&&(e.actionContexts[f.id]?.sequence??1/0)<o),l=c[0];if(l?.status!=="succeeded"||l.outcome?.status!=="succeeded"||l.outcome.output.event!=="build-complete")return{outputs:r,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<o))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:r,recovered:!1}}import{promises as ay}from"node:fs";import sr from"node:path";Qt();ve();rn();Qe();Qt();ve();import{promises as dV}from"node:fs";import kf from"node:path";Ue();kt();async function bI(e,t,n,r){let i=t.input.changeDir;if(nt(i,"Classic active path"),nt(r,"Classic archive path"),n.status!=="succeeded"||n.outcome?.status!=="succeeded"||n.claim?.executorId!=="comet-classic-archive"||n.outcome.output?.archiveDirectory!==r)throw new Error("旧 Archive 缺少成功的原执行结果");let s=[],o=[];async function c(m){let h=await M(e,m,{label:"Classic legacy archive path",expected:"any"});if(h.exists)if(h.kind==="directory")for(let g of await dV.readdir(h.target)){if([".comet-state.lock",".comet-state-transaction.json"].includes(g)){let w=m+"/"+g+"/.comet-runtime-migration.json";(await M(e,w,{label:"Classic legacy migration marker",expected:"file"})).exists&&(o.push(w),s.push(i+"/"+w.slice(r.length+1)));continue}await c(m+"/"+g)}else s.push(m)}await c(r);let l=kf.relative(e,(await En(e)).specsDir).replaceAll("\\","/");for(let m of[...s])m.startsWith(r+"/specs/")&&m.endsWith("/spec.md")&&s.push(l+"/"+m.slice((r+"/specs/").length));let f=Ws(t,n).outputs,a=f["full.design.document"]?.designDoc,d=f["full.build.plan"]?.plan;for(let m of[a,d])m&&s.push(ht(m,i,r));let p=kf.relative(e,await ue(kf.join(e,r))).replaceAll("\\","/"),u=s.filter(m=>m.startsWith(r+"/")).map(m=>i+"/"+m.slice(r.length+1));return{paths:[...new Set([...s,...u])],sourcePaths:u,stateFiles:[p,i+"/"+kf.posix.basename(p)],optionalPaths:o}}kt();var bf=".comet/archive-manifest.json",Rf=class extends Error{constructor(n){super("请使用原 Run 的恢复决定");this.proposal=n}proposal};async function oy(e,t){let n=await M(e,t,{label:"Classic Archive paths",expected:"any"});if(!n.exists)return[];if(n.kind!=="directory")return[t];let r=[];for(let i of(await ay.readdir(n.target)).sort())[".comet-state.lock",".comet-state-transaction.json"].includes(i)||r.push(...await oy(e,t+"/"+i));return r}function Ms(e,t){return j(Bc(e,t))}async function Cf(e){return pn({singleWriter:!0,rootDir:sr.join(await xr(e),"archive-receipts/classic")})}async function cy(e){return pn({singleWriter:!0,rootDir:sr.join(await xr(e),"archive-inputs/classic")})}function RI(e){let t=e;return{...e,paths:e.paths??Object.keys(t.files??{}),specPaths:e.specPaths??Object.keys(t.specs??{}),documents:Array.isArray(e.documents)?e.documents:Object.keys(t.documents??{})}}async function fV(e,t,n){let r=t.input.changeDir,i=t.state,s=sr.relative(e,await ue(sr.join(e,r))).replaceAll("\\","/"),o=sr.posix.dirname(r)+"/archive",c=await M(e,o,{label:"Classic Archive directory",expected:"directory"}),l=c.exists?await ay.readdir(c.target):[];return{activeRef:r,stateRef:s,specsRef:n,paths:(await oy(e,r)).filter(f=>f!==s),specPaths:await oy(e,n),documents:[i.designDoc,i.plan].filter(f=>!!f),archivePaths:l}}async function CI(e,t,n,r){let i=await cy(e),s=Ms(t,n),o=await i.read(s);if(o)return RI(o.snapshot);let c=await fV(e,t,r),l={runId:s,revision:1,execution:Bc(t,n),snapshot:c};if(!await i.compareAndSwap(s,null,l))throw new Error("原 Archive 已有执行准备记录,请恢复同一 Action");return c}async function SI(e,t,n){if(n.status!=="failed"||n.outcome?.status!=="failed")throw new Error("原 Archive 尚未确认失败退出;先恢复原 Action 并核对实际归档进度");let r=t.input.changeDir;if(!(await M(e,r,{label:"Classic active change",expected:"directory"})).exists)throw new Error("原 change 目录已搬迁;恢复原 Archive 进度,不能重开执行");let s=await(await cy(e)).read(Ms(t,n));if(s?.snapshot.archivePaths){let o=await M(e,sr.posix.dirname(r)+"/archive",{label:"Classic Archive directory",expected:"directory"}),c=sr.posix.basename(r);if(o.exists&&(await ay.readdir(o.target)).some(l=>/^\d{4}-\d{2}-\d{2}-/u.test(l)&&l.slice(11)===c&&!s.snapshot.archivePaths.includes(l)))throw new Error("原 Archive 已创建归档目录;先恢复该事务,不能重开执行")}}async function ly(e,t,n,r,i,s){let o=ht(i.stateRef,i.activeRef,r),c=new Set(i.paths.map(p=>ht(p,i.activeRef,r)));c.delete(o);for(let p of i.documents)c.add(ht(p,i.activeRef,r));for(let p of i.paths.filter(u=>u.startsWith(i.activeRef+"/specs/")&&u.endsWith("/spec.md")))c.add(i.specsRef+"/"+p.slice((i.activeRef+"/specs/").length));let l={schema:"comet.classic.archive-manifest.v2",execution:Bc(t,n),activeRef:i.activeRef,archiveRef:r,stateRef:o,paths:[...c].sort(),sourcePaths:i.paths},f=await Cf(e),a=Ms(t,n),d=await f.read(a);if(d&&d.manifest.archiveRef!==r)throw new Error("原 Archive 已记录不同交付目录,不能覆盖");if(!d&&!await f.compareAndSwap(a,null,{runId:a,revision:1,manifest:l}))throw new Error("原 Archive 交付记录已存在");return await wt(e,r+"/"+bf,JSON.stringify(d?.manifest??l,null,2)+`
|
|
252
|
+
`,{label:"Classic Archive progress"}),[]}async function EI(e,t,n,r){let i=await(await Cf(e)).read(Ms(t,n));if(!i||i.manifest.archiveRef!==r||i.manifest.execution.actionId!==n.id)throw new Error("原 Archive 执行收据缺失;核对原命令结果并恢复原记录,不能重复执行或用当前文件补造成功");return i}async function AI(e,t,n,r,i){return await EI(e,t,n,r),Di(e,t,n,r)}async function uy(e,t,n,r,i){let s=await(await Cf(e)).read(Ms(t,n));if(!s){let l=await(await cy(e)).read(Ms(t,n));if(!l||l.execution.actionId!==n.id||l.execution.attempt!==n.attempt)throw new Error("原 Archive 准备记录缺失;不能重复执行或补造成功");let f=RI(l.snapshot),a=await M(e,f.activeRef,{label:"Classic active change",expected:"directory"}),d=await M(e,r,{label:"Classic archived change",expected:"directory"});if(a.exists||!d.exists)throw new Error("原 Archive 搬迁尚未完成或目录归属不明确");for(let p of f.documents){let u=ht(p,f.activeRef,r),m=await le(e,u,{label:"Classic archived document"});await wt(e,u,Hi(m,sr.posix.basename(r),p===t.state.designDoc?"status: final":""),{label:"Classic archived document"})}await ly(e,t,n,r,f),s=await EI(e,t,n,r)}if(s.manifest.archiveRef!==r)throw new Error("原 Archive 目录不匹配");let o=r+"/"+bf;return(await M(e,o,{label:"Classic Archive progress",expected:"file"})).exists||await wt(e,o,JSON.stringify(s.manifest,null,2)+`
|
|
253
|
+
`,{label:"Classic Archive progress"}),[]}async function Di(e,t,n,r,i=n.outcome?.artifacts){await M(e,r+"/"+bf,{label:"Classic Archive manifest",expected:"file"});let s=await(await Cf(e)).read(Ms(t,n)),o=n.outcome?.output?.archiveManifest,c=s?.manifest??o;if(!c)return bI(e,t,n,r);if(!["comet.classic.archive-manifest.v1","comet.classic.archive-manifest.v2"].includes(c.schema)||c.activeRef!==t.input.changeDir||c.archiveRef!==r||c.execution?.actionId!==n.id||c.execution?.runId!==t.runId)throw new Error("归档交付记录不属于原 Run 和 Action");let l=c.paths??Object.keys(c.files??{}),f=c.sourcePaths??Object.keys(c.sources??{}),a=c.optionalPaths??Object.keys(c.optionalFiles??{});for(let p of[...l,...f,...a])nt(p,"Classic Archive path");let d=sr.relative(e,await ue(sr.join(e,r))).replaceAll("\\","/");return{paths:[...new Set([...l,r+"/"+bf,...f.filter(p=>p.startsWith(c.activeRef+"/"))])],sourcePaths:f,stateFiles:[d,c.activeRef+"/"+sr.posix.basename(d)],optionalPaths:[...new Set([...a,...[".comet-state.lock",".comet-state-transaction.json"].map(p=>r+"/"+p+"/.comet-runtime-migration.json")])]}}function Sf(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function qi(e,t){return jt(e)===jt(t)}function xI(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 Go(e,t,n={}){if(Sf(t.state).archived!==!0||kI(e,t))return null;let r=(n.projection?nf:yn)(e,t.runId,{preserveSourceRevision:!0});if(!r)return null;let i=Sf(r.state),s=r.actions.at(-1),o=`${i.workflow}.archive.deliver`;if(i.archived!==!0||i.phase!=="archive"||!["full","tweak","hotfix"].includes(String(i.workflow))||r.status!=="running"||!s||s.stepId!==o||s.status!=="pending"||s.claim||s.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`)},l=r.outputs[o],f=r.actionContexts[s.id]?.sequence,a=l!==void 0&&l.sequence===f,d=l!==void 0&&!a&&r.actions.some(w=>w.id!==s.id&&w.stepId===o&&w.status==="failed"&&w.outcome?.status==="failed"&&r.actionContexts[w.id]?.sequence===l.sequence&&f!==void 0&&l.sequence<f&&qi(w.outcome.output,l.value));(i.branchStatus!=="pending"||s.type!=="invoke_skill"||typeof s.ref!="string"||!s.ref.trim()||s.retry!=="manual"||s.reconciliations.length!==s.attempt-1||s.reconciliations.some((w,k)=>w.attempt!==k+1)||s.receipts.length>=s.attempt||(s.rejectedOutcomes?.length??0)!==0||s.receipts.length!==0!==a||l!==void 0&&!a&&!d||s.reason!==void 0||r.reason!==void 0||!r.actions.some(w=>w.stepId===`${i.workflow}.archive.execute`&&w.ref==="classic-archive"&&w.status==="succeeded")||r.actions.slice(0,-1).some(w=>["pending","running","unknown"].includes(w.status))||r.ready.length!==0||r.waits.some(w=>w.status==="pending")||r.evidenceWaits?.some(w=>w.status==="pending")||Object.values(r.joins).some(w=>Object.values(w).some(k=>k.length!==0)))&&c();let p=t.actions.at(-1);if(!p)return c();qi(xI(p),xI(s))||c(),ad(p,jt(p.input)),(!["pending","running","unknown","failed","succeeded"].includes(p.status)||p.cancellation||p.executionOrigin&&!qi(p.executionOrigin.workflow,t.workflow)||p.reconciliations.length!==p.attempt-1||p.reconciliations.some((w,k)=>w.attempt!==k+1)||p.attempt<s.attempt||!qi(p.receipts.slice(0,s.receipts.length),s.receipts)||!qi(p.reconciliations.slice(0,s.reconciliations.length),s.reconciliations)||p.receipts.length-(p.rejectedOutcomes?.length??0)>p.attempt||p.status==="pending"&&p.reason!==void 0)&&c();let u=p.status==="succeeded",m=p.status==="failed";(t.status!==(u?"completed":m?"failed":"running")||t.reason!==(m?`ACTION_FAILED: ${o}`:void 0)||Sf(t.state).branchStatus!==(u?"handled":i.branchStatus)||t.revision<r.revision+(p.attempt-s.attempt)*3+(p.status==="pending"?0:p.status==="running"?1:2))&&c(),!p.outcome&&p.receipts.length===s.receipts.length&&(Object.hasOwn(t.outputs,o)!==Object.hasOwn(r.outputs,o)||Object.hasOwn(r.outputs,o)&&!qi(t.outputs[o],r.outputs[o]))&&c(),p.outcome?qi(t.outputs[o],{sequence:r.actionContexts[s.id].sequence,value:p.outcome.output})||c():Object.hasOwn(t.outputs,o)&&!(d&&qi(t.outputs[o],l)&&p.receipts.length===(p.rejectedOutcomes?.length??0))&&(p.attempt===1||p.receipts.length===(p.rejectedOutcomes?.length??0)||t.outputs[o].sequence!==r.actionContexts[s.id].sequence)&&c();let h={...t.outputs};Object.hasOwn(r.outputs,o)?h[o]=r.outputs[o]:delete h[o];let g={...t,revision:r.revision,status:r.status,state:{...Sf(t.state),branchStatus:i.branchStatus},actions:[...t.actions.slice(0,-1),s],outputs:h};return delete g.reason,_s(e,g)||c(),r}import{execFileSync as mV}from"node:child_process";import{randomUUID as hV}from"node:crypto";import dy from"node:path";Qt();rn();Ue();li();import pV from"node:path";async function II(e){let t=await Qi(e,{allowPartialProject:!0,allowMissingNativeFields:!0});return t?.native?[pV.posix.join(t.native.artifact_root,"comet","changes")]:[]}function Ef(e,t){return t.some(n=>e===n||e.startsWith(`${n}/`))}function Af(e,t){return mV("git",t,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:3e4,maxBuffer:Number.MAX_SAFE_INTEGER,stdio:["ignore","pipe","pipe"]})}function _I(e){let t;try{t=Af(e,["diff","HEAD","--name-only","--no-renames","-z"])}catch{t=Af(e,["ls-files","--cached","-z"])}return[...new Set([...t.split("\0"),...Af(e,["ls-files","--others","--exclude-standard","-z"]).split("\0")].filter(Boolean))]}async function PI(e){let t=await En(e);return[".comet",t.openSpecRoot,t.superpowersRoot,...await II(e)].map(n=>dy.isAbsolute(n)?dy.relative(e,n).replaceAll("\\","/"):n)}async function OI(e){return pn({singleWriter:!0,rootDir:dy.join(await xr(e),"classic-delivery-baselines")})}async function gV(e){return on(e)?{schema:"comet.classic.workspace-baseline.v2",paths:_I(e)}:void 0}async function TI(e,t){let n=await gV(e);if(!n)return t;let r=hV();return await(await OI(e)).compareAndSwap(r,null,{runId:r,revision:1,paths:n.paths}),{...t,workspaceBaseline:{ref:r}}}async function wV(e,t){let n=t?.input?.workspaceBaseline?.ref;if(!n)return new Set;let r=await(await OI(e)).read(n);return new Set(r?.paths??Object.keys(r?.files??{}))}async function NI(e,t,n){if(!on(e))return[];let r=await PI(e),i=await wV(e,t);if(n){for(let s of n)if(nt(s,"Classic delivery path"),Ef(s,r)||s.split("/").includes("node_modules"))throw new Error("Classic delivery path belongs to workflow metadata or another change: "+s);return[...new Set(n)].sort()}return _I(e).filter(s=>!s.split("/").includes("node_modules")&&!Ef(s,r)&&!i.has(s)).sort()}async function $I(e,t){let n=t.state,r=[...t.actions].reverse().find(m=>m.stepId===n.workflow+".archive.deliver"),i=r?ir(t,r)?.repairCheckId:void 0,s=rf(t),o=i?t.actions.find(m=>m.id===i):[...t.actions].reverse().find(m=>m.stepId===n.workflow+".archive.preflight");if(o?.status!=="succeeded"||o.outcome?.status!=="succeeded")throw new Error("Classic 交付需要当前成功的 Verify 检查");let c=o.outcome.output,l=s?.output.deliveryInputs,f=c.deliveryPaths?[]:await PI(e),a=(c.deliveryPaths??Object.keys(c.deliveryInputs??l??{})).filter(m=>!Ef(m,f)),d=t.evidenceWaits?.slice().reverse().find(m=>m.stepId===n.workflow+".verify.report.evidence"&&m.status==="resolved")?.receipt,p=t.input.changeDir,u=t.outputs[n.workflow+".archive.execute"]?.value?.archiveDirectory;if(n.verificationReport&&!d)throw new Error("Classic 交付缺少已接受的验证报告");return d&&a.push(u?ht(d.ref,p,u):d.ref),fy(e,a)}async function fy(e,t,n){let r=Array.isArray(t)?t:Object.keys(t);for(let s of r)nt(s,"Classic delivery path");let i=r.length?Af(e,["status","--porcelain","--untracked-files=all","--",...r]).trim():"";if(i)throw new Error("Classic 交付路径尚有未提交修改:"+i);return new Set(r)}import{createHash as yV}from"node:crypto";import{execFileSync as my}from"node:child_process";function py(e,t,n){let r=my("git",["remote","get-url",...n?["--push"]:[],t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim();if(!r)throw new Error("Classic delivery remote URL is empty");let i=null;try{i=new URL(r)}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 r}function Yo(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 n=py(e,t,!1),r=py(e,t,!0);if(n!==r)throw new Error("Classic delivery remote has different fetch and push URLs");return yV("sha256").update(n).digest("hex")}function DI(e,t,n){let r=`refs/heads/${n}`,i=my("git",["-c","protocol.allow=never","-c","protocol.https.allow=always","-c","protocol.ssh.allow=always","-c","protocol.file.allow=always","ls-remote","--refs",t,r],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4}).trim(),s=/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(i);return s?.[2]===r?s[1]:null}function vV(e){let t=/^git@([^:/]+):([^/]+\/[^/]+)$/u.exec(e);try{let n=new URL(t?`ssh://git@${t[1]}/${t[2]}`:e);if(!["https:","ssh:"].includes(n.protocol)||n.password||n.search||n.hash||n.port||n.protocol==="https:"&&n.username)return null;let r=n.pathname.replace(/\.git\/?$/u,"").replace(/\/$/u,"").split("/").filter(Boolean);return r.length!==2||r.some(i=>!/^[a-zA-Z0-9_.-]+$/u.test(i))?null:`${n.hostname}/${r.join("/")}`.toLowerCase()}catch{return null}}function jI(e,t){try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.port||n.search||n.hash)return null;let r=/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/u.exec(n.pathname);return r&&`${n.hostname}/${r[1]}/${r[2]}`.toLowerCase()===t?`https://${n.hostname}/${r[1]}/${r[2]}/pull/${r[3]}`:null}catch{return null}}function qI(e){let t=vV(py(e.projectRoot,e.remote,!1)),n=t&&jI(e.prUrl,t);if(!t||!n)return!1;let r=my("gh",["pr","view",n,"--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(r);return typeof i.url=="string"&&jI(i.url,t)===n&&i.headRefName===e.targetBranch&&i.headRefOid===e.commit&&i.baseRefName===e.baseBranch&&(i.state==="OPEN"||i.state==="MERGED")}kt();ve();Ue();import el from"node:path";async function tl(e,t,n){let r=await En(e),i=await M(e,t,{label:"Classic Verify report",expected:"file"}),s=el.relative(r.superpowersReportsDir,i.target);if(!i.exists||!s||s.startsWith(`..${el.sep}`)||el.isAbsolute(s)||s.includes(el.sep)||el.extname(s).toLowerCase()!==".md")throw new Error("Classic Verify report is outside the configured reports directory");let o=i.relative.replaceAll("\\","/");if(!(await ce(e,o,Number.MAX_SAFE_INTEGER,{label:"Classic Verify report"})).bytes.toString("utf8").trim())throw new Error("Classic Verify report is empty");return{ref:o}}var xf={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}}}},FI={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}}}},hy={id:"comet-classic-open-revalidation",version:"1",async validate({run:e,action:t,outcome:n,context:r}){if(n.status==="failed")return{accepted:!0};let i=e.waits.find(o=>o.stepId==="full.open.confirm"&&o.status==="resolved"&&o.decision?.choice==="approved"),s=n.output;return i&&r?.projectRoot&&t.claim?.executorId===FI.id&&s?.contentHash===t.inputHash?{accepted:!0}:{accepted:!1,reason:"Classic Open has no approval for its current SDK request"}}},gy={id:"comet-classic-design-handoff",version:"1",async validate({run:e,outcome:t,context:n}){if(t.status==="failed")return{accepted:!0};let r=e.input,i=e.state,s=t.output;if(!n?.projectRoot||typeof r.change!="string"||typeof r.changeDir!="string"||typeof s?.proposal!="string"||typeof s.handoffContext!="string")return{accepted:!1,reason:"Classic Design handoff lacks a source-bound context pack"};try{if(s.sourceEvidence||s.requirementsEvidence){let c=await Fs(n.projectRoot,r.changeDir,{run:e}),l=c;if(s.sourceEvidence?.ref!==c.ref||s.requirementsEvidence?.ref!==l.ref)return{accepted:!1,reason:"Classic Design proposal sources changed before submission"}}return{accepted:await ry({run:e,projectRoot:n.projectRoot,changeDir:Jt.join(n.projectRoot,r.changeDir),change:r.change,contextCompression:i.contextCompression,handoffContext:s.handoffContext,handoffHash:typeof s.handoffHash=="string"?s.handoffHash:null}),reason:"Classic Design handoff no longer matches its OpenSpec sources"}}catch(o){return{accepted:!1,reason:o instanceof Error?o.message:String(o)}}}},wy={id:"comet-classic-build-configuration",version:"1",validate({run:e,outcome:t}){if(t.status==="failed")return{accepted:!0};let n=e.state,r=t.output;if(!r||!n.isolation||r.isolation!==n.isolation||r.boundBranch!==n.boundBranch)return{accepted:!1,reason:"Classic Build workspace binding changed in the proposal"};let i={...n,...r},s=br(i);return s.missingFields.length||s.invalidFields.length?{accepted:!1,reason:"Classic Build configuration is incomplete or invalid"}:{accepted:!0}}},kV={id:"comet-classic-archive-outcome",version:"1",async validate({run:e,action:t,outcome:n,context:r}){if(n.status==="failed")return{accepted:!0};let i=r?.projectRoot,s=t.input,o=n.output;if(!i||t.claim?.executorId!=="comet-classic-archive"||typeof s.input?.changeDir!="string"||typeof o?.archiveDirectory!="string")return{accepted:!1,reason:"Classic Archive result lacks its execution identity"};try{let c=await En(i),[l,f]=await Promise.all([M(i,s.input.changeDir,{label:"Classic active change",expected:"directory"}),M(i,o.archiveDirectory,{label:"Classic archived change",expected:"directory"})]),a=Jt.relative(c.archiveDir,f.target),d=Jt.basename(f.target);if(l.exists||!f.exists||Jt.dirname(l.target)!==c.changesDir||!a||a.startsWith(`..${Jt.sep}`)||Jt.isAbsolute(a)||a.includes(Jt.sep)||!/^\d{4}-\d{2}-\d{2}-/u.test(d)||d.slice(11)!==Jt.basename(l.target))return{accepted:!1,reason:"Classic Archive has not moved the approved change"};let p=await os(i,f.target);if(p.length>0)return{accepted:!1,reason:p.join(`
|
|
254
|
+
`)};let u=e.actions.find(m=>m.id===t.id);return u?.status==="succeeded"&&u.outcome&&j(u)===j(t)&&j(u.outcome)===j(n)?await Di(i,e,u,o.archiveDirectory):await AI(i,e,t,o.archiveDirectory,n.artifacts),{accepted:!0}}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}};async function bV(e,t,n,r){let i=Jt.relative(e,await ue(Jt.join(e,t))).replaceAll("\\","/");if(n!==`M ${i}`)return!1;let s=Li("git",["show",`HEAD:${i}`],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}),o=await le(e,Jt.join(e,i),{label:"Classic state file"}),c=(0,ky.parseDocument)(s,{uniqueKeys:!0}),l=(0,ky.parseDocument)(o,{uniqueKeys:!0});if(c.errors.length>0||l.errors.length>0)return!1;let f=c.toJS(),a=l.toJS();return!yn(f[It],r.runId)||!yn(a[It],r.runId)||!Hc(a[It],Pi(r))&&!Go(a[It],r)?!1:(delete f[It],delete a[It],vy(f,a))}var RV={id:"comet-classic-delivery-outcome",version:"1",async validate({run:e,action:t,outcome:n,context:r}){if(n.status==="failed")return{accepted:!0};let i=r?.projectRoot,s=t.stepId.split(".")[0],o=t.input,c=ir(e,t)?.outputs??o.outputs,l=c?.[`${s}.archive.preflight`],f=c?.[`${s}.archive.execute`],a=n.output;if(!i||!["full","hotfix","tweak"].includes(s)||!l||!a||!["local","push","pr"].includes(String(l.deliveryAction))||a.action!==l.deliveryAction||a.targetBranch!==l.targetBranch||typeof l.baseCommit!="string"||!f||typeof f.archiveDirectory!="string"||typeof o.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=st(i);if(d!==l.targetBranch)return{accepted:!1,reason:`Classic 当前分支 ${d??"(detached HEAD)"} 与已批准目标 ${String(l.targetBranch)} 不一致`};if(l.deliveryAction!=="local"&&(typeof l.remote!="string"||a.remote!==l.remote||typeof l.remoteIdentity!="string"||Yo(i,l.remote)!==l.remoteIdentity))return{accepted:!1,reason:"Classic delivery remote changed after approval"};let p=Li("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(l.baseCommit))return{accepted:!1,reason:"Classic 交付缺少有效的已批准基线 baseCommit"};let u=Li("git",["rev-list","--reverse","--parents",`${l.baseCommit}..${p}`,"--"],{cwd:i,encoding:"utf8"}).trim().split(`
|
|
255
|
+
`).filter(Boolean);if(!u.length)return{accepted:!1,reason:`Classic 已批准基线 ${l.baseCommit} 之后没有交付提交`};let m=l.baseCommit,h=new Set,g=Hx(i,u.map($=>$.split(/\s+/u)[0]));for(let $ of u){let[T,...F]=$.split(/\s+/u);if(F.length!==1)return{accepted:!1,reason:`Classic 交付范围包含非线性提交 ${T}(父提交数 ${F.length});只接受从已批准基线 ${l.baseCommit} 连续产生的单父提交`};if(F[0]!==m)return{accepted:!1,reason:`Classic 交付提交 ${T} 的父提交 ${F[0]} 不等于 ${m};交付范围必须从已批准基线 ${l.baseCommit} 连续开始`};let U=g.get(T);for(let se of U)h.add(se);m=T}let w=Li("git",["ls-tree","-r","--name-only","HEAD","--",f.archiveDirectory],{cwd:i,encoding:"utf8"}).trim(),k=Li("git",["status","--porcelain","--untracked-files=all","--",f.archiveDirectory],{cwd:i,encoding:"utf8"}).trim(),y=o.input.changeDir.replaceAll("\\","/"),R=f.archiveDirectory.replaceAll("\\","/"),A=Ws(e,t).outputs,q=A["full.build.plan"],D=A["full.design.document"]?.designDoc??q?.designEvidence?.ref,K=q?.plan;if(s==="full"&&(typeof D!="string"||typeof K!="string"))return{accepted:!1,reason:"Classic Archive documents are missing"};let L=Jt.posix.basename(R),Z=typeof D=="string"?ht(D,y,R):null,Y=typeof K=="string"?ht(K,y,R):null,fe=s==="full"?Li("git",["show",`HEAD:${Z}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,z=s==="full"?Li("git",["show",`HEAD:${Y}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,ne=await $I(i,e),Le=e.actions.slice().reverse().find($=>$.stepId===`${s}.archive.execute`&&$.status==="succeeded");if(!Le)throw new Error("Classic delivery 缺少成功的 Archive Action");let I=await Di(i,e,Le,R);for(let $ of I.optionalPaths){let T=$.startsWith(`${R}/`)?`${y}/${$.slice(R.length+1)}`:null;if(Li("git",["ls-tree","-z","HEAD","--",$],{cwd:i,encoding:"utf8"}))I.paths.push($,...T?[T]:[]);else if(T&&[...g.values()].some(U=>U.includes(T)))throw new Error(`Classic archive commit deletes an optional input without committing the archived copy: ${$}`)}let V=await fy(i,I.paths),re=$=>ne.has($)||V.has($)||I.stateFiles.includes($),He=[...h].filter($=>!re($));if(He.length)return{accepted:!1,reason:`Classic 交付提交范围包含未批准的路径:${He.join(", ")}`};let E=k!==""&&await bV(i,R,k,e);return w?k&&!E?{accepted:!1,reason:`Classic 归档目录与交付 HEAD 不一致:${k}`}:[...h].some($=>$.startsWith(`${R}/`))?s==="full"&&(!Z||!Y||!h.has(Z)||!h.has(Y)||!fe?.includes(`archived-with: ${L}`)||!fe.includes("status: final")||!z?.includes(`archived-with: ${L}`))?{accepted:!1,reason:`Classic 交付范围缺少已归档的设计或计划,或归档标记不符:${Z}, ${Y}`}:l.deliveryAction!=="local"&&DI(i,l.remote,l.targetBranch)!==a.commit?{accepted:!1,reason:"Classic remote branch does not contain the archive commit"}:l.deliveryAction==="pr"&&(typeof a.prUrl!="string"||typeof l.prBaseBranch!="string"||!qI({projectRoot:i,remote:l.remote,prUrl:a.prUrl,targetBranch:l.targetBranch,commit:a.commit,baseBranch:l.prBaseBranch}))?{accepted:!1,reason:"Classic PR does not match the approved delivery"}:{accepted:!0}:{accepted:!1,reason:`Classic 交付范围 ${l.baseCommit}..${p} 未包含归档目录:${R}`}:{accepted:!1,reason:`Classic 交付 HEAD 缺少归档目录:${R}`}}catch(d){return{accepted:!1,reason:d instanceof Error?d.message:String(d)}}}};async function Fs(e,t,n={}){let r=await M(e,t,{label:"Classic change",expected:"directory"});if(!r.exists||n.run&&n.run.input.changeDir!==r.relative)throw new Error("Classic artifacts do not belong to the current change");let i=await Xa(e,r.target);if(i.problems.length)throw new Error(i.problems.join(`
|
|
256
|
+
`));return{ref:r.relative}}async function HI(e,t){let n=nt(t,"Classic Design document");if(!(await ce(e,n,Number.MAX_SAFE_INTEGER,{label:"Classic Design document"})).bytes.length)throw new Error("Classic Design document is empty");return{ref:n}}async function If(e,t){let n=t.state,r=t.evidenceWaits?.slice().reverse().find(i=>i.stepId==="full.design.evidence"&&i.status==="resolved"&&i.receipt?.ref===n.designDoc)?.receipt;if(!r||!n.designDoc)throw new Error("Classic Build requires its accepted Design step");return await M(e,n.designDoc,{label:"Classic accepted Design",expected:"file"}),{ref:r.ref}}async function _f(e,t,n){if((await Ds(e,t)).status!=="ready")throw new Error("Classic Build plan is not ready");let i=await M(e,t,{label:"Classic Build plan",expected:"file"}),s=await M(e,n,{label:"Classic change",expected:"directory"});if(!i.exists||!s.exists)throw new Error("Classic Build plan or change is missing");return{ref:i.relative}}async function Pf(e,t,n){if(n.state.workflow!=="full")return;let i=n.waits.find(o=>o.status==="resolved"&&(o.stepId==="full.open.confirm"&&o.decision?.choice==="approved"||["hotfix","tweak"].some(c=>o.stepId===`${c}.build.escalation-confirm`)&&o.decision?.choice==="upgrade")),s=n.actions.slice().reverse().find(o=>o.stepId==="full.design.handoff"&&o.status==="succeeded");if(!i||!s||n.input.changeDir!==t)throw new Error("Classic Design requires its approved Open and completed handoff")}async function Of(e,t,n,r){await nl(e,t,r);let i=br(n);if(n.isolation===null||i.missingFields.length>0||i.invalidFields.length>0)throw new Error("Classic Build configuration is incomplete or invalid");let s=st(e),o=_n({isolation:n.isolation,boundBranch:n.boundBranch,currentBranch:s,gitWorkTree:s===null?on(e):!0});if(o.status==="needs-heal")throw new Error("Classic Build Git branch is not bound in the SDK Run");if(o.status==="unbound-detached"||o.status==="drift")throw new Error("Classic Build Git branch no longer matches the SDK Run");let c=await M(e,t,{label:"Classic change",expected:"directory"});if(!c.exists)throw new Error("Classic change directory does not exist");let l=Jt.posix.join(c.relative.replaceAll("\\","/"),"tasks.md"),f=await ce(e,l,Number.MAX_SAFE_INTEGER,{label:"Classic Build tasks"}),a=nr(f.bytes.toString("utf8"));if(a.length===0||a.some(h=>!h.completed))throw new Error("Classic Build tasks are not all completed");if(n.workflow==="full"){if(await Pf(e,t,r),await If(e,r),!n.plan)throw new Error("Classic Build plan is missing");if(!r.evidenceWaits?.slice().reverse().find(g=>g.stepId==="full.build.plan.evidence"&&g.status==="resolved"&&g.receipt?.ref===n.plan))throw new Error("Classic Build requires its accepted plan step")}let d=Jt.posix.join(c.relative.replaceAll("\\","/"),"proposal.md");if(!(await ce(e,d,Number.MAX_SAFE_INTEGER,{label:"Classic Build proposal"})).bytes.toString("utf8").trim())throw new Error("Classic Build proposal is empty");let u=Jt.posix.basename(c.relative.replaceAll("\\","/")),m=await zx(e,u,n);if(m.length>0)throw new Error(m.join(`
|
|
257
|
+
`))}async function nl(e,t,n){let r=n.state;if(r.workflow==="full")return;let i=n.evidenceWaits?.slice().reverse().find(o=>o.stepId===r.workflow+".open.evidence"&&o.status==="resolved"&&o.receipt?.ref===t),s=n.actions.slice().reverse().find(o=>o.stepId===r.workflow+".open"&&o.status==="succeeded");if(!i||!s)throw new Error("Classic preset requires its accepted Open step")}var LI={id:"comet-classic-open-artifacts",version:"1",async validate({run:e,ref:t,contentHash:n,context:r}){let i=e.state,s=e.input.changeDir,o=e.actions.slice().reverse().find(c=>c.stepId===i.workflow+".open");if(!r?.projectRoot||t!==s||o?.status!=="succeeded"||n!==o.inputHash)return{accepted:!1,actualHash:"",reason:"Classic Open evidence does not belong to its completed Action"};try{await Fs(r.projectRoot,t,{run:e});let c=await iy(r.projectRoot,t,i.language);if(c)throw new Error(c);return{accepted:!0,actualHash:o.inputHash}}catch(c){return{accepted:!1,actualHash:"",reason:String(c)}}}},CV={id:"comet-classic-design-document",version:"1",async validate({run:e,ref:t,contentHash:n,context:r}){let i=e.state,s=e.actions.slice().reverse().find(o=>o.stepId==="full.design.document");if(!r?.projectRoot||i.designDoc!==t||s?.status!=="succeeded"||n!==s.inputHash)return{accepted:!1,actualHash:"",reason:"Classic Design evidence does not belong to its completed Action"};try{return await HI(r.projectRoot,t),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},SV={id:"comet-classic-build-plan",version:"1",async validate({run:e,ref:t,contentHash:n,context:r}){let i=e.state,s=e.actions.slice().reverse().find(o=>o.stepId==="full.build.plan");if(!r?.projectRoot||i.plan!==t||s?.status!=="succeeded"||n!==s.inputHash)return{accepted:!1,actualHash:"",reason:"Classic plan evidence does not belong to its completed Action"};try{return await _f(r.projectRoot,t,String(e.input.changeDir)),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},WI={id:"comet-classic-verification-report",version:"1",async validate({run:e,ref:t,contentHash:n,context:r}){let i=e.state,s=e.actions.slice().reverse().find(o=>o.stepId===i.workflow+".verify.run");if(!r?.projectRoot||i.phase!=="verify"||i.verificationReport!==t||s?.status!=="succeeded"||n!==s.inputHash)return{accepted:!1,actualHash:"",reason:"Classic report does not belong to its completed Verify Action"};try{return await tl(r.projectRoot,t,i.language),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},EV=["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"],Br={type:["string","null"]},MI={type:["boolean","null"]},yy={id:"comet-classic-preset-scope",version:"1",async validate({run:e,outcome:t,context:n}){let r=t.output;if(t.status!=="succeeded"||r?.event!=="escalation-requested"||!r.requirementsEvidence)return{accepted:!0};if(!n?.projectRoot)return{accepted:!1,reason:"Classic preset scope requires its project root"};try{let i=await Fs(n.projectRoot,e.input.changeDir,{presetRequirements:!0});return{accepted:r.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 BI(e){let t=e==="full"?null:BI("full"),n=`${e}.open`,r=`${e}.open.evidence`,i=e==="full"?"full.design.handoff":`${e}.build.execute`,s={id:`comet-classic-${e}-transition`,version:"2"},o={id:"comet-classic-open-artifacts",version:"1"};return{executors:e==="full"?[FI]:t.executors,validators:t?.validators??[...e==="full"?[hy,gy,wy]:[],kV,RV,yy],evidenceValidators:t?.evidenceValidators??(e==="full"?[LI,CV,SV,WI]:[LI,WI]),workflow:{id:`comet-classic-${e}`,version:"2",entry:n,stateSchema:{type:"object",required:EV,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:Br,verifyMode:{enum:[null,"light","full"]},autoTransition:MI,baseRef:Br,designDoc:Br,plan:Br,verifyResult:{enum:["pending","pass","fail"]},verifyFailures:{type:"integer",minimum:0},checkEpoch:{type:"integer",minimum:0},verificationReport:Br,branchStatus:{enum:[null,"pending","handled"]},createdAt:Br,verifiedAt:Br,archiveConfirmation:{enum:[null,"pending","confirmed"]},archived:{type:"boolean"},directOverride:MI,handoffContext:Br,handoffHash:{anyOf:[{type:"null"},{type:"string",pattern:"^[a-f0-9]{64}$"}]},classicProfile:{enum:[null,"full","hotfix","tweak"]},classicMigration:{enum:[null,1]}}},transitionHandler:s,steps:{[n]:{type:"invoke_skill",ref:e==="full"?"comet-open":`comet-${e}`},[r]:{type:"await_evidence",kind:"classic-open-artifacts",validator:o},...e==="full"?{"full.open.confirm":{type:"ask_user",proposalFrom:[n,r],choices:["approved","rejected"]},"full.open.revalidate":{type:"call_tool",ref:"classic-open-revalidate",validator:{id:hy.id,version:hy.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:gy.id,version:gy.version}}:{validator:{id:yy.id,version:yy.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:xf,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:wy.id,version:wy.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:Br,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:xf,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:xf,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:xf,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:n,to:r},{from:r,to:e==="full"?"full.open.confirm":i},...e==="full"?[{from:"full.open.confirm",to:"full.open.revalidate",on:"approved"},{from:"full.open.confirm",to:n,on:"rejected"},{from:"full.open.revalidate",to:i},{from:"full.open.revalidate",to:n}]:[{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:{...s,apply({run:c,event:l}){if(l.kind==="action-outcome"&&l.outcome.status==="succeeded"&&(l.stepId.endsWith(".build.execute")||l.stepId.endsWith(".verify.run"))){let a=l.outcome.output;if(["build-complete","verification-ready"].includes(a.event??"")){let d=c.actions.find(p=>p.id===l.outcome.actionId);(d?.executionOrigin?.workflow.version!=="1"||d.status!=="succeeded"||c.outputs[l.stepId]?.sequence!==c.actionContexts[d.id]?.sequence||!vy(c.outputs[l.stepId]?.value,d.outcome?.output)||!vy(d.outcome,l.outcome))&&rl(a)}}if(l.kind==="action-outcome"&&l.outcome.status==="failed"&&c.actions.find(d=>d.id===l.outcome.actionId)?.type==="invoke_skill")return{state:c.state,next:[]};if(t&&l.stepId.startsWith("full."))return t.transitionHandler.apply({run:c,event:l});if(e!=="full"&&l.kind==="wait-resolved"&&l.stepId===`${e}.build.escalation-confirm`){if(l.choice==="continue")return{state:c.state,next:[i]};if(l.choice!=="upgrade")throw new Error("Classic preset escalation choice is invalid");let a=c.state;return{state:{...bt(a,"preset-escalate").classic,isolation:a.isolation,boundBranch:a.boundBranch},next:["full.design.handoff"]}}if(e!=="full"&&l.kind==="action-outcome"&&l.stepId===i){let a=l.outcome.output;if(l.outcome.status==="succeeded"&&a.event==="escalation-requested"&&typeof a.proposal=="string"&&a.proposal.trim())return{state:c.state,next:[`${e}.build.escalation-confirm`]};if(l.outcome.status!=="succeeded"||a.event!=="build-complete")throw new Error("Classic preset Build result does not match its declared transition");return{state:bt(c.state,"build-complete").classic,next:[`${e}.verify.run`]}}if(e!=="full"&&l.kind==="action-outcome"&&l.stepId===`${e}.verify.run`){let a=l.outcome.output;if(l.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:bt(c.state,"verify-fail").classic,next:[`${e}.build.execute`]}}if(l.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"&&l.kind==="evidence-recorded"&&l.stepId===`${e}.verify.report.evidence`){if(l.ref!==c.state.verificationReport)throw new Error("Classic preset Verify report evidence does not match");return{state:bt(c.state,"verify-pass").classic,next:[`${e}.archive.prepare`]}}if(e!=="full"&&l.kind==="action-outcome"&&l.stepId===`${e}.archive.prepare`){if(l.outcome.status!=="succeeded")throw new Error("Classic preset Archive preparation did not complete");return{state:c.state,next:[`${e}.archive.confirm`]}}if(l.kind==="action-outcome"&&l.stepId===n){if(l.outcome.status!=="succeeded"||l.outcome.output?.event!=="open-complete")throw new Error("Classic Open result does not match its declared transition");return{state:c.state,next:[r]}}if(e==="full"&&l.kind==="wait-resolved"&&l.stepId==="full.open.confirm")return{state:c.state,next:[l.choice==="approved"?"full.open.revalidate":n]};if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.open.revalidate"){if(l.outcome.status!=="succeeded")throw new Error("Classic Open revalidation did not complete");return{state:bt(c.state,"open-complete").classic,next:[i]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId===i){if(l.outcome.status!=="succeeded")throw new Error("Classic Design handoff did not succeed");let a=l.outcome.output;return{state:{...c.state,...c.commands?.some(d=>d.name==="revise-design"&&d.actionId===l.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"&&l.kind==="wait-resolved"&&l.stepId==="full.design.confirm")return{state:c.state,next:[l.choice==="approved"?"full.design.document":"full.design.handoff"]};if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.design.document"){if(l.outcome.status!=="succeeded")throw new Error("Classic Design document work did not succeed");let a=l.outcome.output.designDoc;return{state:{...c.state,designDoc:a},next:["full.design.evidence"]}}if(e==="full"&&l.kind==="evidence-recorded"&&l.stepId==="full.design.evidence"){if(l.ref!==c.state.designDoc)throw new Error("Classic Design evidence does not match the selected document");return{state:bt(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"&&l.kind==="action-outcome"&&l.stepId==="full.build.configure"){if(l.outcome.status!=="succeeded")throw new Error("Classic Build configuration did not succeed");return{state:c.state,next:["full.build.confirm"]}}if(e==="full"&&l.kind==="wait-resolved"&&l.stepId==="full.build.confirm"){if(l.choice==="rejected")return{state:c.state,next:["full.build.configure"]};let d=c.waits.find(g=>g.stepId==="full.build.confirm"&&g.decision?.id===l.decisionId&&g.proposalHash===l.proposalHash)?.proposal?.outputs?.["full.build.configure"],p=c.outputs["full.build.configure"]?.value;if(l.choice!=="approved"||d===void 0||p===void 0||j(d)!==j(p))throw new Error("Classic Build confirmation no longer matches the proposed choices");let u=d,m={...c.state,...u},h=br(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"&&l.kind==="action-outcome"&&l.stepId==="full.build.plan"){if(l.outcome.status!=="succeeded")throw new Error("Classic Build plan work did not succeed");let{plan:a,buildPause:d}=l.outcome.output;return{state:{...c.state,plan:a,buildPause:d??null},next:["full.build.plan.evidence"]}}if(e==="full"&&l.kind==="evidence-recorded"&&l.stepId==="full.build.plan.evidence"){if(l.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"&&l.kind==="wait-resolved"&&l.stepId==="full.build.plan-ready"){if(l.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"&&l.kind==="action-outcome"&&l.stepId==="full.build.execute"){if(l.outcome.status!=="succeeded"||l.outcome.output?.event!=="build-complete")throw new Error("Classic Build work did not complete");return{state:bt(c.state,"build-complete").classic,next:[`${e}.verify.run`]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.verify.run"){if(l.outcome.status!=="succeeded")throw new Error("Classic Verify assessment did not complete");let a=l.outcome.output;if(a.event==="verify-fail"){if(!a.reason?.trim())throw new Error("Classic Verify failure requires a reason");return{state:bt(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"&&l.kind==="evidence-recorded"&&l.stepId==="full.verify.report.evidence"){if(l.ref!==c.state.verificationReport)throw new Error("Classic Verify evidence does not match the selected report");return{state:bt(c.state,"verify-pass").classic,next:[`${e}.archive.prepare`]}}if(e==="full"&&l.kind==="action-outcome"&&l.stepId==="full.archive.prepare"){if(l.outcome.status!=="succeeded")throw new Error("Classic Archive preparation did not complete");return{state:c.state,next:["full.archive.confirm"]}}if(l.kind==="wait-resolved"&&l.stepId===`${e}.archive.confirm`){if(l.choice==="reverify")return{state:bt(c.state,"archive-reopen").classic,next:[`${e}.verify.run`]};if(l.choice==="later")return{state:c.state,next:[`${e}.archive.confirm`]};let d=c.waits.find(g=>g.stepId===`${e}.archive.confirm`&&g.decision?.id===l.decisionId&&g.proposalHash===l.proposalHash)?.proposal?.outputs?.[`${e}.archive.prepare`],p=c.outputs[`${e}.archive.prepare`]?.value;if(d===void 0||p===void 0||j(d)!==j(p))throw new Error("Classic Archive choice no longer matches its proposal");let u=d,m=c.state;if(!["local","push","pr"].includes(l.choice)||!m.boundBranch||u.targetBranch!==m.boundBranch||l.choice!=="local"&&!u.remote||l.choice==="pr"&&!u.prBaseBranch)throw new Error("Classic Archive target does not match the bound branch or delivery");return{state:bt(m,"archive-confirm").classic,next:[`${e}.archive.preflight`]}}if(l.kind==="action-outcome"&&l.stepId===`${e}.archive.preflight`){if(l.outcome.status!=="succeeded")throw new Error("Classic Archive preflight did not pass");let a=c.waits.slice().reverse().find(u=>u.stepId===`${e}.archive.confirm`&&u.status==="resolved"&&["local","push","pr"].includes(u.decision?.choice??"")),d=a?.proposal?.outputs?.[`${e}.archive.prepare`],p=l.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(l.kind==="action-outcome"&&l.stepId===`${e}.archive.execute`){if(l.outcome.status!=="succeeded")return{state:c.state,next:[]};let a=bt(c.state,"archived"),d=c.input.changeDir.replaceAll("\\","/"),p=l.outcome.output.archiveDirectory.replaceAll("\\","/");return{state:{...a.classic,designDoc:ht(a.classic.designDoc,d,p),plan:ht(a.classic.plan,d,p),verificationReport:ht(a.classic.verificationReport,d,p),handoffContext:ht(a.classic.handoffContext,d,p)},next:[`${e}.archive.deliver`]}}if(l.kind==="action-outcome"&&l.stepId===`${e}.archive.deliver`)return l.outcome.status!=="succeeded"?{state:c.state,next:[]}:{state:{...c.state,branchStatus:"handled"},next:[]};if(l.kind!=="evidence-recorded"||l.stepId!==r||l.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:bt(c.state,"open-complete").classic,next:[i]}}}}}function rl(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 Xo=BI;import{AsyncLocalStorage as NV}from"node:async_hooks";Wa();Fa();rn();import{AsyncLocalStorage as xV}from"node:async_hooks";Xd();import{createHash as IV,randomUUID as UI}from"node:crypto";import Ry from"node:path";uh();import{promises as Tf}from"node:fs";import by from"node:path";async function Nf(e,t){let n=lh(e),r=by.join(n.workspaceRoot,"observability"),i=n.dataRoot;for(let o of["","workspaces",n.workspaceId,"observability"]){i=by.join(i,o);let c;try{c=await Tf.lstat(i)}catch(l){if(!t||l.code!=="ENOENT")throw l;await Tf.mkdir(i,{recursive:o===""}).catch(f=>{if(f.code!=="EEXIST")throw f}),c=await Tf.lstat(i)}if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let s=by.join(r,"performance.sqlite");for(let o of["","-wal","-shm"])try{let c=await Tf.lstat(s+o);if(!c.isFile()||c.isSymbolicLink()||c.size>64*1024*1024)throw new Error("Runtime 统计文件无效")}catch(c){if(c.code!=="ENOENT")throw c}return s}import{stripVTControlCharacters as AV}from"node:util";function VI(e,t=process.env){let n=AV(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[r,i]of Object.entries(t))i&&i.length>=6&&/key|token|password|secret|credential/iu.test(r)&&(n=n.split(i).join("[redacted]"));return n}var _V=864e5,PV=1e4,$f=new xV;function Cy(e){let t=$f.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function il(e,t){return VI(e).slice(0,t)}async function jf(e,t){if(!t.length)return;let n=$f.getStore();if(n){let i=s=>process.platform==="win32"?Ry.resolve(s).toLowerCase():Ry.resolve(s);if(i(e)===i(await n.projectRoot())){n.spans.push(...t);return}}let r=Mo(await Nf(e,!0));try{r.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
258
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
259
|
+
id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
|
|
260
|
+
change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
|
|
261
|
+
parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
262
|
+
started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
|
|
263
|
+
revision INTEGER NOT NULL, data TEXT NOT NULL);
|
|
264
|
+
CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
|
|
265
|
+
CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
|
|
266
|
+
BEGIN IMMEDIATE;`);let i=r.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
267
|
+
ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
|
|
268
|
+
started_at=COALESCE(trace_spans.started_at,excluded.started_at),
|
|
269
|
+
ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
|
|
270
|
+
WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
|
|
271
|
+
ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
|
|
272
|
+
revision=MAX(trace_spans.revision,excluded.revision),
|
|
273
|
+
data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
|
|
274
|
+
WHERE excluded.revision >= trace_spans.revision OR (trace_spans.started_at IS NULL AND excluded.started_at IS NOT NULL)`),s=t.length>1e3?[...t.filter(o=>o.parentSpanId===null),...t.filter(o=>o.parentSpanId!==null).slice(-999)].slice(0,1e3):t;for(let o of s){if(!o.change||!o.runId||!o.traceId||!o.spanId||o.change.length>240||o.runId.length>240||o.traceId.length>512||o.spanId.length>512||(o.parentSpanId?.length??0)>512)continue;let c={...o,name:il(o.name,240),summary:o.summary?il(o.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(o.attributes??{}).slice(0,20).map(([a,d])=>[il(a,80),Array.isArray(d)?d.slice(0,30).map(p=>il(p,240)):typeof d=="string"?il(d,2e3):d]))};t.length>1e3&&o.parentSpanId===null&&(c.attributes.truncated=!0);let l=JSON.stringify(c);for(;Buffer.byteLength(l,"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;l=JSON.stringify(c)}if(Buffer.byteLength(l,"utf8")>4096)continue;let f=IV("sha256").update(JSON.stringify([o.traceId,o.spanId])).digest("hex");i.run(f,o.traceId,o.workflow,o.change,o.runId,o.spanId,o.parentSpanId,o.kind,c.name,o.status,o.startedAt,o.endedAt,o.updatedAt,o.revision,l)}r.prepare("DELETE FROM trace_spans WHERE updated_at < ?").run(new Date(Date.now()-7*_V).toISOString()),r.prepare("DELETE FROM trace_spans WHERE id IN (SELECT id FROM trace_spans ORDER BY updated_at DESC, id DESC LIMIT -1 OFFSET ?)").run(PV),r.exec("COMMIT")}finally{r.close()}}async function KI(e,t){let n=$f.getStore(),r=n?.binding.workflow===e.workflow?n:void 0;if(r)try{let p=(await Promise.all([e.projectRoot(),r.projectRoot()])).map(u=>{let m=Ry.resolve(u);return process.platform==="win32"?m.toLowerCase():m});(p[0]!==p[1]||e.runId&&r.binding.runId&&e.runId!==r.binding.runId)&&(r=void 0)}catch{r=void 0}let i=new Date().toISOString(),s={traceId:r?.traceId??UI(),spanId:UI(),binding:r?.binding??{workflow:e.workflow,change:e.change,runId:e.runId},spans:r?.spans??[],startedAt:i,kind:e.kind,name:e.name,projectRoot:e.projectRoot,parent:r};if(s.binding.change&&s.binding.runId){let d=[];for(let p=s;p;p=p.parent)d.push({traceId:p.traceId,spanId:p.spanId,parentSpanId:p.parent?.spanId??null,workflow:s.binding.workflow,change:s.binding.change,runId:s.binding.runId,kind:p.kind,name:p.name,status:"running",startedAt:p.startedAt,endedAt:null,updatedAt:i,revision:0});try{await jf(await e.projectRoot(),d)}catch{}}let o,c,l=!1;try{o=await $f.run(s,t)}catch(d){l=!0,c=d}let f=new Date().toISOString(),a=l?"failed":"succeeded";try{!l&&e.status&&(a=e.status(o))}catch{a="unknown"}if(s.binding.change&&s.binding.runId&&s.spans.push({traceId:s.traceId,spanId:s.spanId,parentSpanId:r?.spanId??null,workflow:s.binding.workflow,change:s.binding.change,runId:s.binding.runId,kind:e.kind,name:e.name,startedAt:i,endedAt:f,updatedAt:f,revision:1,status:a}),!r&&s.spans.length)try{await jf(await e.projectRoot(),s.spans)}catch{}if(l)throw c;return o}var OV=(e,t)=>`workflow:${e}:${t}`,zI=(e,t)=>{let n=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(n[0])?n[1]??n[0]:n[0]},JI=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}))}),GI=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function TV(e){let{workflow:t,previous:n,next:r,initial:i,observedAt:s}=e,o=OV(t,r.runId),c=`run:${r.runId}`,l={workflow:t,change:r.runId,runId:r.runId,traceId:o,updatedAt:s,revision:r.revision},f=["completed","failed","cancelled"].includes(r.status),a=new Map(n?.actions.map(p=>[`${p.id}:${p.attempt}`,p])),d=[{...l,spanId:c,parentSpanId:null,kind:"workflow",name:r.workflow.id,status:r.status==="completed"?"succeeded":r.status,startedAt:i?s:null,endedAt:f&&(i||n!==null&&n.status!==r.status)?s:null,summary:r.reason,attributes:{workflowVersion:r.workflow.version,sequence:r.sequence,parentRunIds:r.lineage,childRunIds:r.children.map(p=>p.runId)}}];for(let p of r.actions){let u=a.get(`${p.id}:${p.attempt}`);if(u&&u.status===p.status&&u.outcome?.outcomeId===p.outcome?.outcomeId&&u.reason===p.reason&&u.outcome?.summary===p.outcome?.summary)continue;let m=["succeeded","failed","cancelled"].includes(p.status);d.push({...l,spanId:`action:${p.id}:${p.attempt}`,parentSpanId:c,kind:"action",name:p.stepId,status:p.status,attempt:p.attempt,startedAt:p.status==="running"&&(u?.status==="pending"||i)?s:null,endedAt:m&&(i||n!==null)?s:null,summary:p.outcome?.summary??p.reason,attributes:{phase:zI(p.stepId,t),actionId:p.id,actionType:p.type,ref:p.ref??null,executor:p.claim?.executorId??null,inputFields:GI(p.input),outputFields:p.outcome?GI(p.outcome.output):[],artifacts:(p.outcome?.artifacts??[]).map(h=>h.uri)}})}for(let p of["wait","evidence"]){let u=p==="wait"?r.waits:r.evidenceWaits??[],m=p==="wait"?n?.waits:n?.evidenceWaits,h=new Map(m?.map(g=>[g.id,g]));for(let g of u){let w=h.get(g.id);w?.status!==g.status&&d.push({...l,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&&(n!==null||i)&&g.status==="pending"?s:null,endedAt:g.status!=="pending"&&(i||n!==null)?s:null,attributes:{phase:zI(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return d}function YI(e,t,n){let r=null;return{...n,...n.restoreCheckpoint?{restoreCheckpoint:(i,s,o)=>n.restoreCheckpoint(i,s,o)}:{},async read(i){let s=await n.read(i);try{r=s?JI(s):null}catch{r=null}return s&&Cy({workflow:t,change:s.runId,runId:s.runId}),s},async compareAndSwap(i,s,o){let c=r?.runId===i&&r.revision===s?r:null,l=await n.compareAndSwap(i,s,o);if(l){Cy({workflow:t,change:i,runId:i});try{await jf(e,TV({workflow:t,previous:c,next:o,initial:s===null,observedAt:new Date().toISOString()}))}catch{}try{r=JI(o)}catch{r=null}}return l}}}kt();rn();import{promises as $V}from"node:fs";var sl=Rt(Pt(),1);import{createHash as jV}from"node:crypto";import Hs from"node:path";import{isDeepStrictEqual as DV}from"node:util";Qe();gn();nn();nn();var XI=new Set(["language","contextCompression","autoTransition","reviewMode"]);var QI=new NV;function qV(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 Ln(e,t){return DV(e,t)}function ZI(e,t){return Object.keys(e).filter(n=>!Ln(e[n],t[n]))}function Sy(e){return e.actions.some(Jc)}function Wi(e,t={},n=!1){let r=lt(e),i=!1,s=async(p=t.readOnly)=>{if(!p&<(e)!==r)throw new Error("Classic SDK workspace identity changed; reload the store in the current workspace");return!p&&!i&&(await ur(e),i=!0),r},o=YI(e,"classic",t.store??pn({singleWriter:!0,rootDir:Hs.join(r,"sdk-runs","classic")})),c=p=>JSON.stringify([r,p]);function l(p,u){if(t.identity){let h=["runtime","dispatch","--application-file",Hs.join(t.identity.packageRoot,"application.json"),"--project-root",e,"--request","<recovery-request.json>","--json"];throw new Error(`Classic SDK Run ${p} requires recovery: ${u}. 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.
|
|
275
|
+
Recovery argv: ${JSON.stringify(h)}
|
|
276
|
+
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: ${u}. ${m} in ${e} to restore or synchronize its recorded state.`)}async function f(p,u){let m=null;for(let L of await Kn(e,p)){let Z;try{Z=await le(e,L,{label:"Classic state file"})}catch(Y){if(Y.code==="ENOENT")continue;throw Y}if(Et(Z)){if(m)throw new Error(`Classic change ${p} has multiple SDK state files`);m={file:L,source:Z}}}if(!m)return null;let h=(0,sl.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=yn(g[It],p,{preserveSourceRevision:!0});if(!w)return null;if(j(g.application_checkpoint??null)!==j(t.identity??null))throw new Error("Classic portable checkpoint requires its original fixed Application package");let k=tn(g).classic,y=w.input,R=w.workflow.id.replace(/^comet-classic-/u,""),C=k?ZI(w.state,k):[],A=typeof y?.changeDir=="string"?await ue(Hs.join(e,...y.changeDir.split("/"))):null,q=A!==null&&m.file!==A;if(!k||C.some(L=>!XI.has(L))||y?.change!==p||y.changeDir!==`openspec/changes/${p}`&&y.changeDir!==`docs/openspec/changes/${p}`||q&&!k.archived&&!Sy(w)||!["full","hotfix","tweak"].includes(R)||w.workflow.id!==`comet-classic-${R}`||k.workflow!==R&&!Gc(w,R)||!t.allowBranchRebind&&k.boundBranch!==null&&k.boundBranch!==st(e))throw new Error(`Classic portable Run checkpoint for ${p} does not match its state`);let D=w.revision,K={...w,revision:D,...u?{state:k}:{}};if(u&&j(u)!==j({...K,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||u)&&!o.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 rc(e,{schema:us,workflow:"classic",change:p,format:"sdk",application:t.identity?.id??`classic-${R}`,runId:p}),D===1&&!u?await o.compareAndSwap(p,null,K):await o.restoreCheckpoint(p,u?1:null,K),o.read(p)}async function a(p){let u=p.input;if(u?.change!==p.runId||typeof u.changeDir!="string")throw new Error(`Classic SDK Run ${p.runId} has invalid change identity`);let m=u.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=Hs.join(e,...m.split("/"));try{if((await $V.stat(h)).isDirectory())return ue(h)}catch(y){if(y.code!=="ENOENT")throw y}if(!p.state.archived&&!Sy(p))return null;let g=Hs.join(Hs.dirname(h),"archive"),w=await Uu(e,g,p.runId);if(w===null)return null;let k=w.filter(y=>y!==p.runId);if(k.length!==1)throw new Error(`Classic SDK Archive ${p.runId} is ambiguous`);return ue(Hs.join(g,k[0]))}async function d(p,u){return await Kn(e,p),await s(),(async()=>{let h;if(n)try{h=(await Co(o,p)).record}catch(z){if(z.code!=="RUN_NOT_FOUND")throw z;h=null}else h=await o.read(p);if(!h){t.readOnly&&l(p,"the recorded Run is missing or incomplete");let z=await La(()=>f(p,h??void 0));if(h&&!z)throw new Error(`Classic SDK Run ${p} requires its matching portable checkpoint or original Run history before completing recovery`);h=z}if(!h)return null;let g=h,w=g.state,k=await a(g),y=g.revision===1&&g.actions.every(z=>z.status==="pending"&&!z.claim);if(!k)return t.readOnly&&!y&&l(p,"the change directory is missing"),g;let R;try{R=await le(e,k,{label:"Classic state file"})}catch(z){if(z.code!=="ENOENT")throw z;R=null}let C=R===null?new sl.Document:(0,sl.parseDocument)(R,{uniqueKeys:!0});if(C.errors.length>0)throw new Error(`Invalid Classic state file: ${C.errors[0].message}`);let A=C.toJS(),q=R===null?null:tn(A).classic,D=Go(A?.[It],g,{projection:n});if(D)return(R===null||!Et(R)||!Ln(q,D.state)||t.identity&&!Ln(A.application_checkpoint,t.identity))&&l(p,"the immutable archived delivery checkpoint has changed"),g;if(q){let z=yn(A?.[It],p,{preserveSourceRevision:!0});if(g.revision===1&&z&&z.revision>g.revision){t.readOnly&&l(p,"the initial checkpoint import is incomplete");let I=await f(p,g);I||l(p,"the initial checkpoint import is incomplete"),g=I,w=g.state}let ne=z?.state??w,Le=ZI(ne,q);if(Le.some(I=>!XI.has(I))){let I=g.input?.recoverySourceHash,V=g.revision===1&&typeof I=="string"&&R!==null&&jV("sha256").update(R).digest("hex")===I;if(!Ln(q,w)&&!V)throw new Error(`Classic state file ${k} changed a Runtime-owned field`)}else if(Le.some(I=>!Ln(w[I],q[I]))){if(!u)throw new Error(`Classic state file ${k} changed during an SDK transition`);for(let V of Le)if(!Ln(w[V],ne[V])&&!Ln(w[V],q[V]))throw new Error(`Classic state file ${k} conflicts with SDK field ${V}`);t.readOnly&&l(p,"state file settings have not been imported"),w={...w};for(let V of Le)w[V]=q[V];let I={...g,revision:g.revision+1,state:w};if(await La(()=>Kn(e,p)),!await o.compareAndSwap(p,g.revision,I))throw new Error(`Classic SDK Run ${p} changed while importing state file settings`);g=I}}if(q&&w.boundBranch===null&&vo(w.isolation)&&!w.archived&&["running","waiting"].includes(g.status)&&!g.actions.some(z=>["running","unknown"].includes(z.status))){let z=_n({isolation:w.isolation,boundBranch:w.boundBranch,currentBranch:st(e)});if(z.status==="needs-heal"){t.readOnly&&l(p,"the Git branch binding has not been recorded"),w={...w,boundBranch:z.branch};let ne={...g,revision:g.revision+1,state:w};if(await La(()=>Kn(e,p)),!await o.compareAndSwap(p,g.revision,ne))throw new Error(`Classic SDK Run ${p} changed while binding its Git branch`);g=ne}}if(t.readOnly){let z=A?.[It],ne=z===void 0;return z!==void 0&&n?ne=_s(z,g):z!==void 0&&(ne=Hc(z,Pi(g))),(R===null||!Et(R)||!q||!Ln(q,w)||!ne||t.identity&&A.application_checkpoint!==void 0&&!Ln(A.application_checkpoint,t.identity))&&l(p,"the state projection or portable checkpoint is missing or stale"),g}let K=Wu(w),L=A??{};for(let[z,ne]of Object.entries(K))Ln(L[z],ne)||(ne===void 0?C.delete(z):C.set(z,ne));let Z=tf(Pi(g));Ln(L[It],Z)||C.set(It,Z),t.identity&&!Ln(L.application_checkpoint,t.identity)&&C.set("application_checkpoint",t.identity);let Y=C.toString(),fe=Et(Y)?Y:ah+Y;return R!==fe&&await wt(e,k,fe,{label:"Classic state file"}),$s(g)&&(t.identity||await Ma(e,"classic",g.runId)),g})()}return{queryScope:o.queryScope,async read(p){if(!t.identity&&QI.getStore()?.has(c(p)))return await s(!0),o.read(p);if(!t.readOnly){await s(!0);try{let u=await Wi(e,{...t,store:o,readOnly:!0}).read(p);if(u&&!$s(u))return u}catch{}}return d(p,!0)},async readProjection(p){await s(!0);let u=await Wi(e,{...t,store:o,readOnly:!0},!0).read(p);return await s(!0),u},async compareAndSwap(p,u,m){return La(async()=>{if(t.readOnly)throw new Error("Classic SDK read-only store cannot change a Run");if(m.status==="cancelled"&&u!==null){let g=await o.read(p);if(g&&Sy(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 Kn(e,p),u!==null&&await a(m),await s();let h=await o.compareAndSwap(p,u,m);if(h&&u!==null){let g=QI.getStore(),w=c(p);g&&!t.identity&&m.workflow.version==="2"&&!qV(m)?g.set(w,()=>d(p,!1)):(g?.delete(w),await d(p,!1))}return h})}}}async function e_(e){let t={change:e.name,changeDir:LV.relative(e.projectRoot,e.changeDir).replaceAll("\\","/"),...e.recoverySourceHash?{recoverySourceHash:e.recoverySourceHash}:{},...e.recoverySource?{recoverySource:e.recoverySource}:{}},n=e.recoverySourceHash?t:await TI(e.projectRoot,t),r=Xo(e.profile),i=Wi(e.projectRoot);return xs({store:{async read(c){let l=await i.read(c);if(l&&!await pr(e.projectRoot,"classic",c))throw new b("RUN_OWNER_MISSING",`Classic SDK Run ${c} 缺少归属记录`);return l},async compareAndSwap(c,l,f){if(l===null){if(c!==e.name)throw new Error("Classic SDK Run ID and change name differ");await rc(e.projectRoot,{schema:us,workflow:"classic",change:e.name,format:"sdk",application:`classic-${e.profile}`,runId:c},{canonical:!0})}return i.compareAndSwap(c,l,f)}},workflows:[r.workflow],transitionHandlers:[r.transitionHandler],evidenceValidators:r.evidenceValidators,validators:r.validators}).start({runId:e.name,workflow:{id:r.workflow.id,version:r.workflow.version},input:n,initialState:e.initialState})}nn();Qe();async function MV(e,t){if(!Et(t))return null;let n=(0,Ey.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Classic state: ${n.errors[0].message}`);let r=tn(n.toJS()).classic,i=await WV.readdir(e),s=[];for(let o of i)o===".comet-state.lock"&&await KR(t_.join(e,o))||s.push(o);return r?.phase==="open"&&r.designDoc===null&&r.plan===null&&r.verifyResult==="pending"&&r.verifyFailures===0&&!r.archived&&s.every(o=>xu(o)||o===".openspec.yaml")?r:null}async function FV(e,t,n){return await Kn(e,t),n()}async function Ay(e,t){await Kn(e,t);let n=await yi(e,"classic",t);return n||FV(e,t,async()=>{let r=await yi(e,"classic",t);if(r)return r;let i=(await ss(t,e)).directory,s=t_.relative(e,await ue(i)),o=await M(e,s,{label:"Classic legacy change state",expected:"file"});if(!o.exists)return null;let c=await le(e,o.target,{label:"Classic change state"});if(Et(c)){let l=(0,Ey.parseDocument)(c,{uniqueKeys:!0});if(l.errors.length>0)throw new Error(`Invalid Classic state: ${l.errors[0].message}`);let f=l.toJS(),a=tn(f).classic;if(a?.archived&&a.isolation==="worktree"&&f.application_checkpoint==null&&a.boundBranch&&a.boundBranch!==st(e)&&yn(f[It],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 Wi(e).read(t)){let p=await yi(e,"classic",t);if(!p||p.format!=="sdk")throw new Error(`Recovered Classic change ${t} has no Run ownership`);return p}let d=await MV(i,c);if(d){await e_({projectRoot:e,name:t,profile:d.workflow,changeDir:i,initialState:d});let p=await yi(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 OC(e,{schema:us,workflow:"classic",change:t,format:"compat"})})}import{isDeepStrictEqual as VV}from"node:util";var n_=Rt(Pt(),1);import HV from"node:path";Qe();kt();nn();async function Df(e,t,n,r="delivery",i){let s=Ls(t,n),o=t.state,c=_n({isolation:o.isolation,boundBranch:o.boundBranch,currentBranch:st(e),gitWorkTree:on(e)});if(!["ok","not-applicable"].includes(c.status))throw new Error("Classic delivery repair requires its approved branch");await Di(e,t,s.archive,s.archiveRef);{if(!n.reports||n.command||n.excludedOutputPaths?.length)throw new Error("Classic v2 delivery repair requires platform reports and the approved paths");return{...s}}}async function r_(e,t,n){if(!vf(t))throw new Error("Classic delivery repair requires the original archived Run with no unresolved execution");let r=Ls(t);{if(!n)throw new Error("Classic v2 delivery repair requires --checks <checks-json-file>");rl(n);let i={checkpointHash:await BV(e,t),archiveActionId:r.archive.id,checkActionId:r.check.id,reports:n};return await Df(e,t,i,"prepare"),i}}async function BV(e,t){let n=Ls(t),r=await le(e,await ue(HV.join(e,n.archiveRef)),{label:"Classic archived delivery checkpoint",maxBytes:Number.MAX_SAFE_INTEGER}),i=(0,n_.parseDocument)(r,{uniqueKeys:!0});if(!Et(r)||i.errors.length)throw new Error("Classic archived checkpoint is invalid");let s=Fe(i.toJS()),o=s.run_checkpoint;if(j(tn(s).classic)!==j(t.state)||!_s(o,t)&&Go(o,t,{projection:!0})===null)throw new Error("Classic archived checkpoint changed after the authoritative Run was read");return j(o)}function i_(e,t,n){let r=`${t}.delivery.check`,i=`${t}.delivery.confirm`,s={id:"comet-classic-delivery-repair-command",version:"1",async validate({run:l,name:f,input:a,context:d}){let p=Fe(a);if(!d?.projectRoot||f!=="repair-delivery"||p.expectedRevision!==l.revision||p.fromPhase!=="archive"||Object.keys(p).length!==3)return{accepted:!1,reason:"Classic delivery repair requires its current revision"};if(n){let h=l.workflow.hash===n.workflow.hash?structuredClone(n):Ps(n);if(h.workflow.hash=l.workflow.hash,h.definitionHashes[JSON.stringify([l.workflow.id,l.workflow.version])]=l.workflow.hash,j(h)!==j(l))return{accepted:!1,reason:"Classic delivery repair no longer matches its authoritative source Run"}}let u=await r_(d.projectRoot,n??l,p.deliveryRepair.reports),m=j(u)===j(p.deliveryRepair);return{accepted:m,allowFailed:m&&l.status==="failed",reason:"Classic delivery repair scope changed"}}},o={id:"comet-classic-delivery-repair-check",version:"1",async validate({run:l,action:f,outcome:a,context:d}){if(!d?.projectRoot||!zo(l,f)||f.claim?.executorId!=="comet-classic-check")return{accepted:!1,reason:"Classic delivery repair check has the wrong execution owner"};{let p=Jo(f);if(a.status!=="succeeded"||!VV(a.output,{...p.reports,deliveryPaths:sy(l,p)}))return{accepted:!1,reason:"Classic delivery repair reports differ from the submitted reports"}}return a.status==="succeeded"&&await Df(d.projectRoot,l,Jo(f),"delivery"),{accepted:!0}}},c={id:"comet-classic-check",capabilities:[],supports:l=>l.type==="call_tool"&&l.ref==="classic-check"&&l.stepId===r,async preflight(l,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");await Df(f.projectRoot,a,Jo(l),"prepare")},async execute(l,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");{let d=Jo(l);return{status:"succeeded",output:{...d.reports,deliveryPaths:sy(a,d)}}}}};return{...e,workflow:{...e.workflow,steps:{...e.workflow.steps,[r]:{type:"call_tool",ref:"classic-check",validator:{id:o.id,version:o.version}},[i]:{type:"ask_user",proposalFrom:r,choices:["approved","later"]}},transitions:[...e.workflow.transitions??[],{from:r,to:i},{from:i,to:`${t}.archive.deliver`,on:"approved"},{from:i,to:i,on:"later"}],commands:{...e.workflow.commands,"repair-delivery":{stepId:r,validator:{id:s.id,version:s.version}}}},commandValidators:[...e.commandValidators,s],validators:[...e.validators,o],executors:[...e.executors,c],transitionHandler:{...e.transitionHandler,apply(l){if(l.event.kind==="action-outcome"&&l.event.stepId===r)return{state:l.run.state,next:l.event.outcome.status==="succeeded"?[i]:[]};if(l.event.kind==="wait-resolved"&&l.event.stepId===i){let f=l.run.actions.slice().reverse().find(a=>a.stepId===r&&a.status==="succeeded");return{state:l.run.state,next:l.event.choice==="approved"&&f?[{stepId:`${t}.archive.deliver`,input:{deliveryRepairCheckId:f.id}}]:[i]}}return e.transitionHandler.apply(l)}}}}function Py(e){let t=e.actions.at(-1);return e.status==="failed"&&t?.status==="failed"&&t.type==="invoke_skill"&&!e.actions.some(n=>["running","unknown","pending"].includes(n.status))&&!e.waits.some(n=>n.status==="pending")&&!e.evidenceWaits?.some(n=>n.status==="pending")?t:null}var ol={id:"comet-classic-work-continuation-command",version:"1",async validate({run:e,name:t,input:n,context:r}){let i=n,s=Py(e),o=t==="continue-work"&&s!==null&&i?.expectedRevision===e.revision&&i.fromPhase===e.state.phase&&i.interruptedActionId===s.id&&Object.keys(i).filter(c=>c!=="deliveryCheckpointHash").length===3;return{accepted:o,allowFailed:o,reason:"Classic continuation requires the original settled failed Skill and current revision"}}},s_={id:"comet-classic-work-continuation",capabilities:[],supports:e=>e.ref==="classic-work-continuation",async execute(e,t,n){let r=e.input.activation?.interruptedActionId,i=n?.actions.find(s=>s.id===r);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}}}},xy={id:"comet-classic-work-continuation-outcome",version:"1",validate({run:e,action:t,outcome:n}){let r=t.input.activation?.interruptedActionId,i=e.actions.find(s=>s.id===r);return{accepted:t.claim?.executorId===s_.id&&n.status==="succeeded"&&i?.status==="failed"&&i.type==="invoke_skill"&&j(n.output)===j({interruptedActionId:i.id,resumeStepId:i.stepId}),reason:"Classic continuation does not match its original failed Skill"}}};function Oy(e){let t=e.state,n=e.actions.at(-1);return t.phase==="build"&&e.status==="failed"&&!t.archived&&n?.status==="failed"&&n.stepId===`${t.workflow}.build.execute`&&!e.actions.some(r=>["running","unknown","pending"].includes(r.status))?n:null}var Iy={id:"comet-classic-build-continuation-command",version:"1",validate({run:e,name:t,input:n}){let r=n,i=e.state,s=t==="continue-build"&&(Oy(e)!==null||Bs(e))&&r?.expectedRevision===e.revision&&r.fromPhase===i.phase&&Object.keys(r).length===2;return{accepted:s,allowFailed:s,reason:"Classic Build continuation requires the current stopped failed Builder"}}};function Ty(e){let t=e.state;return t.archived||t.phase!=="archive"||!["failed","running"].includes(e.status)||e.actions.some(n=>["running","unknown","pending"].includes(n.status))||e.waits.some(n=>n.status==="pending")||e.evidenceWaits?.some(n=>n.status==="pending")?null:e.actions.slice().reverse().find(n=>n.stepId===`${t.workflow}.archive.execute`&&n.status==="failed")??null}var _y={id:"comet-classic-archive-repair-command",version:"1",async validate({run:e,name:t,input:n,context:r}){let i=n,s=Ty(e);return t!=="repair-archive"||!s||!r?.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 SI(r.projectRoot,e,s),{accepted:!0,allowFailed:!0})}},al={id:"comet-classic-revision-command",version:"1",validate({run:e,name:t,input:n}){let r=e.state,i=t==="revise-design"?"design":t==="revise-plan"?"build":null,s=n,o=[...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"],l=["verify","archive"].includes(r.phase)&&Bs(e);return{accepted:r.workflow==="full"&&(r.phase===i||t==="revise-design"&&r.phase==="build"||l)&&!r.archived&&s?.expectedRevision===e.revision&&Object.keys(s).length===2&&s.fromPhase===r.phase&&o.length===1&&(l||c.includes(o[0].stepId)||t==="revise-design"&&r.phase==="build"&&["full.build.plan","full.build.plan.evidence","full.build.plan-ready","full.build.execute","full.build.check","full.build.check.evidence"].includes(o[0].stepId)),reason:"Classic revision is stale or does not match the pending Design or Build work"}}};function Bs(e){let t=e.state;if(t.archived||!["verify","archive"].includes(t.phase)||!["running","waiting"].includes(e.status)||e.actions.some(r=>["running","unknown"].includes(r.status)||r.stepId.endsWith(".archive.execute")&&(!["pending","cancelled"].includes(r.status)||r.attempt!==1||!!r.claim||r.receipts.length>0)))return!1;let n=[...e.actions.filter(r=>r.status==="pending"),...e.waits.filter(r=>r.status==="pending"),...(e.evidenceWaits??[]).filter(r=>r.status==="pending")];return n.length===1&&["verify.run","verify.report.evidence","verify.check","verify.check.evidence","archive.prepare","archive.confirm","archive.preflight","archive.execute"].some(r=>n[0].stepId===`${t.workflow}.${r}`)}var qf={id:"comet-classic-verification-revision-command",version:"1",validate({run:e,name:t,input:n}){let r=n;return{accepted:t==="reopen-verification"&&Bs(e)&&r?.expectedRevision===e.revision&&Object.keys(r).length===2&&r.fromPhase===e.state.phase,reason:"Classic verification cannot reopen after Archive execution or while work has an unresolved outcome"}}};function UV(e,t=!0,n=!0,r=!0,i=!0,s){let o=Xo(e),c={...ol,async validate(f){if(!s)return ol.validate(f);let a=f.run.workflow.hash===s.workflow.hash?structuredClone(s):Ps(s);return a.workflow.hash=f.run.workflow.hash,a.definitionHashes[JSON.stringify([f.run.workflow.id,f.run.workflow.version])]=f.run.workflow.hash,j(a)!==j(f.run)?{accepted:!1,reason:"Classic continuation no longer matches its authoritative source Run"}:ol.validate({...f,run:s})}},l=n&&t==="full"&&e!=="full"?Xo("full").workflow:null;return{...o,workflow:{...o.workflow,steps:{...o.workflow.steps,...i?{"classic.resume-work":{type:"call_tool",ref:"classic-work-continuation",validator:{id:xy.id,version:xy.version}}}:{},...Object.fromEntries(Object.entries(l?.steps??{}).filter(([f])=>f.startsWith("full.open")))},transitions:[...o.workflow.transitions??[],...l?.transitions?.filter(f=>f.from.startsWith("full.open"))??[],{from:"full.design.evidence",to:"full.build.plan"},...i?Object.entries(o.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:ol.id,version:ol.version}}}:{},...r?{"continue-build":{stepId:`${t==="full"?"full":e}.build.execute`,validator:{id:Iy.id,version:Iy.version}}}:{},...n?{"repair-archive":{stepId:`${t==="full"?"full":e}.open`,validator:{id:_y.id,version:_y.version}}}:{},...t?{"reopen-verification":{stepId:`${t==="full"?"full":e}.verify.run`,validator:{id:qf.id,version:qf.version}}}:{},"revise-design":{stepId:"full.design.handoff",validator:{id:al.id,version:al.version}},"revise-plan":{stepId:"full.build.plan",validator:{id:al.id,version:al.version}}}},commandValidators:[...i?[c]:[],...r?[Iy]:[],...n?[_y]:[],al,...t?[{...qf,validate:f=>f.run.state.workflow!==(t==="full"?"full":e)?{accepted:!1,reason:"Classic verification command does not match the active workflow profile"}:qf.validate(f)}]:[]],executors:[...o.executors,...i?[s_]:[]],validators:[...o.validators,...i?[xy]:[]],transitionHandler:{...o.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(u=>u.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 o.transitionHandler.apply(f)}}}}function o_(e,t,n={}){let r={...Xo(e),commandValidators:[]};if(!t||t.workflow.hash===j(er(r.workflow)))return r;let i=t.state.workflow,s=UV(e,i==="full"&&e!=="full"?"full":!0);if(t.workflow.hash===j(er(s.workflow)))return s;let o=i_(s,i);if(t.workflow.hash===j(er(o.workflow)))return o;if(t.workflow.version!=="1")throw new Error("Classic 当前 Run 的 definition hash 不匹配,请保留原定义与业务记录。");return t.commands?.some(c=>c.name==="repair-delivery")?o:t.commands?.length||i!==e?s:r}gn();kt();var KV="执行当前检查 Action;Runtime 会绑定原命令、输入快照和收据,并校验后续证据。默认单次真实执行;--local 不是执行位置开关,而是允许确定性检查复用。任务要求每阶段真实执行、命令有副作用或读取外部状态时,禁止添加 --local;只有任务允许且完整输入和执行条件确定时才显式选择复用。使用 --json 时解析完整 stdout,stderr 单独保留,不合并后截断解析。",zV="交付修复检查已固定原 Verify 命令。按 data.continuation.commandArgs 执行 state next --continue,使用当前 Run 的原 Action、命令和收据继续检查;不使用 check run 或 check rerun 重新登记检查,不重放 Archive。检查成功后展示新交付范围,结束当前回复并等待用户针对本范围的实际回答。使用 --json 时解析完整 stdout,stderr 单独保留。",Ny="提交本次交付修复的 Agent 平台检查报告,保留原 Run、归档和批准的路径,不运行受管命令或重放 Archive。随后展示交付范围并取得当前提案的明确批准。";function $y(e){if(e.status==="completed")return{kind:"done"};let t=e.actions.find(o=>o.status==="running"||o.status==="unknown"),n=e.actions.find(o=>o.status==="pending"),r=t??n;if(r){let o=e.state?.workflow,c=(o==="hotfix"||o==="tweak")&&e.workflow.id===`comet-classic-${o}`&&r.type==="invoke_skill"&&r.stepId===`${o}.build.execute`&&r.ref==="comet-build"?`comet-${o}`:r.ref;return{kind:t?"reconcile":"action",stepId:r.stepId,actionId:r.id,attempt:r.attempt,inputHash:r.inputHash,...c?{ref:c}:{},...c==="classic-check"?{instruction:r.stepId.endsWith(".delivery.check")?e.workflow.version==="2"?Ny:zV:KV}:{}}}let i=e.evidenceWaits?.find(o=>o.status==="pending");if(i)return{kind:"evidence",stepId:i.stepId,evidenceId:i.id,evidenceKind:i.kind};let s=e.waits.find(o=>o.status==="pending");return s?{kind:"decision",stepId:s.stepId,waitId:s.id,proposalHash:s.proposalHash,choices:s.choices,instruction:s.stepId.endsWith(".design.confirm")||s.stepId.endsWith(".delivery.confirm")?"核对当前提案与已有批准、委托授权的对象、范围和条件。授权仍覆盖时记录依据并继续;超出授权、发生实质变化或用户明确要求逐阶段确认时,展示待决定内容并等待答复。不得把 Agent 自行判断写成用户确认。"+(s.stepId.endsWith(".delivery.confirm")?"本次重检完成后核对当前交付范围与原授权;用户明确要求审阅本次范围后确认时,先展示并结束当前回复,等待实际答复。":""):"核对当前提案是否已有有效批准或委托授权;授权覆盖时记录依据,否则展示选项并等待用户决定。"}:null}async function Us(e,t,n={}){await Kn(e,t);let r=(await ss(t,e)).directory,i=n.owner??await pr(e,"classic",t,{readOnly:n.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 s=i.application.slice(8),o=Wi(e,n),c=await o.read(i.runId),l=o_(s,c);if(c){let y=$w(c,l.workflow);y!==c&&(await xs({...l,workflows:[l.workflow],transitionHandlers:[l.transitionHandler],store:{read:async()=>y,compareAndSwap:async()=>!1}}).inspect(i.runId),c=y)}let f=!0,a=xs({store:{...o,async read(y){if(f&&y===i.runId)return f=!1,c;let R=await o.read(y);return R&&$w(R,l.workflow)}},workflows:[l.workflow],transitionHandlers:[l.transitionHandler],evidenceValidators:l.evidenceValidators,validators:l.validators,executors:l.executors,commandValidators:l.commandValidators}),d=await a.inspect(i.runId),p=d.state,u=d.input&&typeof d.input=="object"&&!Array.isArray(d.input)&&typeof d.input.changeDir=="string"?Vs.resolve(e,d.input.changeDir):null,m=u?Vs.join(Vs.dirname(u),"archive"):null,h=Gc(d,s),g=h?"full":s,w=d.actions.some(y=>y.stepId===`${g}.archive.execute`&&(y.status==="running"||y.status==="unknown")),k=u!==null&&(r===u||(p?.archived===!0||w)&&Vs.dirname(r)===m&&/^\d{4}-\d{2}-\d{2}-/u.test(Vs.basename(r))&&Vs.basename(r).slice(11)===t);if(d.workflow.id!==l.workflow.id||d.workflow.version!==l.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!==s&&!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}}async function Lf(e,t,n={}){let r=Vs.resolve(e),i=n.owner??await pr(r,"classic",t,{readOnly:!0});return i?{projectRoot:r,...await Us(r,t,{...n,owner:i})}:null}gn();var f_=Rt(Pt(),1);uf();import{createHash as Hf,randomUUID as Tee}from"node:crypto";import{promises as YV}from"node:fs";import et from"node:path";var JV=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_PREFIX","GIT_IMPLICIT_WORK_TREE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"]);function GV(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>{let n=t.toUpperCase();return!JV.has(n)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(n)}))}function a_(e){return{...GV(e.environment),...e.authentication?{}:{GIT_CONFIG_GLOBAL:process.platform==="win32"?"NUL":"/dev/null",GIT_CONFIG_NOSYSTEM:"1"},GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",SSH_ASKPASS_REQUIRE:"never",GIT_NO_REPLACE_OBJECTS:"1",GH_PROMPT_DISABLED:"1"}}Sn();ve();rn();Qe();mi();kt();var c_=["implementing","task-review","checkoff","done","blocked"];function Mi(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic progress requires a JSON object");return e}function Bf(e,t){let n=Object.keys(e).filter(r=>!t.includes(r));if(n.length)throw new Error(`Unknown Classic progress field(s): ${n.join(", ")}; allowed fields: ${t.join(", ")}`)}function Wn(e,t){if(typeof e!="string"||!e.trim()||e.length>4096||[...e].some(n=>n.charCodeAt(0)<32||n.charCodeAt(0)===127))throw new Error(`Invalid Classic progress ${t}`);return e}function jy(e,t){if(!Array.isArray(e)||e.length>200)throw new Error(`Invalid Classic progress ${t}`);return e.map(n=>Wn(n,t))}function XV(e){let t=Mi(e);if(Bf(t,["schemaVersion","taskIds","revision","stage","sessionId","evidence","unresolved","reviewRounds"]),t.schemaVersion!==1)throw new Error("Unsupported Classic checkpoint schemaVersion");let n=jy(t.taskIds,"taskIds");if(!n.length||new Set(n).size!==n.length||n.some(r=>!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/u.test(r)))throw new Error("Classic checkpoint taskIds must be unique stable IDs");if(!c_.includes(t.stage))throw new Error(`Invalid Classic checkpoint stage '${String(t.stage)}'; stages: ${c_.join("|")}`);if(!Number.isSafeInteger(t.reviewRounds)||t.reviewRounds<0)throw new Error("Invalid Classic checkpoint reviewRounds");return{schemaVersion:1,taskIds:n,...typeof t.revision=="string"?{revision:t.revision}:{},stage:t.stage,sessionId:Wn(t.sessionId,"sessionId"),evidence:jy(t.evidence,"evidence"),unresolved:jy(t.unresolved,"unresolved"),reviewRounds:t.reviewRounds}}async function p_(e,t,n){let r=et.join(t,".comet",n);if(await Ge(e,r,{label:"Classic progress",expected:"file"}))return JSON.parse(await le(e,r,{label:"Classic progress"}))}function QV(e,t){let n=Hf("sha256").update(t).digest("hex");return et.join(lt(e),"classic-delivery",`${n}.json`)}async function ZV(e,t){let n=QV(e,t);if(!await Ge(e,n,{label:"Classic delivery reauthorization",expected:"file"}))return null;let r=Mi(JSON.parse(await le(e,n,{label:"Classic delivery reauthorization"})));if(Bf(r,["schemaVersion","changeIdentity","previousAuthorizationId","authorizationId","action","targetBranch","remote","authorizedRemoteUrl"]),r.schemaVersion!==1||r.changeIdentity!==t)throw new Error("Classic delivery reauthorization identity is invalid");let i=qy({action:r.action,targetBranch:r.targetBranch,...r.remote===void 0?{}:{remote:r.remote}},!0);if(i.action==="archive-only")throw new Error("Classic archive-only delivery cannot be reauthorized");if(i.commit!==void 0||i.prUrl!==void 0)throw new Error("Classic delivery reauthorization cannot change sealed commit or PR evidence");return{schemaVersion:1,changeIdentity:t,previousAuthorizationId:Wn(r.previousAuthorizationId,"previousAuthorizationId"),authorizationId:Wn(r.authorizationId,"authorizationId"),...i,targetBranch:i.targetBranch,...r.authorizedRemoteUrl===void 0?{}:{authorizedRemoteUrl:Wn(r.authorizedRemoteUrl,"authorizedRemoteUrl")}}}async function m_(e,t,n){let r=await p_(e,t,"coordination.json");if(r===void 0)return{checkpoint:null,stale:!1};let i=XV(r),s=new Set(nr(n).map(o=>o.id));return{checkpoint:i,stale:i.taskIds.some(o=>!s.has(o))}}function qy(e,t=!1){let n=Mi(e);if(Bf(n,["action","targetBranch","remote","commit","prUrl",...t?["schemaVersion","changeIdentity","authorizedRemoteUrl","authorizationId"]:[]]),!["local","push","pr","archive-only"].includes(n.action))throw new Error(`Invalid Classic delivery action '${String(n.action)}'; actions: local|push|pr|archive-only`);if(n.action==="archive-only"){if(n.targetBranch!==void 0||n.remote!==void 0||n.commit!==void 0||n.prUrl!==void 0)throw new Error("Classic archive-only delivery cannot claim a Git branch, remote, commit, or PR");return{action:"archive-only"}}let r=Wn(n.targetBranch,"targetBranch");if(r.startsWith("-")||/[~^:?*[\\\s]/u.test(r)||r.includes("..")||r.includes("@{"))throw new Error("Invalid Classic delivery targetBranch");let i={action:n.action,targetBranch:r};if(n.remote!==void 0){let s=Wn(n.remote,"remote");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/u.test(s))throw new Error("Classic delivery remote must be a name, not a URL");i.remote=s}if(n.commit!==void 0){let s=Wn(n.commit,"commit");if(!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/u.test(s))throw new Error("Classic delivery commit must be a full object ID");i.commit=s.toLowerCase()}if(n.prUrl!==void 0){let s=Wn(n.prUrl,"prUrl"),o=new URL(s);if(o.protocol!=="https:"||o.username||o.password)throw new Error("Invalid Classic delivery prUrl");i.prUrl=s}return i}function h_(e){let t=(0,f_.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length)throw new Error("Invalid Classic delivery change state");return Mi(t.toJS())}function eU(e,t,n){return typeof e.run_id=="string"&&e.run_id?`run:${e.run_id}`:g_(e,t,n)}function g_(e,t,n){let r=e.archived===!0||et.basename(et.dirname(t))==="archive"?et.basename(t).replace(/^\d{4}-\d{2}-\d{2}-/u,""):et.basename(t);if(typeof e.created_at!="string"||typeof e.base_ref!="string"&&e.base_ref!==null)throw new Error("Classic delivery requires stable change identity");return`legacy:${Hf("sha256").update(JSON.stringify([r,e.created_at,e.base_ref??et.resolve(n)])).digest("hex")}`}function w_(e,t,n,r){let i=eU(t,n,r);if(e===i)return i;if(typeof e=="string"&&e.startsWith("legacy:")&&e===g_(t,n,r))return e;throw new Error("Classic delivery change identity mismatch")}var tU=rt("classicCurrentState",async(e,t)=>nU(e,t));async function nU(e,t){return h_(await le(e,await ue(t),{label:"Classic delivery state"}))}async function y_(e,t){return tU(e,t)}var Ff=class extends Error{constructor(t,n){super(`Classic delivery git command timed out: ${[t,...n].join(" ")}`)}};function Dy(e,t,n,r){return Mx(t,n,{cwd:e,timeoutMs:5e3,env:a_({authentication:r})}).trim()}function ll(e,t,n,r=!1){try{return Dy(e,t,n,r)}catch{return null}}function rU(e,t,n,r=!1){try{return Dy(e,t,n,r)}catch(i){if(!(i instanceof Ti)||!i.timedOut)return null;try{return Dy(e,t,n,r)}catch(s){if(s instanceof Ti&&s.timedOut)throw new Ff(t,n);return null}}}function cl(e,t){return ll(e,"git",["-C",e,...t])}function Wf(e,t){return rU(e,"git",["-C",e,...t])}function l_(e,t,n=!1){return ll(e,"git",["-C",e,"remote","get-url",...n?["--push"]:[],t],!0)}function iU(e,t){let n=et.relative(e,t).replaceAll("\\","/");return[`:(literal)${n}`,...[".comet-state.lock",".comet-state-transaction.json",...[...fh].map(r=>`.comet/${r}`)].map(r=>`:(exclude,literal)${n}/${r}`)]}function u_(e,t,n,r){let i=et.relative(e,t).replaceAll("\\","/"),s=iU(e,t),o=lo.map(l=>Wf(e,["show",`${n}:${i}/${l}`])).filter(l=>l!==null);if(o.length!==1)return!1;let c=o[0];try{let l=h_(c);return l.archived===!0&&w_(r,l,t,e)===r&&Wf(e,["merge-base","--is-ancestor",n,"HEAD"])!==null&&Wf(e,["diff","--quiet","--no-ext-diff","--no-textconv",n,"--",...s])!==null&&Wf(e,["ls-files","--others","--exclude-standard","--",...s])===""}catch(l){if(l instanceof Ff)throw l;return!1}}async function sU(e,t){let n=et.join(t,".comet","main-specs.json");if(await Ge(e,n,{label:"Classic main spec snapshot",expected:"file"}))return;let r=et.join(et.dirname(et.dirname(et.dirname(t))),"specs"),i={},s=async o=>{await Vn(e,o,{label:"Classic main specs",expected:"directory"});for(let c of await YV.readdir(o,{withFileTypes:!0})){let l=et.join(o,c.name);if(c.isDirectory())await s(l);else if(c.isFile()){let f=await ce(e,et.relative(e,l).replaceAll("\\","/"),Number.MAX_SAFE_INTEGER,{label:"Classic main spec snapshot input"});if(Object.keys(i).length>=1e4)throw new Error("Classic main spec snapshot exceeds its file count limit");i[et.relative(r,l).replaceAll("\\","/")]=f.bytes.toString("base64")}else throw new Error(`Classic main specs contain unsupported entry: ${l}`)}};await Ge(e,r,{label:"Classic main specs",expected:"directory"})&&await s(r),await hi(e,et.dirname(n),"Classic main spec snapshot directory"),await wt(e,n,JSON.stringify({schemaVersion:1,files:i})+`
|
|
277
|
+
`,{label:"Classic main spec snapshot",exclusive:!0})}async function v_(e,t){let r=(await Fi(e,t)).delivery;if(r?.action!=="archive-only")return;if((await y_(e,t)).archived!==!0)throw new Error("Classic document archive must be completed first");await sU(e,t);let s=await b_(e,r.changeIdentity);s?.archiveCompleted||s?.archiveFiles||await uU(e,{schemaVersion:1,changeIdentity:r.changeIdentity,authorizationId:r.authorizationId,archiveCompleted:!0})}function oU(e){return Hf("sha256").update(e).digest("hex")+".json"}async function k_(e,t){let n=oU(t);return[{root:et.dirname(lt(e)),file:et.join(lt(e),"classic-delivery-receipts",n)}]}function aU(e,t){let n=Mi(e);if(Bf(n,["schemaVersion","changeIdentity","authorizationId","invalidated","commit","prUrl","archiveFiles","archiveCompleted"]),n.schemaVersion!==1||n.changeIdentity!==t)throw new Error("Invalid Classic delivery receipt schema or identity");if(n.invalidated!==void 0&&typeof n.invalidated!="boolean")throw new Error("Invalid Classic delivery receipt invalidation");let r=qy({action:"local",targetBranch:"main",...n.commit!==void 0?{commit:n.commit}:{},...n.prUrl!==void 0?{prUrl:n.prUrl}:{}});return{schemaVersion:1,changeIdentity:t,authorizationId:Wn(n.authorizationId,"authorizationId"),...n.invalidated===!0?{invalidated:!0}:{},...r.commit?{commit:r.commit}:{},...r.prUrl?{prUrl:r.prUrl}:{},...n.archiveCompleted===!0?{archiveCompleted:!0}:{},...n.archiveFiles===void 0?{}:{archiveFiles:cU(n.archiveFiles)}}}async function b_(e,t){let n=null;for(let r of await k_(e,t)){if(!await Ge(r.root,r.file,{label:"Classic delivery receipt",expected:"file"}))continue;let i=aU(JSON.parse(await le(r.root,r.file,{label:"Classic delivery receipt"})),t);if(n&&JSON.stringify(n)!==JSON.stringify(i))throw new Error("Conflicting Classic delivery receipts");n=i}return n}function cU(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic document archive receipt");let t=e;if(Object.keys(t).length===0||Object.keys(t).length>1e4||Object.entries(t).some(([n,r])=>n.startsWith("/")||n.includes("\\")||n.split("/").some(i=>!i||i==="."||i==="..")||typeof r!="string"||!/^[a-f0-9]{64}$/u.test(r)))throw new Error("Invalid Classic document archive receipt");return t}function lU(e){return e.authorizationId===void 0?`legacy:${Hf("sha256").update(JSON.stringify(e)).digest("hex")}`:Wn(e.authorizationId,"authorizationId")}async function uU(e,t){let[n]=await k_(e,t.changeIdentity);await hi(e,et.dirname(n.file),"Classic delivery receipt directory"),await wt(e,n.file,JSON.stringify(t,null,2)+`
|
|
278
|
+
`,{label:"Classic delivery receipt"})}function d_(e,t,n){return t===n||cl(e,["merge-base","--is-ancestor",t,n])!==null}function dU(e){let t=/^git@([^:/]+):([^/]+\/[^/]+)$/u.exec(e);try{let n=new URL(t?`ssh://git@${t[1]}/${t[2]}`:e);if(!["https:","ssh:"].includes(n.protocol)||n.password||n.search||n.hash||n.port||n.protocol==="https:"&&n.username)return null;let r=n.pathname.replace(/\.git\/?$/u,"").replace(/\/$/u,"").split("/").filter(Boolean);return r.length!==2||r.some(i=>!/^[a-zA-Z0-9_.-]+$/u.test(i))?null:`${n.hostname}/${r.join("/")}`.toLowerCase()}catch{return null}}function Mf(e,t){try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.port||n.search||n.hash)return null;let r=/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/u.exec(n.pathname);return r&&`${n.hostname}/${r[1]}/${r[2]}`.toLowerCase()===t?`https://${n.hostname}/${r[1]}/${r[2]}/pull/${r[3]}`:null}catch{return null}}async function Fi(e,t,n={}){let r=n.evidence!==!1,i=await p_(e,t,"delivery.json");if(i===void 0)return{delivery:null,verification:{status:"needsAuthorization"}};let s=Mi(i);if(s.schemaVersion!==1)throw new Error("Unsupported Classic delivery schemaVersion");let o=qy(s,!0),c=await y_(e,t),l=w_(s.changeIdentity,c,t,e),f=lU(s),a=await ZV(e,l);if(a&&a.previousAuthorizationId!==f)throw new Error("Classic delivery reauthorization is stale for the sealed authorization");let d=a?{action:a.action,targetBranch:a.targetBranch,...a.remote===void 0?{}:{remote:a.remote}}:o,p=a?.authorizationId??f,u=await b_(e,l),m=u?.authorizationId===p?u:null;if(m?.invalidated)return{delivery:null,verification:{status:"needsAuthorization",invalidated:!0}};for(let z of["commit","prUrl"]){if(z==="commit"&&m?.[z]&&d[z]&&m[z]!==d[z])throw new Error("Classic delivery receipt conflicts with authorization evidence");m?.[z]&&(d[z]=m[z])}let h=s.authorizedRemoteUrl===void 0?void 0:Wn(s.authorizedRemoteUrl,"authorizedRemoteUrl"),g=a?.authorizedRemoteUrl??h,w={...d,schemaVersion:1,changeIdentity:l,authorizationId:p,...g?{authorizedRemoteUrl:g}:{}};if(d.action==="archive-only"){let z=c.archived===!0&&!!(m?.archiveCompleted||m?.archiveFiles);return{delivery:w,verification:{status:z?"complete":"needsVerification",archiveVerified:z}}}if(!r)return{delivery:w,verification:{status:m?.commit||m?.prUrl?"complete":"needsVerification",currentBranch:null,commitExists:!1,archiveCommitted:!1,observedCommit:null,observedPrUrl:null,remoteVerified:!1,prVerified:!1,remoteStatus:"notChecked",prStatus:"notChecked"}};let k=cl(e,["symbolic-ref","--quiet","--short","HEAD"]),y=et.relative(e,t).replaceAll("\\","/"),R=null;!d.commit&&c.archived===!0&&(R=cl(e,["log","-20","--format=%H","HEAD","--",...lo.map(ne=>`:(literal)${y}/${ne}`)])?.split(/\r?\n/u).find(ne=>/^[a-f0-9]{40,64}$/u.test(ne)&&u_(e,t,ne,l))??null);let C=d.commit??R,A=!!C&&cl(e,["cat-file","-t",C])==="commit",q=c.archived===!0&&A&&u_(e,t,C,l),D=k===d.targetBranch&&(!c.bound_branch||a!==null||c.bound_branch===k)&&q,K=!1,L=!1,Z=null,Y=n.verifyRemote&&d.action!=="local"?"unavailable":"notChecked",fe="notChecked";if(n.verifyRemote&&D&&d.action!=="local"&&d.remote&&g&&l_(e,d.remote)===g&&l_(e,d.remote,!0)===g){let z=`refs/heads/${d.targetBranch}`,ne=ll(e,"git",["-C",e,"-c","protocol.allow=never","-c","protocol.https.allow=always","-c","protocol.ssh.allow=always","-c","protocol.file.allow=always","ls-remote","--refs",d.remote,z],!0),Le=ne?.split(/\r?\n/u)??[],I=Le.length===1?/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(Le[0]):null,V=I?.[2]===z?I[1]:null;K=!!C&&!!V&&d_(e,C,V),Y=K?"verified":ne===""?"missing":ne===null||!V||cl(e,["cat-file","-t",V])!=="commit"?"unavailable":"missing";let re=dU(g),He=re&&d.prUrl?Mf(d.prUrl,re):null,E=K||ne==="",$=T=>T.headRefName===d.targetBranch&&typeof T.headRefOid=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(T.headRefOid)&&(K?T.headRefOid===V&&["OPEN","MERGED"].includes(T.state):ne===""&&T.state==="MERGED"&&!!C&&d_(e,C,T.headRefOid));if(E&&d.action==="pr"&&(fe="unavailable"),E&&d.action==="pr"&&He&&re){let T=ll(e,"gh",["pr","view",He,"--repo",re,"--json","url,headRefName,headRefOid,state"],!0);try{let F=T?Mi(JSON.parse(T)):null;L=!!F&&typeof F.url=="string"&&Mf(F.url,re)===He&&$(F),fe=L?"verified":F?"missing":"unavailable"}catch{L=!1,fe="unavailable"}}else if(E&&d.action==="pr"&&!d.prUrl&&re){let T=ll(e,"gh",["pr","list","--repo",re,"--head",d.targetBranch,"--state","all","--json","url,headRefName,headRefOid,state","--limit","100"],!0);try{let F=T===null?null:JSON.parse(T);if(!Array.isArray(F)||F.length>=100)throw new Error("Incomplete PR discovery");let U=F.map(Mi).filter(se=>typeof se.url=="string"&&Mf(se.url,re)&&$(se));U.length===1?(Z=Mf(U[0].url,re),L=!0,fe="verified"):fe=U.length===0?"missing":"unavailable"}catch{fe="unavailable"}}}return{delivery:w,verification:{status:D&&(d.action==="local"||(d.action==="push"?K:L))?"complete":"needsVerification",currentBranch:k,commitExists:A,archiveCommitted:q,observedCommit:R,observedPrUrl:Z,remoteVerified:K,prVerified:L,remoteStatus:Y,prStatus:fe}}}kt();var wU=Rt(Pt(),1);Jw();ds();uf();import{AsyncLocalStorage as Ly}from"node:async_hooks";fu();var Qee=new Ly,Zee=new Ly,ete=new Ly;gn();li();Cu();ve();Qt();Ht();Ue();gn();import Mn from"node:path";import pU from"node:path";import{stripVTControlCharacters as fU}from"node:util";function Ks(e,t={}){return{code:"CLASSIC_COMMAND_FAILED",message:fU(e instanceof Error?e.message:String(e)),...t}}Qe();async function Wy(e,t,n){let r=[];if(n.designDoc)try{(await le(e,n.designDoc,{label:"Classic Design Doc"})).trim()||r.push({code:"CLASSIC_DESIGN_EMPTY",field:"design_doc",path:n.designDoc,message:"Design Doc is empty.",remediation:"Write the selected technical design before completing Design."})}catch(s){r.push(Ks(s,{code:"CLASSIC_DESIGN_UNREADABLE",field:"design_doc",path:n.designDoc,remediation:"Restore the recorded Design Doc or register its correct repository-relative reference. Do not clear valid design work."}))}let i="missing";if(n.handoffContext)try{i=await Ir(e,pU.join(t,"proposal.md"),"Classic Design source")?"ready":"missing"}catch{i="stale"}return{design:n.designDoc?r.length?"invalid":"ready":"missing",handoff:i,issues:r}}Ue();Qe();mi();function R_(e){return{phase:e.phase,...e.task?{task:e.task}:{},contextMode:"snapshot",commandArgs:["comet","task",e.projectRoot??".","--task",e.task??"<original-task>","--phase",e.phase,"--session",e.sessionId??"<receiving-session-id>","--context-mode","snapshot",...e.workflow&&e.change?["--workflow",e.workflow,"--change",e.change]:[],"--json"],instruction:[e.language==="zh-CN"?"领取响应已有 contextDelivery 时直接读取 context[].text,不重复检索;上下文丢失时使用 contextActions.restore。其他情况下,首次进入本阶段、交接给新 Agent 或上下文恢复后,由接收方用自己的会话标识和原始请求执行一次本命令,将返回的 context[].text 加入上下文;普通连续执行无需重复获取。将适用偏好和项目约束交给执行者与审查者。Skill 由平台按实际可用能力加载;不兼容或不可用时说明原因。已交付偏好不代表已加载或遵循 Skill;偏好不能代替 Runtime 检查或阶段授权。空结果或获取失败时沿用明确指令继续,不循环重试。":"When the claim response includes contextDelivery, read context[].text without another retrieval; use contextActions.restore after context loss. Otherwise, on first entering this phase, handing off to a new Agent, or restoring context, the receiver runs this command once with its own session ID and the original task, then adds context[].text to context. Do not repeat during uninterrupted work. Pass applicable preferences and project constraints to implementers and reviewers. Load Skills using actual host capabilities; explain unavailable or incompatible choices. Delivery does not prove a Skill was loaded or followed; preferences do not replace Runtime checks or authorization. Continue with explicit instructions after empty or unavailable retrieval; do not loop on retries.",e.instruction].filter(Boolean).join(" ")}}function ul(e,t,n,r){return R_({workflow:"classic",change:r,phase:e.phase,language:e.language??"en",projectRoot:t,sessionId:n,instruction:e.language==="zh-CN"?"原始请求缺失时从当前 proposal、specs 和任务范围恢复目标。子代理接收本阶段、任务范围和此请求后,以自己的会话标识获取上下文。偏好与已确认的执行方式、TDD 或审查配置冲突时说明差异,配置变更仍走现有确认流程;不静默替换固定 Skill 或跳过必需审查。记忆不写入设计交接产物或批准哈希。":"Recover a missing task goal from the current proposal, specs and task scope. Give child Agents this phase, scope and request; each receiver retrieves context with its own session ID. Explain conflicts with confirmed execution, TDD or review configuration; change configuration through its existing approval flow. Do not silently replace fixed Skills or skip required reviews. Keep memory out of design handoff artifacts and approval hashes."})}async function C_(e,t,n,r=!1,i,s={}){let o=await Nt(e),c=i===void 0?await $t(t,{migrate:!1}):{classic:n,run:i??null},l=Mn.join(t,"tasks.md"),f=await Ge(e,l,{label:"Classic task authority",expected:"file"}),a=f?await le(e,l,{label:"Classic recovery task authority"}):"",d;try{d=nr(a)}catch{d=[]}let p=d.find(q=>!q.completed)??null,m=!!(n.plan&&await Ge(e,n.plan,{label:"Classic plan",expected:"file"}))?await le(e,n.plan,{label:"Classic recovery plan mapping"}):"",h=Jx(m,d),g=n.workflow==="full"?await Ds(e,n.plan):null,w=br(n),k=w.missingFields.length>0||w.invalidFields.length>0,y=await m_(e,t,a),R=n.phase==="archive"?await Fi(e,t):null,C={kind:"continue-phase",reason:"Continue the current phase using confirmed artifacts."},A=n.phase==="design"?await Wy(e,t,n):null;if(A)C={kind:A.design==="invalid"?"repair-design":A.design==="missing"?"design":"complete-design",reason:A.design==="invalid"?"Repair only the reported Design Doc metadata or reference; preserve existing confirmed work.":A.design==="missing"?"Continue the existing design and obtain explicit confirmation before registering it.":`Retain the registered Design Doc. Handoff is ${A.handoff}; after confirming recorded user authorization, complete only the remaining Design steps.`,...A.design==="ready"?{cwd:e,argv:["comet","state","complete-design",Mn.basename(t),"--design-doc",n.designDoc,"--json"]}:{}};else if(n.phase==="build"){if(n.workflow==="full"&&!n.isolation?C={kind:"workspace",reason:"Resume /comet-open to restore the missing isolation decision without regenerating valid artifacts."}:n.workflow==="full"&&k?C={kind:"configure",reason:`Complete only the missing or invalid configuration in /comet-build before planning (${[...w.missingFields.length?[`missing: ${w.missingFields.join(", ")}`]:[],...w.invalidFields.length?[`invalid: ${w.invalidFields.map(({field:q,reason:D})=>`${q} (${D})`).join("; ")}`]:[]].join("; ")}); retain confirmed settings and any valid plan.`}:n.workflow==="full"&&g?.status!=="ready"?C={kind:"plan",reason:n.buildMode==="autonomous"?"Restore or create the compact implementation plan in the configured plans directory using confirmed design and task IDs. No external planning Skill is required. Preserve existing work.":"Restore the implementation plan in the configured plans directory, or use the confirmed planning method to create it. Preserve existing work and confirmed execution strategy."}:h.unmapped.length?C={kind:"reconcile-plan",reason:"Inspect implementation and acceptance, then map legacy plan items to task IDs or add genuinely extra tasks. Do not reimplement from checkbox state."}:n.buildPause?C={kind:"paused",reason:"Keep the valid plan and confirmed configuration. Clear the explicit plan-ready pause only after the user asks to continue."}:d.length?p?C={kind:"reconcile-task",taskId:p.id,reason:"Check current code, checks and review evidence. Record accepted completion; otherwise finish only the missing implementation, checks or review."}:C={kind:"check",reason:"All tasks done in the authoritative tasks.md. Revalidate or execute Build checks, then run guard --apply."}:C={kind:"reconcile-task",reason:"Restore the task authority and match existing work before proceeding."},C.kind==="reconcile-task"&&y.checkpoint&&!y.stale){let q=d.find(D=>y.checkpoint.taskIds.includes(D.id??"")&&!D.completed);q&&(C={kind:y.checkpoint.stage==="task-review"?"review":["checkoff","done"].includes(y.checkpoint.stage)?y.checkpoint.unresolved.length?"blocked":"checkoff":y.checkpoint.stage==="blocked"?"blocked":"reconcile-task",taskId:q.id,reason:["checkoff","done"].includes(y.checkpoint.stage)&&y.checkpoint.unresolved.length?"Resolve the recorded unresolved items and reconcile acceptance evidence before recording task completion.":"Reconcile the recorded work package with current code and evidence, then resume its exact missing step; do not restart implementation from checkbox state."})}}else n.phase==="verify"?C={kind:n.verifyResult==="pass"?"transition":"verify",reason:n.verifyResult==="pass"?"Verification passed; continue to Archive.":"Resume missing checks or independent review; retain valid evidence."}:n.phase==="archive"&&(C={kind:n.archived?"delivery":n.archiveConfirmation==="confirmed"?"archive":"confirm-archive",reason:n.archived?"Do not archive again. Inspect recorded authorization and actual delivery before continuing.":"Preserve explicit archive and delivery authorization; do not infer it from branch_status."});return{projectRoot:e,workspace:{projectRoot:e},status:c.run?.status??null,stateVersion:null,iteration:c.run?.iteration??null,changeDir:t,artifactRefs:{change:Mn.relative(e,t).replaceAll("\\","/"),tasks:Mn.relative(e,l).replaceAll("\\","/"),designDoc:n.designDoc??Mn.relative(e,Mn.join(t,"design.md")).replaceAll("\\","/"),plan:n.plan,plansRoot:Mn.relative(e,Mn.join(o.superpowersRoot,"plans")).replaceAll("\\","/"),handoffContext:n.handoffContext},...A?{designReadiness:A,issues:A.issues}:{},layout:{schema:"comet.classic-layout.v1",openSpecRoot:o.openSpecRoot,changesRoot:o.changesDir,archiveRoot:o.archiveDir,specsRoot:o.specsDir,superpowersRoot:o.superpowersRoot},configurationReadiness:w,nextAction:C,continuation:{...C,cwd:e,...n.archived?{}:{contextRequest:ul(n,e,void 0,Mn.basename(t))},skill:n.phase==="build"&&["hotfix","tweak"].includes(n.workflow)?`comet-${n.workflow}`:`comet-${n.phase}`,automatic:n.autoTransition??!0},evidence:{status:"not-revalidated",reason:"entry"},nextTask:p?.text??null,taskState:{authority:l,exists:f,total:d.length,completed:d.filter(q=>q.completed).length,needsIds:d.some(q=>!q.id),next:p,...r?{tasks:d}:{}},planMapping:{status:h.unmapped.length?"reconciliation-required":"ready",unmappedCount:h.unmapped.length,...r?{unmapped:h.unmapped}:{}},coordination:{path:y.checkpoint?(await mo(e,Mn.join(t,".comet","coordination.json"),{readOnly:!0}))?.target??Mn.join(t,".comet","coordination.json"):null,stale:y.stale,...y.checkpoint?{taskIds:y.checkpoint.taskIds,stage:y.checkpoint.stage,sessionId:y.checkpoint.sessionId,reviewRounds:y.checkpoint.reviewRounds,unresolved:y.checkpoint.unresolved,...r?{checkpoint:y.checkpoint}:{}}:{}},delivery:R,requiredFiles:[l,...n.plan?[Mn.resolve(e,n.plan)]:[]]}}import S_ from"node:path";async function E_(e,t){let n=t.actions.find(o=>["running","unknown"].includes(o.status));if(!n)return null;if(Yc(n))return{status:"outcome-rejected",blocked:!0,action:{actionId:n.id,stepId:n.stepId,status:n.status,attempt:n.attempt,inputHash:n.inputHash},claim:n.claim,rejection:n.rejectedOutcomes?.at(-1),instructions:["配置提案已回传但未通过校验。修正 JSON 后重提,沿用原 claim 并保留拒绝历史。","恢复后须展示新提案并重新取得用户批准;不得使用 --confirmed,或声明原尝试未执行。"],commandArgs:["comet","state","propose-build",String(t.input.change),"--file","<configuration-json>","--json"],cwd:S_.resolve(e),inspectRequest:{operation:"inspect",runId:t.runId}};let r={actionId:n.id,attempt:n.attempt,inputHash:n.inputHash},i={runId:t.runId,expectedRevision:t.revision},s=n.type==="invoke_skill"&&n.status==="unknown"&&n.stepId===t.state.workflow+".build.execute"&&n.claim;return{status:"outcome-unknown",blocked:!0,action:{...r,stepId:n.stepId,status:n.status,ref:n.ref,retry:n.retry},claim:n.claim??null,instructions:["通过 Agent 平台核对或等待原任务,沿用原领取提交实际结果;等待超时不能另派任务,也不能把未知结果记成通过。","平台负责执行的超时、取消和进程清理;Comet 仅保留业务任务和批准。"],inspectRequest:{operation:"inspect",runId:t.runId},...n.status==="running"?{markUnknownRequest:{operation:"mark-unknown",...i,actionId:n.id,attempt:n.attempt,reason:"平台无法取回原任务结果,正在核对实际工作"}}:{},...s?{interruptedOutcomeRequestTemplate:{operation:"record-outcome",...i,outcome:{...r,claimToken:"<原领取令牌>",outcomeId:"<本次结果的唯一标识>",status:"failed",output:{summary:"<填写平台任务状态、部分产物和外部副作用的实际核对结果>"}},context:{projectRoot:S_.resolve(e)}}}:{},retryRequestTemplate:{operation:"retry",...i,actionId:n.id,attempt:n.attempt,reconciliation:{resolution:"not-executed",evidence:{summary:"<只有证实原任务从未执行时才能填写>"}}}}}async function Vf(e,t,n={}){let r=t.state,i=t.runId,s=t.input,o=t.revision,c=[],l=(d,p)=>{let u=`revise-${d}`;c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:p,remediation:`Run comet state ${u} ${i} --expected-revision ${o}, then ${d==="design"?"propose-design and approve the new proposal":"submit-plan and follow its next action"}`,commandArgs:["comet","state",u,i,"--expected-revision",String(o)]})};if(r.workflow!=="full"&&!r.archived&&["build","verify","archive"].includes(r.phase)&&!t.waits.some(d=>d.status==="pending"&&d.stepId===`${r.workflow}.build.escalation-confirm`))try{await nl(e,s.changeDir,t)}catch(d){c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:d instanceof Error?d.message:String(d),remediation:r.phase==="build"?"Propose the revised scope and obtain a fresh explicit decision.":"Return to Build with the preserved implementation, then confirm the revised preset scope.",commandArgs:r.phase==="build"?["comet","state","propose-escalation",i,"--reason","<scope-change>"]:["comet","state","continue-build",i,"--expected-revision",String(o)]})}if(r.workflow==="full"&&r.phase==="design"&&n.submittedDesign!==t&&!t.actions.some(d=>d.stepId==="full.design.handoff"&&d.status==="pending")){let d=t.outputs["full.design.handoff"]?.value,p=d?.requirementsEvidence??t.outputs["full.open.evidence"]?.value;if(p)try{let u=await Fs(e,s.changeDir,{designRequirements:!!d?.requirementsEvidence});p.ref!==u.ref&&l("design","Classic Design requirements changed after the proposal")}catch(u){l("design",u instanceof Error?u.message:String(u))}}let f=!1;if(r.workflow==="full"&&["build","verify","archive"].includes(r.phase)&&!r.archived&&!t.actions.some(d=>d.stepId==="full.design.handoff"&&d.status==="pending"))try{await Pf(e,s.changeDir,t),await If(e,t)}catch(d){f=!0,l("design",d instanceof Error?d.message:String(d))}if(!f&&r.workflow==="full"&&["build","verify","archive"].includes(r.phase)&&!r.archived&&r.plan&&!t.actions.some(d=>d.stepId==="full.build.plan"&&d.status==="pending")){let p=t.outputs["full.build.plan"]?.value?.planEvidence??t.evidenceWaits?.slice().reverse().find(u=>u.stepId==="full.build.plan.evidence"&&u.status==="resolved")?.receipt;if(p)try{let u=await _f(e,r.plan,s.changeDir);p.ref!==u.ref&&l("plan","Classic Build plan or task requirements changed after accepted evidence")}catch(u){l("plan",u instanceof Error?u.message:String(u))}}let a=d=>{if(!Bs(t)){c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:d,remediation:"Reconcile the unresolved work before replacing accepted Verify evidence",commandArgs:["comet","state","next",i]});return}c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:d,remediation:`Run comet state reopen-verification ${i} --expected-revision ${o}, then verify the current inputs and obtain a new Archive approval`,commandArgs:["comet","state","reopen-verification",i,"--expected-revision",String(o)]})};if(r.phase==="verify"&&r.verificationReport){let d=`${r.workflow}.verify.run`,p=t.actions.slice().reverse().find(h=>h.stepId===d),u=p?t.actionContexts[p.id]?.sequence:void 0,m=t.evidenceWaits?.slice().reverse().find(h=>h.stepId===`${r.workflow}.verify.report.evidence`&&h.status==="resolved"&&u!==void 0&&h.results[d]?.sequence===u)?.receipt;if(m)try{let h=await tl(e,r.verificationReport,r.language);if(m.ref!==h.ref)throw new Error("Classic Verify report changed within the accepted verification round")}catch(h){a(h instanceof Error?h.message:String(h))}}return c}function A_(e,t=!1){return t?{...e,id:e.runId}:{id:e.runId,runId:e.runId,revision:e.revision,status:e.status,actions:e.actions.filter(n=>["pending","running","unknown"].includes(n.status)).map(({id:n,stepId:r,type:i,ref:s,status:o,attempt:c,inputHash:l,claim:f,requiredCapabilities:a})=>({id:n,stepId:r,type:i,...s?{ref:s}:{},status:o,attempt:c,inputHash:l,requiredCapabilities:a,...f?{claim:f}:{}})),evidenceWaits:(e.evidenceWaits??[]).filter(n=>n.status==="pending").map(({id:n,stepId:r,kind:i,status:s})=>({id:n,stepId:r,kind:i,status:s})),waits:e.waits.filter(n=>n.status==="pending").map(({id:n,stepId:r,status:i,proposal:s,proposalHash:o,choices:c})=>({id:n,stepId:r,status:i,proposal:s,proposalHash:o,choices:c}))}}function Qo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function mU(e,t){if(!/^comet-classic-(full|hotfix|tweak)$/u.test(e.workflow.id))return{input:t.input};if(t.type==="call_tool"&&["classic-check","classic-open-revalidate","classic-archive-preflight","classic-archive"].includes(t.ref??""))return{};let r=t.stepId.slice(t.stepId.indexOf(".")+1),i=["open","design.handoff","design.document","build.configure","build.plan","build.execute","verify.run","archive.prepare","archive.deliver"],s=Qo(t.input),o=ir(e,t)?.outputs??(s?Qo(s.outputs):null);if(t.type!=="invoke_skill"||!i.includes(r)||!["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"].includes(t.ref??"")||!s||!o||!Object.hasOwn(s,"input")||Object.keys(s).some(m=>!["input","outputs","activation"].includes(m)))return{input:t.input};let c=t.stepId.split(".")[0],l={},f=m=>{let h=Qo(m);return h?Object.fromEntries(Object.entries(h).filter(([g])=>["scope","argv","cwd","exitCode","receiptRef","contentHash","inputBefore","inputAfter","tier","changedDuringExecution"].includes(g))):m},a=m=>{let h=`${c}.${m}`;o[h]!==void 0&&(l[h]=f(o[h]))};if(r==="verify.run"&&a("build.check"),r==="archive.prepare"&&a("verify.check"),r==="archive.deliver"){for(let m of["archive.preflight","archive.execute"]){let h=`${c}.${m}`;o[h]!==void 0&&(l[h]=o[h])}a("delivery.check")}let d=e.actionContexts[t.id]?.results??{},p=r.startsWith("build.")?e.actions.filter(m=>{let h=d[m.stepId],g=Qo(m.outcome?.output);return h?.sequence===e.actionContexts[m.id]?.sequence&&(m.status==="failed"||g?.event==="verify-fail")}).sort((m,h)=>e.actionContexts[h.id].sequence-e.actionContexts[m.id].sequence)[0]:void 0;p?.outcome&&(l[p.stepId]=p.type==="call_tool"?f(p.outcome.output):p.outcome.output);let u=r.startsWith("build.")?(e.evidenceWaits??[]).find(m=>m.status==="invalidated"&&d[m.stepId]?.sequence===m.sequence):void 0;return{inputSummary:{usage:"host-context-only",scope:s.input,...s.activation===void 0?{}:{activation:s.activation},configurationRef:"data.configuration",artifactRefsRef:"data.artifactRefs",taskStateRef:"data.taskState",approvalsRef:"data.continuation.current.approvals",...Object.keys(l).length?{outputs:l}:{},...u?.invalidation?{invalidatedEvidence:u.invalidation}:{}}}}function hU(e,t,n,r={}){let i=$y(e),s=e.state,o=A_(e),c={runId:e.runId,expectedRevision:e.revision},l=["comet","runtime","dispatch","--application",e.workflow.id.replace(/^comet-classic-/u,"classic-"),"--project-root",t,"--request","<request-json-file>","--json"],f=e.waits.filter(y=>y.status==="resolved"&&o.actions.some(R=>{let C=e.actions.find(A=>A.id===R.id);return e.actionContexts[R.id]?.results[y.stepId]?.sequence===y.sequence||ir(e,C)?.approvalWaitIds.includes(y.id)})),a={actions:o.actions.map(y=>({...y,...y.type==="invoke_skill"?{contextRequest:ul(s,t,y.claim?.sessionId,e.runId)}:{},...mU(e,e.actions.find(R=>R.id===y.id))})),waits:o.waits.map(y=>({...y,request:{operation:"resolve-wait",...c,waitId:y.id,proposalHash:y.proposalHash,choice:"<user-choice>",decisionId:"<decision-id>"}})),evidenceWaits:(o.evidenceWaits??[]).map(y=>({...y,request:{operation:"record-evidence",...c,evidenceId:y.id,kind:y.kind,ref:"<actual-evidence-ref>",contentHash:"<actual-evidence-sha256>",submissionId:"<submission-id>"}})),approvals:f.map(({id:y,stepId:R,proposal:C,proposalHash:A,choices:q,decision:D})=>({id:y,stepId:R,proposal:C,proposalHash:A,choices:q,decision:D}))},d={...i,schema:"comet.classic.continuation.v1",cwd:t,run:{id:e.runId,revision:e.revision,status:e.status},automatic:s.autoTransition??!0,...!["completed","cancelled"].includes(e.status)&&!s.archived?{contextRequest:ul(s,t,void 0,e.runId)}:{},dispatch:{commandArgs:l},...o.actions.length?{inspection:{commandArgs:["comet","state","next",n,"--details","--json"],actionInputPath:"data.run.actions[matching id].input",instruction:"仅确需未给出的原始输入时读取。inputSummary 仅供宿主理解当前工作,不能替代原 Action input 提交或计算 inputHash;inputHash 始终绑定原始完整输入。"}}:{}};function p(y){return{...d,...y,current:a}}let u=(y,...R)=>["comet","state",y,n,...R,"--json"];if(Oy(e))return p({mode:"execute",commandArgs:u("continue-build","--expected-revision",String(e.revision)),requiredInputs:[],instruction:"原 Builder 已回报失败并结束。保留部分实现、已完成任务和配置,继续原 Run;只完成缺失工作,不重放已经完成的副作用。"});if(Py(e))return p({mode:"execute",commandArgs:u("continue-work","--expected-revision",String(e.revision)),requiredInputs:[],instruction:"原 Skill 已回报真实失败。保留原执行、已确认阶段和部分产物,在同一 Run 创建后续工作,只补缺失步骤,不重放已完成副作用。"});if(Ty(e))return p({mode:"execute",commandArgs:u("repair-archive","--expected-revision",String(e.revision)),requiredInputs:[],instruction:"归档进程已失败。此命令先核对原输入和规格均未变化、没有归档目录,再重开 Open 修正输入;保留原失败记录并重新确认需求、验收和交付。核对失败时保留现场并恢复原执行。"});if(e.status==="cancelled"&&!$s(e))return p({mode:"reconcile",commandArgs:null,requiredInputs:["original-business-task-result"],instruction:"Run 已取消派发,但原归档或关联子 Run 的业务结果尚未核对。保留原记录并先恢复未完成的业务;普通任务的取消与清理由 Agent 平台处理,不提交进程停止回执。"});if(e.status==="completed"||e.status==="cancelled")return p({mode:"done",commandArgs:null,requiredInputs:[],instruction:e.status==="cancelled"?"Run 已取消,不再安排执行。":"Run 已完成。以本次 done continuation 和已验证交付回执为当前终态;归档 YAML 保留交付前基线,不据其旧状态重新推进。仅在冷恢复或交付事实变化时运行 state delivery --verify --json 复核。"});if(e.status==="failed"&&vf(e))return p({mode:"execute",commandArgs:u("repair-delivery","--expected-revision",String(e.revision),"--checks","<checks-json-file>"),requiredInputs:["保留原实现和原命令;仅移除已声明且可再生成的输出"],instruction:"原交付修复检查已真实失败并停止。修正本机执行条件、核对并移除本次声明的生成物,再在同一 Run 重新检查;原实现变化必须恢复,不重放 Archive,成功后重新取得交付批准。"});if(e.status==="failed")return p({mode:"reconcile",commandArgs:null,requiredInputs:[],instruction:e.reason??"Run 已失败;没有可自动执行的后继。"});let m=i&&"actionId"in i?e.actions.find(y=>y.id===i.actionId):void 0;if(m&&Yc(m))return p({mode:"reconcile",commandArgs:u("propose-build","--file","<configuration-json>"),requiredInputs:["修正后的 Build 配置 JSON 文件"],instruction:"Build 配置提案已被拒绝。修正配置后重提;沿用原 claim 补交结果并保留拒绝记录,随后仍须用户批准新提案。不要释放领取或重放执行任务。"});if(m?.status==="running")return p({mode:"wait",waitReason:"executor",commandArgs:m.stepId===`${s.workflow}.archive.execute`?u("check","archive","--recover"):u("check",s.phase,"--recover"),requiredInputs:[],instruction:m.stepId===`${s.workflow}.archive.execute`?"等待原归档执行器返回结果,不得重放。仅确认原执行器已停止且回报丢失后,读取 state check archive --recover 给出的 markUnknownRequest,通过 runtime dispatch 提交,再运行 comet archive "+n+" --recover。":"等待原领取方返回本次执行结果;也可运行只读恢复检查核对原领取和产物。确认原执行已停止之前,不得标记 unknown 或重新派发。"});if(m?.status==="unknown")return p({mode:"reconcile",commandArgs:m.stepId===`${s.workflow}.archive.execute`?["comet","archive",n,"--recover","--json"]:u("check",s.phase,"--recover"),requiredInputs:m.stepId===`${s.workflow}.archive.execute`?["原归档执行器已经停止,归档目录与原 claim 的检查点及产物完整"]:["原领取方本次尝试的真实结果或确未执行证据"],instruction:m.stepId===`${s.workflow}.archive.execute`?"确认原归档执行器已停止后,通过 archive --recover 核对搬迁目录、原 claim 和归档产物并补记结果;证据不完整时停止,不得重放归档。":"核对原 claim 和实际产物。结果未明前不得重放;仅有原始可信结果时补交 outcome。"});if(r.openApprovalHash&&s.phase==="open")return p({mode:"ask",commandArgs:["comet","guard",n,"open","--apply","--approval-hash",r.openApprovalHash,"--json"],requiredInputs:["当前 Open 产物与范围的明确批准或有效委托授权"],instruction:`核对当前 Open 产物是否处于已有批准或明确委托授权的范围内。授权仍覆盖时记录依据并继续;需要新决定时展示内容并等待答复。不得把 Agent 自行判断写成用户确认。使用当前 contentHash=${r.openApprovalHash} 记录决定;内容变化后重新预检,只确认超出授权的部分。`});if(i?.kind==="decision"){let y=a.waits.find(C=>C.id===i.waitId),R=y.stepId.endsWith(".design.confirm")?"decide-design":y.stepId.endsWith(".build.confirm")?"decide-build":y.stepId.endsWith(".build.escalation-confirm")?"decide-escalation":y.stepId.endsWith(".archive.confirm")?"decide-archive":y.stepId.endsWith(".delivery.confirm")?"decide-delivery-repair":y.stepId.endsWith(".build.plan-ready")?"continue-plan":null;return p({mode:"ask",commandArgs:R?u(R,"--proposal-hash",y.proposalHash,...R==="continue-plan"?[]:["--choice","<user-choice>"]):l,requiredInputs:[`当前 proposalHash 的有效批准或委托授权:${y.choices.join("|")}`],instruction:i.instruction,request:y.request})}if(i?.kind==="evidence"){let y=a.evidenceWaits.find(R=>R.id===i.evidenceId);return["classic-open-artifacts","classic-design-document","classic-build-plan","classic-verification-report","classic-build-check","classic-verify-check"].includes(y.kind)?p({mode:"execute",commandArgs:u("next","--continue"),requiredInputs:[],instruction:"沿原 Run 提交已接受材料和真实检查收据;CLI 装配原请求身份,不重跑已完成检查。"}):p({mode:"execute",commandArgs:l,requiredInputs:["request-json-file","真实 evidence ref、contentHash 和 submissionId"],instruction:"提交当前等待项的真实证据;检查证据必须来自原 Runtime 收据,不重跑已完成的检查。",request:y.request})}if(!m)return p({mode:"reconcile",commandArgs:null,requiredInputs:[],instruction:"当前 Run 没有可执行的 Action 或 Wait;核对 Run 状态,不从 phase 推测下一工作。"});if(m.type==="call_tool")return m.ref==="classic-open-revalidate"?p({mode:"execute",commandArgs:u("next","--continue"),requiredInputs:[],instruction:"由原 Open 执行器重新校验已批准的产物;授权或来源变化仍由 Runtime 拒绝。"}):m.ref==="classic-check"&&m.stepId.endsWith(".delivery.check")?p({mode:"execute",commandArgs:u("next","--continue"),requiredInputs:[],instruction:Ny}):["classic-archive-preflight","classic-archive"].includes(m.ref??"")?p({mode:"execute",commandArgs:["comet","guard",n,"archive","--apply","--json"],requiredInputs:[],instruction:"按当前 Run 已记录的归档决定执行;Runtime 在副作用边界重新校验授权和证据。"}):p({mode:"reconcile",commandArgs:null,requiredInputs:[],instruction:`当前工具 ${m.ref??m.type} 没有内置 CLI 映射;使用该应用固定的执行器契约。`});let h=m.type==="invoke_skill"&&i&&"ref"in i?i.ref:void 0,g=null,w=[],k="完成当前 Skill 的工作后,再提交当前 Action。";if(m.type==="invoke_skill"){if(m.stepId.endsWith(".open"))g=["comet","guard",n,"open","--json"],w=["当前 change 的真实 OpenSpec 需求产物"],k="先完成 Open 需求产物,再预检并取得本次产物的用户批准。";else if(m.stepId.endsWith(".design.handoff"))g=u("propose-design","--proposal","<proposal>"),w=["proposal: 候选方案、取舍、风险和已授权的 Spec Patch"],k="先核对来源并准备真实候选方案;提交后等待当前提案的用户决定。";else if(m.stepId.endsWith(".design.document")){let y=f.find(R=>R.stepId.endsWith(".design.confirm")&&R.decision?.choice==="approved");g=u("complete-design","--design-doc","<design-doc-ref>","--approval-hash",y?.proposalHash??"<approval-hash>"),w=["design-doc-ref: 按已批准方案完成的真实 Design Doc",...y?[]:["approval-hash: 当前方案的已批准哈希"]],k="先按当前批准方案保存 Design Doc;Runtime 会重新校验批准和来源。"}else if(m.stepId.endsWith(".build.configure"))g=u("propose-build","--file","<configuration-json>"),w=["configuration-json: 已讨论的 build_mode、tdd_mode、review_mode、subagent_dispatch 与必要的 direct_override"],k="只补缺失或改变的配置决定;用户已明确选择当前完整配置时加 --confirmed 一次提交提案与批准,否则提交后等待当前 Wait 的决定。已有有效批准不重复提问。";else if(m.stepId.endsWith(".build.plan"))g=u("submit-plan","--plan","<plan-ref>"),w=["plan-ref: 引用当前 Design Doc 和 task IDs 的真实计划"],k="先完成当前计划;仅用户明确要求计划完成后暂停时添加 --pause。";else if(m.stepId.endsWith(".build.execute"))g=u("complete-build","--checks","<checks-json-file>"),w=["当前计划任务的真实实现、必要审查和 tasks.md 完成记录"],k="完成实现、任务记录和必要审查,在平台执行检查,将实际 checks 报告保存到 JSON 后提交。空检查列表必须填写 checksReason。只补尚未完成的任务记录;不得重复 task-complete 已完成任务。";else if(m.stepId.endsWith(".verify.run"))g=["comet","guard",n,"verify","--report","<report-ref>","--apply","--checks","<checks-json-file>","--json"],w=["report-ref: 当前真实验收报告","checks-json-file: 平台执行的 checks 报告;未执行时说明原因"],k="在平台执行必要检查,保存实际报告与检查结果。Guard 提交当前验收,不重复执行命令。";else if(m.stepId.endsWith(".archive.prepare"))g=u("propose-archive","--summary","<delivery-summary>"),w=["delivery-summary: 当前目标、归档影响与交付摘要;push/pr 还须明确 remote/pr-base 并添加对应参数"],k="核对真实验证结论和交付目标后提案;尚未获得归档、push 或 PR 授权。";else if(m.stepId.endsWith(".archive.deliver")){let y=m.stepId.split(".")[0],R=e.actionContexts[m.id]?.results[`${y}.archive.preflight`]?.value;g=u("complete-delivery","--commit","<commit-sha>",...R?.deliveryAction==="pr"?["--pr-url","<pr-url>"]:[]),w=["commit-sha: 使用 git rev-parse HEAD 返回的完整提交哈希,不使用短 SHA;允许从 archive.preflight.baseCommit 开始的连续单父提交",...R?.deliveryAction==="pr"?["pr-url: 已获授权且实际创建的 PR"]:[]],k="按当前 Action inputSummary 与 approvals 中已批准的目标完成真实归档提交及必要远端交付。修复与归档可分为多个连续单父提交;整个 baseCommit..HEAD 范围只能包含本次已验证实现和归档产物,不得夹带其他 change、合并提交或改写 Git 历史。仅补交实际结果,不再次归档。"}}return p({mode:h&&d.automatic?"execute":"wait",...h&&!d.automatic?{waitReason:"manual-transition"}:{},commandArgs:null,requiredInputs:w,...h?{skill:h}:{},...g?{completion:{commandArgs:g,requiredInputs:w,instruction:`仅在当前 Skill 的真实工作完成且满足所列前提后提交。${k}`}}:{},instruction:h?`${d.automatic?"加载":"等待用户手动加载"} ${h},仅完成 ${m.stepId} 的当前工作,并沿用本次 Run 与工作区。${d.automatic?"":"用户已明确调用本 Skill 时,执行当前工作;仅停止自动加载后续 Skill。"}${k}`:"此 Action 需要应用声明的宿主执行器;不要把工具或子流程引用当作 Skill。"})}function gU(e){let t=e.state.workflow,n=Qo(e.outputs[`${t}.archive.preflight`]?.value);if(!n)return{delivery:null,verification:{status:"needsAuthorization"}};let r=Qo(e.outputs[`${t}.archive.deliver`]?.value);return{delivery:{action:n.deliveryAction,targetBranch:n.targetBranch,baseCommit:n.baseCommit,...n.remote?{remote:n.remote}:{},...r?.commit?{commit:r.commit}:{},...r?.prUrl?{prUrl:r.prUrl}:{}},verification:{status:r&&e.status==="completed"?n.deliveryAction==="local"?"local-verified":"complete":"needsVerification"}}}async function Zo(e,t,n=!1,r={}){let{run:i,projectRoot:s}=t,o=i.state,c=hU(i,s,e,r),l=$y(i),f={change:e,runtimeFormat:"sdk",checksMode:"agent",phase:o.phase,nextAction:r.openApprovalHash&&c.mode==="ask"&&l?.stepId==="full.open"?{...l,instruction:c.instruction}:l,continuation:c,configuration:o,delivery:o.phase==="archive"?gU(i):null,projectRoot:s,workspace:{projectRoot:s},run:A_(i,n)};try{let{directory:a}=await ss(e,s),d=await Vf(s,i,r),p=!["completed","cancelled"].includes(i.status)&&vo(o.isolation)?st(s):null;(["completed","cancelled"].includes(i.status)?null:_n({isolation:o.isolation,boundBranch:o.boundBranch,currentBranch:p,gitWorkTree:vo(o.isolation)&&o.boundBranch===null&&p===null?on(s):!0}))?.status==="drift"&&d.unshift({code:"CLASSIC_BRANCH_DRIFT",message:o.archived?`归档已完成,待交付工作仍绑定 ${o.boundBranch},请切回原分支继续。`:`当前分支与 ${o.boundBranch} 不一致。切回原分支继续,或确认当前分支接管。`,remediation:o.archived?"保留已执行的归档和原交付范围,不重绑已归档 Run。":"Confirm branch ownership before rebind; settle original executions first.",commandArgs:o.archived?["git","switch",o.boundBranch]:["comet","state","rebind",e,"--json"]});let m=i.actions.some(w=>["running","unknown"].includes(w.status)),h=await C_(s,a,o,n,null,{editReview:!1}),g=i.actions.some(w=>w.status==="unknown")?await E_(s,i):null;return{...f,diagnostics:await Kw(s,i,t.owner).then(w=>d.length?{...w,healthy:!1,issues:[...w.issues,...d]}:w),...d.length?{issues:d,recoveryActions:d.map(w=>({commandArgs:w.commandArgs})),...m?{}:{continuation:{...f.continuation,mode:"reconcile",commandArgs:d[0].commandArgs[0]==="comet"?[...d[0].commandArgs,"--json"].filter((w,k,y)=>w!=="--json"||k===y.indexOf("--json")):d[0].commandArgs,requiredInputs:[],instruction:`${d[0].message};${d[0].remediation}`,completion:void 0}}}:{},changeDir:h.changeDir,layout:h.layout,artifactRefs:h.artifactRefs,configurationReadiness:h.configurationReadiness,taskState:h.taskState,nextTask:h.nextTask,planMapping:h.planMapping,coordination:h.coordination,requiredFiles:h.requiredFiles,...g?{recovery:g}:{}}}catch(a){return{...f,contextWarning:{code:"CLASSIC_CONTEXT_UNAVAILABLE",message:a instanceof Error?a.message:String(a)}}}}function My(e,t,n){let r={open:["open","open.evidence","open.revalidate"],design:["design.document","design.evidence"],build:["build.execute","build.check","build.check.evidence"],verify:["verify.run","verify.report.evidence","verify.check","verify.check.evidence"],archive:["archive.preflight","archive.execute"]},i=s=>["pending","running","unknown"].includes(s.status)&&(r[t]??[]).includes(s.stepId.slice(s.stepId.indexOf(".")+1));return{actionIds:[...new Set([...n?.actionIds??[],...e.actions.filter(i).map(s=>s.id)])],evidenceIds:[...new Set([...n?.evidenceIds??[],...(e.evidenceWaits??[]).filter(i).map(s=>s.id)])]}}function x_(e,t,n){let r="actionId"in e&&typeof e.actionId=="string"&&t.actionIds.includes(e.actionId),i="evidenceId"in e&&typeof e.evidenceId=="string"&&t.evidenceIds.includes(e.evidenceId);return e.mode!=="execute"||!r&&!i?e:{...e,mode:"reconcile",commandArgs:null,completion:void 0,blockers:[{code:"CLASSIC_GUARD_BLOCKED",message:n,...r&&"actionId"in e?{actionId:e.actionId}:{},...i&&"evidenceId"in e?{evidenceId:e.evidenceId}:{}}],instruction:`当前工作仍被阻塞:${n}。先修复或核对所列问题;不要重复原失败命令,也不要重放已领取的工作。`}}Ue();var Ene=rt("readCometCurrentSelection",e=>fo(e)),Ane=rt("classicHookSdkRun",(e,t)=>Us(e,t,{readOnly:!0}));async function I_(e,t){return Ma(e,"classic",t)}Ue();Eu();Eu();gn();Tm();function Fy(e,t){let n=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)?h:{},r=n(e),i=n(r.entry),s=n(r.run??i.run??(typeof r.runId=="string"?r:void 0)),o=n(r.state??i.state??r),c=n(r.preparation??r.workspace??i.workspace),l=n(r.continuation??i.continuation??r.nextAction??i.nextAction),f=typeof c.projectRoot=="string"&&c.projectRoot!=="."?c.projectRoot:typeof l.cwd=="string"?l.cwd:typeof r.projectRoot=="string"?r.projectRoot:typeof i.projectRoot=="string"?i.projectRoot:t??null,a=o.stateVersion??o.state_version,d=o.status??s.status,{current:p,...u}=l,m=p===void 0?l:{...u,currentRef:r.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof o.phase=="string"?o.phase:null,status:typeof d=="string"?d:null,stateVersion:typeof a=="number"?a:null,workspace:{cwd:f},continuation:Object.keys(l).length?{...m,cwd:f}:null,...Object.keys(s).length?{run:{id:typeof s.id=="string"?s.id:typeof s.runId=="string"?s.runId:null,revision:typeof s.revision=="number"?s.revision:null,status:typeof s.status=="string"?s.status:null}}:{}}}Ue();Qm();Qe();async function __(e=process.cwd()){let t=await it(e),n=await Ar(t);await Su(t,n);let r=process.env.COMET_OPENSPEC||"openspec";try{pu(r,[],{cwd:n.openSpecBase})}catch(i){throw new Error(`OpenSpec CLI unavailable: ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}gn();Qe();var $_=Rt(Pt(),1);import{execFileSync as RU}from"node:child_process";import{randomUUID as By}from"node:crypto";import{promises as CU}from"node:fs";import Rr from"node:path";ve();Qa();Ue();Qe();import{execFileSync as P_}from"node:child_process";import{randomUUID as Hy}from"node:crypto";import O_ from"node:path";function vU(e){let t=e.state?.workflow,n=e.waits.slice().reverse().find(i=>i.stepId===`${t}.archive.confirm`&&i.status==="resolved"&&["local","push","pr"].includes(i.decision?.choice??"")),r=n?.proposal?.outputs?.[`${t}.archive.prepare`];if(!n?.decision||!r||typeof r.targetBranch!="string"||!r.targetBranch||n.decision.choice!=="local"&&(typeof r.remote!="string"||!r.remote)||n.decision.choice==="pr"&&(typeof r.prBaseBranch!="string"||!r.prBaseBranch))throw new Error("Classic Archive has no current delivery approval");return{action:n.decision.choice,targetBranch:r.targetBranch,...typeof r.remote=="string"?{remote:r.remote}:{},...typeof r.prBaseBranch=="string"?{prBaseBranch:r.prBaseBranch}:{},...r.deliveryPaths?{deliveryPaths:r.deliveryPaths}:{}}}var dl=class extends Error{};async function ea(e,t){try{let n=e.state;if(!n||!Lx(e,n.workflow)||e.status!=="running"||n?.phase!=="archive"||n.verifyResult!=="pass"||n.archiveConfirmation!=="confirmed"||n.archived)throw new Error("Classic SDK Run is not ready to Archive");let r=vU(e);await nl(t,String(e.input.changeDir),e);let i=e.actions.find(o=>["pending","running"].includes(o.status)&&[`${n.workflow}.archive.preflight`,`${n.workflow}.archive.execute`].includes(o.stepId));if(n.workflow==="full"&&i){let o=Ws(e,i),c=o.outputs["full.build.plan"],l=o.outputs["full.design.document"]?.designDoc??c?.designEvidence?.ref;if(typeof c?.plan!="string"||typeof l!="string")throw new Error("Classic Archive documents are missing");o.recovered&&await Of(t,String(e.input.changeDir),n,e)}let s=st(t);if(!s||s!==n.boundBranch||s!==r.targetBranch)throw new Error("Classic Archive branch differs from the approved bound branch");return await kU(e,t,n),r}catch(n){throw new dl(n instanceof Error?n.message:String(n),{cause:n})}}async function kU(e,t,n,r=2){let i=e.evidenceWaits?.slice().reverse().find(s=>s.stepId===n.workflow+".verify.report.evidence"&&s.status==="resolved")?.receipt;{let s=[...e.actions].reverse().find(c=>c.stepId===n.workflow+".verify.run"),o=s?.outcome?.output;if(!i||i.ref!==n.verificationReport||s?.status!=="succeeded"||o?.event!=="verification-ready"||o.verificationReport!==n.verificationReport)throw new Error("Classic Archive requires the latest accepted Verify report");rf(e)||rl(o);return}}async function bU(e,t,n){let r=O_.resolve(n),i=e.state.workflow;if(t.runId!==e.runId||t.stepId!==i+".archive.preflight"||t.type!=="call_tool"||t.ref!=="classic-archive-preflight")throw new Error("Current Classic SDK Run has no Archive preflight Action");let s=await ea(e,r),o=s.targetBranch,c=s.remote?Yo(r,s.remote):void 0,l=P_("git",["rev-parse","HEAD"],{cwd:r,encoding:"utf8"}).trim();if(st(r)!==o)throw new Error("Classic Archive branch changed during preflight");return{status:"succeeded",output:{deliveryAction:s.action,targetBranch:s.targetBranch,verifiedBranch:o,baseCommit:l,deliveryPaths:await NI(r,e,s.deliveryPaths),...s.remote?{remote:s.remote,remoteIdentity:c}:{},...s.prBaseBranch?{prBaseBranch:s.prBaseBranch}:{}}}}async function T_(e,t){let n=O_.resolve(t.projectRoot),r=await e.inspect(t.runId),i=r.state.workflow,s=r.actions.slice().reverse().find(a=>a.stepId===i+".archive.preflight"&&a.status==="pending");if(!s)throw new Error("Current Classic SDK Run has no pending Archive preflight Action");let o=await bU(r,s,n),c=o.output,l=Hy(),f=Hy();await e.claim({runId:r.runId,actionId:s.id,attempt:s.attempt,inputHash:s.inputHash,executorId:"comet-classic-archive-preflight",claimToken:l,expectedRevision:r.revision,context:{requestId:f,projectRoot:n}});try{if(st(n)!==c.verifiedBranch||P_("git",["rev-parse","HEAD"],{cwd:n,encoding:"utf8"}).trim()!==c.baseCommit)throw new Error("Classic Archive branch or HEAD changed during preflight");return await e.recordOutcome({runId:r.runId,context:{requestId:f,projectRoot:n},outcome:{actionId:s.id,attempt:s.attempt,inputHash:s.inputHash,claimToken:l,outcomeId:Hy(),...o}})}catch(a){let p=(await e.inspect(r.runId)).actions.find(u=>u.id===s.id);throw p?.status==="running"&&p.attempt===s.attempt&&await e.markUnknown({runId:r.runId,actionId:s.id,attempt:s.attempt,reason:a instanceof Error?a.message:String(a)}),a}}kt();nn();function SU(e,t){return/^\d{4}-\d{2}-\d{2}-/u.test(e)&&e.slice(11)===t}async function Uf(e,t){try{return new Set((await CU.readdir(e)).filter(n=>SU(n,t)))}catch(n){if(n.code==="ENOENT")return new Set;throw n}}async function N_(e,t,n,r){if(!t)return;let i=await M(e,t,{label:"Classic Archive document",expected:"file"});if(!i.exists)return;let s=await le(e,i.target,{label:"Classic Archive document"});await wt(e,i.target,Hi(s,n,r),{label:"Classic Archive document"})}async function j_(e,t,n){let r=e.state.workflow,i=e.actions.slice().reverse().find(d=>d.stepId===`${r}.archive.preflight`);if(t.runId!==e.runId||t.stepId!==`${r}.archive.execute`||t.type!=="call_tool"||t.ref!=="classic-archive"||i?.status!=="succeeded")throw new Error("Classic SDK Run has no preflighted Archive Action");let s=await ea(e,n),o=i.outcome?.output;if(o?.deliveryAction!==s.action||o.targetBranch!==s.targetBranch||o.verifiedBranch!==s.targetBranch||s.action==="pr"&&o.prBaseBranch!==s.prBaseBranch||typeof o.baseCommit!="string"||s.remote!==void 0&&(o.remote!==s.remote||o.remoteIdentity!==Yo(n,s.remote))||RU("git",["rev-parse","HEAD"],{cwd:n,encoding:"utf8"}).trim()!==o.baseCommit)throw new Error("Classic Archive preflight no longer matches the approved delivery");let c=e.input;if(typeof c?.change!="string"||typeof c.changeDir!="string")throw new Error("Classic Archive change identity is missing");let l=await En(n),f=await M(n,c.changeDir,{label:"Classic active change",expected:"directory"});if(!f.exists||f.target!==Rr.join(l.changesDir,c.change))throw new Error("Classic Archive active change differs from the SDK Run");await ue(f.target);let a=await Uf(l.archiveDir,c.change);return await __(n),{active:f,runInput:{change:c.change,changeDir:c.changeDir},layout:l,before:a}}async function EU(e,t,n){let r;try{r=await j_(e,t,n)}catch(y){return{status:"failed",output:{archiveStarted:!1,reason:y instanceof Error?y.message:String(y)}}}let{active:i,runInput:s,layout:o,before:c}=r,l;try{await Ku(n,i.target),l=await CI(n,e,t,Rr.relative(n,o.specsDir).replaceAll("\\","/")),await ea(e,n)}catch(y){return{status:"failed",output:{archiveStarted:!1,reason:y instanceof Error?y.message:String(y)}}}let f=await ui(["archive",s.change,"--yes"],n);if(f.exitCode!==0){let y=[f.stderr,f.stdout].filter(Boolean).join(`
|
|
279
|
+
`);if(f.executionStarted===!1)return{status:"failed",output:{archiveStarted:!1,reason:f.stderr??"OpenSpec Archive did not start"}};if(!f.executionCompleted)throw new Error(y||"OpenSpec Archive execution has an unresolved result");let R=await M(n,s.changeDir,{label:"Classic active change",expected:"directory"}),C=[...await Uf(o.archiveDir,s.change)].some(A=>!c.has(A));if(!R.exists&&C)throw new Error(y||"OpenSpec Archive moved the change before returning a failure; recover the original Archive progress");return{status:"failed",output:{archiveStarted:!0,reason:y||`OpenSpec Archive exited with code ${f.exitCode}`}}}let d=[...await Uf(o.archiveDir,s.change)].filter(y=>!c.has(y));if(d.length!==1)throw new Error("OpenSpec Archive did not produce one unambiguous archived change");let p=d[0],u=Rr.join(o.archiveDir,p),m=await M(n,Rr.relative(n,u).replaceAll("\\","/"),{label:"Classic archived change",expected:"directory"}),h=await M(n,s.changeDir,{label:"Classic active change",expected:"directory"});if(!m.exists||h.exists)throw new Error("OpenSpec Archive left the change in an inconsistent location");let g=await os(n,m.target);if(g.length)throw new Error(g.join(`
|
|
280
|
+
`));let w=e.state,k=Rr.relative(n,m.target).replaceAll("\\","/");return await N_(n,ht(w.designDoc,s.changeDir,k),p,"status: final"),await N_(n,ht(w.plan,s.changeDir,k),p,""),{status:"succeeded",artifacts:await ly(n,e,t,k,l),output:{archiveDirectory:k}}}async function D_(e,t){let n=Rr.resolve(t.projectRoot),r=await e.inspect(t.runId),i=r.state.workflow,s=r.actions.slice().reverse().find(l=>l.stepId===i+".archive.execute"&&l.status==="pending");if(!s)throw new Error("Classic SDK Run has no preflighted Archive Action");await j_(r,s,n);let o=By(),c=By();await e.claim({runId:r.runId,actionId:s.id,attempt:s.attempt,inputHash:s.inputHash,executorId:"comet-classic-archive",claimToken:o,expectedRevision:r.revision,context:{requestId:c,projectRoot:n}});try{let l=await e.inspect(r.runId),f=l.actions.find(d=>d.id===s.id),a=await EU(l,f,n);return await e.recordOutcome({runId:r.runId,context:{requestId:c,projectRoot:n},outcome:{actionId:s.id,attempt:s.attempt,inputHash:s.inputHash,claimToken:o,outcomeId:By(),...a}})}catch(l){let a=(await e.inspect(r.runId)).actions.find(d=>d.id===s.id);throw a?.status==="running"&&a.attempt===s.attempt&&await e.markUnknown({runId:r.runId,actionId:s.id,attempt:s.attempt,reason:l instanceof Error?l.message:String(l)}),l}}async function q_(e,t){let n=Rr.resolve(t.projectRoot),r=await e.inspect(t.runId),i=r.state;if(r.actions.some(A=>A.stepId===`${i.workflow}.archive.execute`&&A.status==="running"))throw new Error(`Classic Archive executor may still be running. Wait for its result. Only after confirming the original executor has stopped, use comet state check ${t.runId} archive --recover --json to obtain markUnknownRequest, submit it through runtime dispatch, then retry comet archive ${t.runId} --recover. Do not replay Archive.`);if(i.archived){let A=r.actions.slice().reverse().find(q=>q.ref==="classic-archive"&&q.status==="succeeded"&&q.claim?.executorId==="comet-classic-archive");if(A){let q=(A.outcome?.output).archiveDirectory;return await uy(n,r,A,q),await Di(n,r,A,q),r}}let s=r.actions.filter(A=>A.status==="unknown"),o=s.length===1?s[0]:null;if(i.phase!=="archive"||i.archived||!o||o.stepId!==`${i.workflow}.archive.execute`||o.claim?.executorId!=="comet-classic-archive")throw new Error("Classic SDK Archive has no single moved Action to recover");let c=r.input;if(typeof c?.change!="string"||typeof c.changeDir!="string")throw new Error("Classic SDK Archive change identity is missing");let l=await En(n);if((await M(n,c.changeDir,{label:"Classic active change",expected:"directory"})).exists)throw new Error("Classic SDK Archive still has its active change");let a=await Uf(l.archiveDir,c.change);if(a.size!==1)throw new Error("Classic SDK Archive destination is ambiguous");let d=[...a][0],p=Rr.join(l.archiveDir,d),u=await M(n,Rr.relative(n,p),{label:"Classic archived change",expected:"directory"});if(!u.exists)throw new Error("Classic SDK Archive destination is missing");let m=await le(n,await ue(u.target),{label:"Classic archived state"});if(!Et(m))throw new Error("Classic archived state is not managed by the SDK");let h=(0,$_.parseDocument)(m,{uniqueKeys:!0});if(h.errors.length>0)throw new Error("Classic archived state is invalid");let w=yn(h.toJS().run_checkpoint,r.runId)?.actions.find(A=>A.id===o.id),k=Pi(r).run.actions.find(A=>A.id===o.id);if(!w||w.status!=="unknown"||w.stepId!==o.stepId||w.attempt!==o.attempt||w.inputHash!==o.inputHash||w.claim?.executorId!==o.claim.executorId||w.claim?.token!==k?.claim?.token)throw new Error("Classic archived state does not match the lost Archive Action");let y=await os(n,u.target);if(y.length)throw new Error(y.join(`
|
|
281
|
+
`));let R=Rr.relative(n,u.target).replaceAll("\\","/"),C=await uy(n,r,o,R,t.confirmedProposalHash);return e.recordOutcome({runId:r.runId,context:{requestId:`classic-sdk-archive-recovery:${r.runId}:${o.id}`,projectRoot:n},outcome:{actionId:o.id,attempt:o.attempt,inputHash:o.inputHash,claimToken:o.claim.token,outcomeId:`${o.id}:${o.attempt}:recovered:${r.revision}`,status:"succeeded",artifacts:C,output:{archiveDirectory:R}}})}Qe();Qe();async function Vr(e,t,n,r,i,s,o,c){let l=i!==void 0,f=c??(s?await Zo(e,{run:s,projectRoot:n},!1,!l&&t==="open"&&r?{openApprovalHash:r}:{}):null),a=l&&s?(await Vf(n,s)).find(d=>d.commandArgs[2]==="reopen-verification"):void 0;return!a&&l&&s&&t==="archive"&&Bs(s)&&/check inputs|check environment|report|evidence/iu.test(i??"")&&(a={code:"CLASSIC_EVIDENCE_DRIFT",message:i,remediation:"保留当前修改并重开 Verify;验收通过后重新确认 Archive 交付方式。",commandArgs:["comet","state","reopen-verification",e,"--expected-revision",String(s.revision)]}),{exitCode:l?1:0,data:{...f??{change:e,phase:t,projectRoot:n},...f&&l&&o?{continuation:x_(f.continuation,o,i)}:{},...a&&f?{continuation:{...f.continuation,mode:"execute",commandArgs:[...a.commandArgs,"--json"],requiredInputs:[],skill:void 0,completion:void 0,instruction:a.remediation}}:{},...r===null?{}:{approvalHash:r},checks:{passed:l?0:1,total:1,blocked:l},issues:l?[Ks(i)]:[]},stderr:l?`BLOCKED — ${i}
|
|
282
|
+
`:`ALL CHECKS PASSED — ${t==="open"?"approval required before applying":`phase=${t}`}
|
|
283
|
+
`}}async function W_(e){let{projectRoot:t,change:n,apply:r}=e,i=e.inspected??await Us(t,n),{run:s,state:o,runtime:c,profile:l}=i,f=My(i.run,"archive");if(o.phase!=="archive")return Vr(n,o.phase,t,null,`Classic SDK Archive Guard requires Archive; current phase is ${o.phase}`,s,f);if(o.archived)return Vr(n,"archive",t,null,"Classic SDK change is already archived; finish its pending delivery Action",s,f);if(s.actions.some(m=>m.status==="running"||m.status==="unknown"))return Vr(n,"archive",t,null,s.actions.some(m=>m.status==="unknown")?"Classic SDK has an unknown Action outcome; reconcile the original attempt":"Classic SDK has a running Action; wait for its original executor",s,f);try{r||await ea(s,t)}catch(m){return Vr(n,"archive",t,null,m instanceof Error?m.message:String(m),s,f)}let a=s.actions.some(m=>m.stepId===`${l}.archive.preflight`&&m.status==="pending"),d=s.actions.some(m=>m.stepId===`${l}.archive.execute`&&m.status==="pending");if(!a&&!d)return Vr(n,"archive",t,null,"Classic SDK has no pending Archive Action",s,f);if(!r)return Vr(n,"archive",t,null,void 0,s,f);let p;try{if(a){let m=await T_(c,{runId:s.runId,projectRoot:t});Object.assign(f,My(m,"archive",f))}p=await D_(c,{runId:s.runId,projectRoot:t})}catch(m){if(!(m instanceof dl))throw m;let h=await c.inspect(s.runId);return Vr(n,"archive",t,null,m.message,h,f)}return p.state?.archived===!0?Vr(n,"archive",t,null,void 0,p,f):Vr(n,"archive",t,null,"Classic SDK Archive did not complete",p,f)}ju();import xU from"path";var IU=xU.join(".comet","state-events.jsonl"),_U=Number.MAX_SAFE_INTEGER;async function M_(e,t){let n={schemaVersion:1,timestamp:new Date().toISOString(),...t};return await Nu(e,IU,`${JSON.stringify(n)}
|
|
284
|
+
`,_U,"Classic state event log"),n}kt();var OU="\x1B[32m",TU="\x1B[31m",NU="\x1B[33m",Uy="\x1B[0m";function Fn(e){return`${OU}${e}${Uy}`}function _t(e){return`${TU}${e}${Uy}`}function fl(e){return`${NU}${e}${Uy}`}var mt=class extends Error{constructor(n,r=1){super(n);this.exitCode=r}exitCode},Vy=class{stderr=[];openSpecStdout=[];openSpecStderr=[];stepsOk=0;stepsTotal=0;envelope;captureOpenSpec(t){t.stdout&&this.openSpecStdout.push(t.stdout),t.stderr&&this.openSpecStderr.push(t.stderr)}finishEnvelope(t){this.envelope=Ux({name:t.name,stepsOk:this.stepsOk,stepsTotal:this.stepsTotal,dryRun:t.dryRun,locale:t.locale}),this.stderr.push(this.envelope.summary)}toResult(t=0){let n=this.stderr.length>0?this.stderr.join(`
|
|
285
|
+
`)+`
|
|
286
|
+
`:"",r=this.openSpecStderr.join(""),i=r&&n&&!r.endsWith(`
|
|
287
|
+
`)?`
|
|
288
|
+
`:"";return{exitCode:t,...this.openSpecStdout.length>0?{stdout:this.openSpecStdout.join("")}:{},...r||n?{stderr:`${r}${i}${n}`}:{},...this.envelope===void 0?{}:{envelope:this.envelope}}}};function $U(e){let t=Ya(e);if(t)throw new mt(_t(`FATAL: ${t}`))}function F_(e){return PU("sha256").update(e).digest("hex")}function jU(e){return F_(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function DU(e,t){let n=Cr.relative(e,t);return n!==""&&!Cr.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Cr.sep}`)}function zs(e,t,n,r){if(!r)return r;let i=Cr.resolve(e,r);return DU(t,i)?qe(e,Cr.join(n,Cr.relative(t,i))):r}function qU(e,t,n,r){let i={...r};for(let s of["handoff_context","handoff_markdown"]){let o=i[s];o&&(i[s]=zs(e,t,n,o)??o)}return i}async function LU(e,t){let n=await $t(t);if(!n.classic||!n.run||!n.classic.archived)throw new mt(_t(" [FAIL] Final archived state is incomplete"));let r=await os(e,t);if(r.length)throw new mt(_t(r.join(`
|
|
289
|
+
`)));let i=[["design_doc",n.classic.designDoc],["plan",n.classic.plan],["verification_report",n.classic.verificationReport],["handoff_context",n.classic.handoffContext]],s=await Za(t,n.run.artifactsRef),o=[["artifacts.handoff_context",s.handoff_context],["artifacts.handoff_markdown",s.handoff_markdown]];for(let[c,l]of[...i,...o])if(l&&!await Ge(e,Cr.resolve(e,l),{label:`Classic archived ${c}`,expected:"file"}))throw new mt(_t(` [FAIL] Final archived ${c} does not exist: ${l}`))}async function WU(e,t,n){let r=await Tr(e,t.trajectoryRef);r.some(i=>i.type==="recovery_reconciled"&&i.data.kind==="classic-archive"&&i.data.actionId===n)||await Or(e,t.trajectoryRef,{sequence:r.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:t.runId,data:{kind:"classic-archive",actionId:n}})}async function Kf(e,t,n,r,i,s){if(!await Ge(t,n,{label:"Classic archive annotation target",expected:"file"}))return;if(s){e.stderr.push(fl(` [DRY-RUN] Would annotate: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1;return}let o=await le(t,n,{label:"Classic archive annotation target"}),c=Hi(o,r,i);await wt(t,n,c,{label:"Classic archive annotation target"}),e.stderr.push(Fn(` [OK] Annotated: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1}async function MU(e,t){if(!(await Vn(e,t,{label:"Classic main specs directory",expected:"directory"})).exists)return;let r=!1;for(let i of await gi(e,t)){let o=(await le(e,i,{label:`Classic main spec ${i}`})).split(/\r?\n/u).map((c,l)=>({line:c,number:l+1})).filter(c=>/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements$/u.test(c.line));if(o.length>0){r=!0,process.stderr.write(_t(`FATAL: delta-only section heading leaked into main spec: ${i}`)+`
|
|
290
|
+
`);for(let c of o)process.stderr.write(`${c.number}:${c.line}
|
|
291
|
+
`)}}if(r)throw new mt("")}var Ky=_u(async e=>{if(e.length<1||e.length!==1&&e.length!==2&&e.length!==5||e[1]!==void 0&&!["--dry-run","--recover"].includes(e[1])||e.length===5&&(e[1]!=="--recover"||e[2]!=="--confirmed"||e[3]!=="--proposal-hash"||!/^[a-f0-9]{64}$/u.test(e[4])))return{exitCode:64,stderr:"Usage: comet archive <change-name> [--dry-run|--recover [--confirmed --proposal-hash <sha256>]]"};let t=new Vy,n=e[0],r=e[1]==="--dry-run",i=e[1]==="--recover";try{$U(n);let s=Iu(),c=(await Ay(s,n))?.format==="compat"?null:await Lf(s,n);if(c){if(i){let q=c,D;try{D=await q_(q.runtime,{projectRoot:c.projectRoot,runId:q.run.runId,confirmedProposalHash:e.length===5?e[4]:void 0})}catch(K){if(!(K instanceof Rf))throw K;return{exitCode:73,stderr:K.message,data:{...await Zo(n,{run:q.run,projectRoot:c.projectRoot}),recoveryApproval:K.proposal,continuation:{mode:"ask",kind:"await-user",automatic:!1,requiresUserDecision:!0,requiredInputs:["confirmedProposalHash"],instruction:"向用户展示完整规格变化与原批准的 delta。仅在用户确认这些结果完整实现原契约后,使用当前 proposalHash 恢复;不能自行确认未知规格输出。",commandArgs:["comet","archive",n,"--recover","--confirmed","--proposal-hash",K.proposal.proposalHash,"--json"]}}}}return{exitCode:0,data:{...await Zo(n,{run:D,projectRoot:c.projectRoot}),recoveredAction:q.run.actions.find(K=>K.status==="unknown")?.id,pendingAction:D.actions.find(K=>K.status==="pending")?.id},stderr:`Classic SDK Archive recovered for ${n}; continue its delivery Action
|
|
292
|
+
`}}return W_({projectRoot:c.projectRoot,change:n,apply:!r})}if(i)return{exitCode:64,stderr:"--recover is only available for SDK-owned Classic changes"};let l=await Ar(s),f=await go(n,l.projectRoot),a=f.directory,d=qe(l.projectRoot,a),u=`${new Date().toISOString().slice(0,10)}-${n}`,m=Cr.join(l.archiveDir,u);t.stderr.push(`=== Comet Archive: ${n} ===`);let h=f.stateExists,g=h?null:await wo(n,l.projectRoot),w=h?a:g?.directory;if(!w||!await Ge(l.projectRoot,await ue(w),{label:`Classic change ${n} state`,expected:"file"}))throw new mt(_t(`FATAL: .comet.yaml not found in ${d}/`));g&&(m=g.directory,u=Cr.basename(g.directory));let k=await $t(w);if(!k.classic)throw new mt(_t("FATAL: archive requires Classic state"));let y=k.classic,R=y.designDoc,C=y.plan;if(y.phase!=="archive")throw new mt(_t(`FATAL: phase is '${y.phase}', expected 'archive'`));if(y.verifyResult!=="pass")throw new mt(_t(`FATAL: verify_result is '${y.verifyResult}', expected 'pass'. Run comet-verify first.`));t.stderr.push(Fn(" [OK] Entry state verified")),t.stepsOk+=1,t.stepsTotal+=1;let A=await Vn(l.projectRoot,m,{label:`Classic archive target ${u}`,expected:"directory"});if(h&&A.exists)throw new mt(_t(`FATAL: archive target already exists: ${m}`));if(t.stderr.push(Fn(" [OK] Archive target available")),t.stepsOk+=1,t.stepsTotal+=1,r)t.stderr.push(fl(` [DRY-RUN] Would run OpenSpec archive: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1;else if(!y.archived||k.run?.pending){await hi(l.projectRoot,`${w}/.comet`,"Classic change runtime directory");let q=`classic-archive:${n}`,D=await sn(w,async()=>{let L=await wf(w);if(L.classic.phase!=="archive"||L.classic.verifyResult!=="pass")throw new mt(_t("FATAL: Archive state changed before preparing the pending action."));let Z=await Yu(w,L.run.pendingRef),Y=!!g||Z?.id===q&&Z.type==="checkpoint"&&Z.ref===n;if(L.run.pending&&L.run.pending!==q)throw new mt(_t(`FATAL: another action is pending: ${L.run.pending}`));if(!Y&&!L.classic.archived&&L.classic.archiveConfirmation!=="confirmed")throw new mt(_t(`FATAL: archive_confirmation is '${y.archiveConfirmation??"null"}', expected 'confirmed'. Run final archive confirmation first.`));if(!Y){await vC(s,w,L.run,L.classic),await Ku(l.projectRoot,w);let fe={id:q,stepId:L.run.currentStep,type:"checkpoint",ref:n};await uC(w,L.run.pendingRef,fe);let z=await $t(w);if(!z.classic||!z.run||z.run.runId!==L.run.runId||z.classic.phase!=="archive"||z.classic.verifyResult!=="pass"||z.classic.archiveConfirmation!=="confirmed")throw new mt(_t("FATAL: Archive state changed while preparing the pending action."));await $r(w,{classic:z.classic,run:{...z.run,pending:q,status:"waiting"},unknownKeys:z.unknownKeys})}return Y});if(!g){let L=await ui(["archive",n,"--yes"],l.projectRoot);if(t.captureOpenSpec(L),L.exitCode!==0)throw new mt("",L.exitCode)}let K=await wo(n,l.projectRoot,{preferredArchiveName:u});if(!K&&!g&&(K=await wo(n,l.projectRoot,{skipExactCompatibility:!0})),!K)return t.stderr.push(_t(" [FAIL] OpenSpec archive output not found")),t.stepsTotal+=1,t.stderr.push(""),t.finishEnvelope({name:n,dryRun:r,locale:Xc(y.language)}),t.stderr.push(Fn(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(1);m=K.directory,u=Cr.basename(K.directory),t.stderr.push(Fn(` [OK] OpenSpec archive completed: ${m}`)),t.stepsOk+=1,t.stepsTotal+=1,await MU(l.projectRoot,l.specsDir),t.stderr.push(Fn(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,R&&await Kf(t,l.projectRoot,zs(l.projectRoot,a,m,R),u,"status: final",!1),C&&await Kf(t,l.projectRoot,zs(l.projectRoot,a,m,C),u,"",!1),await sn(m,async()=>{let L=await $t(m);if(!L.classic||!L.run)throw new mt(_t(" [FAIL] archived state projection is incomplete"));let Z={...qU(l.projectRoot,a,m,await Za(m,L.run.artifactsRef)),archive_directory:qe(l.projectRoot,m)};await yo(m,L.run.artifactsRef,Z);let Y=bt(D&&L.classic.archiveConfirmation!=="confirmed"?{...L.classic,archiveConfirmation:"confirmed"}:L.classic,"archived"),fe=(await Fi(l.projectRoot,m)).delivery?.action==="archive-only",z={...Y.classic,...fe?{branchStatus:"handled"}:{},designDoc:zs(l.projectRoot,a,m,Y.classic.designDoc),plan:zs(l.projectRoot,a,m,Y.classic.plan),verificationReport:zs(l.projectRoot,a,m,Y.classic.verificationReport),handoffContext:zs(l.projectRoot,a,m,Y.classic.handoffContext)},ne=L.run;(L.run.currentStep!=="completed"||L.run.status!=="completed")&&(ne=await yf(m,z,L.run,{actionId:q,archiveDirectory:qe(l.projectRoot,m),event:"archived",source:"comet-archive"})),D&&await WU(m,ne,q);let Le=await Tr(m,ne.trajectoryRef),I=await lC(m,ne.contextRef),V={runId:ne.runId,stateVersion:ne.iteration,trajectoryOffset:Le.length,contextHash:I===null?null:F_(I),artifactsHash:jU(Z),createdAt:new Date().toISOString()};await Qu(m,ne.checkpointRef,V);let re={...ne,pending:null,status:"completed"};await $r(m,{classic:z,run:re,unknownKeys:L.unknownKeys}),await M_(m,{change:u,event:"archived",source:"comet-archive",from:L.classic,to:z,effects:Y.effects}),await Xu(m,re.pendingRef)}),t.stderr.push(Fn(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}else{if(!k.run)throw new mt(_t("FATAL: archived Classic state is missing its Run projection"));t.stderr.push(Fn(` [OK] OpenSpec archive completed: ${m}`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(Fn(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(Fn(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}if(r?(R&&await Kf(t,l.projectRoot,R,u,"status: final",!0),C&&await Kf(t,l.projectRoot,C,u,"",!0),t.stderr.push(fl(` [DRY-RUN] Would set archived: true in ${m}/.comet.yaml`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(fl(" [DRY-RUN] Would verify final archive integrity")),t.stepsOk+=1,t.stepsTotal+=1):(await LU(l.projectRoot,m),await v_(l.projectRoot,m),t.stderr.push(Fn(" [OK] Final archive integrity verified")),t.stepsOk+=1,t.stepsTotal+=1),!r){let q=await Fi(l.projectRoot,m);["complete","local-verified"].includes(q.verification.status)&&await I_(l.projectRoot,n)}return t.stderr.push(""),t.finishEnvelope({name:n,dryRun:r,locale:Xc(y.language)}),t.stderr.push(r?fl(`Dry run complete. ${t.stepsOk}/${t.stepsTotal} steps would succeed.`):Fn(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(t.stepsOk<t.stepsTotal?1:0)}catch(s){if(s instanceof mt){if(s.message)for(let o of s.message.split(`
|
|
293
|
+
`))t.stderr.push(o);return t.toResult(s.exitCode)}throw s}});import{realpathSync as zU}from"fs";import{pathToFileURL as K_}from"url";nn();var FU=new Set([...Ka,"archive_confirmation","verify_failures","check_epoch","classic_profile","classic_migration","bound_branch"]),H_=new Set(pi.filter(e=>!FU.has(e))),zy={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"]};nn();var HU=`
|
|
294
|
+
Options: --json (machine-readable output), --compact (requires --json), --help
|
|
295
|
+
精简视图用 outputView.references 的 JSON Pointer 定位重复字段;Request 模板保留完整;没有字节收益时返回原完整协议。去掉 --compact 获取完整协议。
|
|
296
|
+
JSON: one object with command and exitCode; data, stdout, stderr, summary and next are optional.
|
|
297
|
+
Use exitCode for success; do not parse human-readable stdout. Help text is in stdout in JSON mode.
|
|
298
|
+
`;function B_(e,t){let n=t.indexOf("--"),r=n<0?t:t.slice(0,n);if(!r.includes("--help")&&!r.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>"]},s={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: ${[...pi,...Ka].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):",...[...H_].map(l=>` ${l}${zy[l]?`: ${zy[l].join("|")}`:l==="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: ${yx.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."]},o=r.find(l=>!l.startsWith("-")),c=e==="state"&&o&&s[o]||i[e];return c?`Usage: ${c.join(`
|
|
299
|
+
`)}
|
|
300
|
+
${HU}Command placeholders must be replaced with actual values.
|
|
301
|
+
`:void 0}ds();import{randomUUID as BU}from"node:crypto";Xd();import{performance as V_}from"node:perf_hooks";ds();var VU=7*864e5,UU=1e4;async function KU(e,t){let n=Mo(await Nf(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
302
|
+
CREATE TABLE IF NOT EXISTS samples (
|
|
303
|
+
id TEXT PRIMARY KEY, workflow TEXT NOT NULL, kind TEXT NOT NULL, command TEXT NOT NULL,
|
|
304
|
+
occurredAt TEXT NOT NULL, durationMs REAL NOT NULL, exitCode INTEGER NOT NULL,
|
|
305
|
+
gitCommands INTEGER NOT NULL, gitDurationMs REAL NOT NULL);
|
|
306
|
+
CREATE INDEX IF NOT EXISTS samples_time ON samples(occurredAt);
|
|
307
|
+
BEGIN IMMEDIATE;`),n.prepare("DELETE FROM samples WHERE occurredAt < ?").run(new Date(Date.now()-VU).toISOString()),n.prepare("INSERT INTO samples VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(BU(),t.workflow,t.kind,t.command,t.occurredAt,t.durationMs,t.exitCode,t.gitCommands,t.gitDurationMs),n.prepare("DELETE FROM samples WHERE id IN (SELECT id FROM samples ORDER BY occurredAt DESC, rowid DESC LIMIT -1 OFFSET ?)").run(UU),n.exec("COMMIT")}finally{n.close()}}async function U_(e,t){let n=V_.now(),r,i,s=!1,o=1,c=!0,{metrics:l}=await KI({projectRoot:e.projectRoot,workflow:e.workflow,kind:e.kind??"command",name:e.traceName??e.command,status:()=>{try{o=r?e.exitCode?.(r)??r.exitCode??1:e.errorExitCode?.(i)??1}catch{return c=!1,"unknown"}return o===0?"succeeded":"failed"}},()=>DC(async()=>{try{r=await t()}catch(a){s=!0,i=a}})),f=Math.max(0,V_.now()-n);try{if(!c)throw new Error("Runtime result classification unavailable");await KU(await e.projectRoot(),{workflow:e.workflow,kind:e.kind??"command",command:e.command,occurredAt:new Date().toISOString(),durationMs:f,exitCode:o,...l})}catch{}if(s)throw i;return r}Ue();function JU(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e,exitCode:t.exitCode,agent:Fy(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}})+`
|
|
308
|
+
`,...t.envelope===void 0?{}:{envelope:t.envelope}}}async function z_(e,t,n,r={}){let i=n.indexOf("--"),s=f=>i<0||f<i,o=n.some((f,a)=>s(a)&&f==="--json"),c=n.filter((f,a)=>!s(a)||f!=="--json"),l;try{let f=B_(e,c),a=()=>t(c,{json:o,invocationCwd:r.invocationCwd??process.cwd(),...r.projectRoot?{projectRoot:r.projectRoot}:{}});l=f?{exitCode:0,stdout:f}:e==="hook-guard"?await a():await jC(()=>U_({projectRoot:()=>r.projectRoot??it(r.invocationCwd??process.cwd()),workflow:"classic",command:e,errorExitCode:d=>d instanceof ts?1:70},a))}catch(f){l={exitCode:f instanceof ts?1:70,stderr:f instanceof Error?f.message:String(f),data:{issues:[Ks(f)]}}}return o?JU(e,l):l}function J_(e,t){return async(n,r={})=>n[0]!==e?{exitCode:64,stderr:`Expected Classic command: ${e}`}:z_(e,t,n.slice(1),r)}function G_(e){let t=process.argv[1];if(!t)return!1;if(e===K_(t).href)return!0;try{return e===K_(zU(t)).href}catch{return!1}}async function Y_(e,t,n=process.argv.slice(2)){let r=await z_(e,t,n);return r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr+(r.stderr.endsWith(`
|
|
309
|
+
`)?"":`
|
|
310
|
+
`)),r.exitCode}var ese=J_("archive",Ky);G_(import.meta.url)&&(process.exitCode=await Y_("archive",Ky));export{ese as runClassicCli};
|