comet-dsh-plugin 0.0.0-stage → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +58 -4
- package/rules/comet-workflow-guard.md +65 -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 +295 -0
- package/skills/comet/scripts/comet-hook-router-guard.mjs +629 -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 +572 -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 +470 -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,335 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var RP=Object.create;var Qf=Object.defineProperty;var SP=Object.getOwnPropertyDescriptor;var CP=Object.getOwnPropertyNames;var EP=Object.getPrototypeOf,xP=Object.prototype.hasOwnProperty;var kl=(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 re=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var I=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},AP=(e,t)=>{for(var n in t)Qf(e,n,{get:t[n],enumerable:!0})},IP=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of CP(t))!xP.call(e,i)&&i!==n&&Qf(e,i,{get:()=>t[i],enumerable:!(r=SP(t,i))||r.enumerable});return e};var St=(e,t,n)=>(n=e!=null?RP(EP(e)):{},IP(t||!e||!e.__esModule?Qf(n,"default",{value:e,enumerable:!0}):n,e));var Ee=I(It=>{"use strict";var Zf=Symbol.for("yaml.alias"),sv=Symbol.for("yaml.document"),bl=Symbol.for("yaml.map"),ov=Symbol.for("yaml.pair"),ep=Symbol.for("yaml.scalar"),Rl=Symbol.for("yaml.seq"),Pr=Symbol.for("yaml.node.type"),_P=e=>!!e&&typeof e=="object"&&e[Pr]===Zf,PP=e=>!!e&&typeof e=="object"&&e[Pr]===sv,OP=e=>!!e&&typeof e=="object"&&e[Pr]===bl,TP=e=>!!e&&typeof e=="object"&&e[Pr]===ov,av=e=>!!e&&typeof e=="object"&&e[Pr]===ep,NP=e=>!!e&&typeof e=="object"&&e[Pr]===Rl;function cv(e){if(e&&typeof e=="object")switch(e[Pr]){case bl:case Rl:return!0}return!1}function $P(e){if(e&&typeof e=="object")switch(e[Pr]){case Zf:case bl:case ep:case Rl:return!0}return!1}var jP=e=>(av(e)||cv(e))&&!!e.anchor;It.ALIAS=Zf;It.DOC=sv;It.MAP=bl;It.NODE_TYPE=Pr;It.PAIR=ov;It.SCALAR=ep;It.SEQ=Rl;It.hasAnchor=jP;It.isAlias=_P;It.isCollection=cv;It.isDocument=PP;It.isMap=OP;It.isNode=$P;It.isPair=TP;It.isScalar=av;It.isSeq=NP});var ma=I(tp=>{"use strict";var vt=Ee(),rn=Symbol("break visit"),lv=Symbol("skip children"),ur=Symbol("remove node");function Sl(e,t){let n=uv(t);vt.isDocument(e)?eo(null,e.contents,n,Object.freeze([e]))===ur&&(e.contents=null):eo(null,e,n,Object.freeze([]))}Sl.BREAK=rn;Sl.SKIP=lv;Sl.REMOVE=ur;function eo(e,t,n,r){let i=dv(e,t,n,r);if(vt.isNode(i)||vt.isPair(i))return fv(e,r,i),eo(e,i,n,r);if(typeof i!="symbol"){if(vt.isCollection(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let o=eo(s,t.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===rn)return rn;o===ur&&(t.items.splice(s,1),s-=1)}}}else if(vt.isPair(t)){r=Object.freeze(r.concat(t));let s=eo("key",t.key,n,r);if(s===rn)return rn;s===ur&&(t.key=null);let o=eo("value",t.value,n,r);if(o===rn)return rn;o===ur&&(t.value=null)}}return i}async function Cl(e,t){let n=uv(t);vt.isDocument(e)?await to(null,e.contents,n,Object.freeze([e]))===ur&&(e.contents=null):await to(null,e,n,Object.freeze([]))}Cl.BREAK=rn;Cl.SKIP=lv;Cl.REMOVE=ur;async function to(e,t,n,r){let i=await dv(e,t,n,r);if(vt.isNode(i)||vt.isPair(i))return fv(e,r,i),to(e,i,n,r);if(typeof i!="symbol"){if(vt.isCollection(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let o=await to(s,t.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===rn)return rn;o===ur&&(t.items.splice(s,1),s-=1)}}}else if(vt.isPair(t)){r=Object.freeze(r.concat(t));let s=await to("key",t.key,n,r);if(s===rn)return rn;s===ur&&(t.key=null);let o=await to("value",t.value,n,r);if(o===rn)return rn;o===ur&&(t.value=null)}}return i}function uv(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 dv(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(vt.isMap(t))return n.Map?.(e,t,r);if(vt.isSeq(t))return n.Seq?.(e,t,r);if(vt.isPair(t))return n.Pair?.(e,t,r);if(vt.isScalar(t))return n.Scalar?.(e,t,r);if(vt.isAlias(t))return n.Alias?.(e,t,r)}function fv(e,t,n){let r=t[t.length-1];if(vt.isCollection(r))r.items[e]=n;else if(vt.isPair(r))e==="key"?r.key=n:r.value=n;else if(vt.isDocument(r))r.contents=n;else{let i=vt.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}tp.visit=Sl;tp.visitAsync=Cl});var np=I(mv=>{"use strict";var pv=Ee(),DP=ma(),qP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},LP=e=>e.replace(/[!,[\]{}]/g,t=>qP[t]),ha=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+LP(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&&pv.isNode(t.contents)){let s={};DP.visit(t.contents,(o,c)=>{pv.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
|
+
`)}};ha.defaultYaml={explicit:!1,version:"1.2"};ha.defaultTags={"!!":"tag:yaml.org,2002:"};mv.Directives=ha});var El=I(ga=>{"use strict";var hv=Ee(),WP=ma();function MP(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 gv(e){let t=new Set;return WP.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function wv(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function FP(e,t){let n=[],r=new Map,i=null;return{onAnchor:s=>{n.push(s),i??(i=gv(e));let o=wv(t,i);return i.add(o),o},setAnchors:()=>{for(let s of n){let o=r.get(s);if(typeof o=="object"&&o.anchor&&(hv.isScalar(o.node)||hv.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}}ga.anchorIsValid=MP;ga.anchorNames=gv;ga.createNodeAnchors=FP;ga.findNewAnchor=wv});var rp=I(yv=>{"use strict";function wa(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=wa(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=wa(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=wa(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=wa(e,r,i,s);o===void 0?delete r[i]:o!==s&&(r[i]=o)}return e.call(t,n,r)}yv.applyReviver=wa});var Jr=I(kv=>{"use strict";var HP=Ee();function vv(e,t,n){if(Array.isArray(e))return e.map((r,i)=>vv(r,String(i),n));if(e&&typeof e.toJSON=="function"){if(!n||!HP.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}kv.toJS=vv});var xl=I(Rv=>{"use strict";var BP=rp(),bv=Ee(),VP=Jr(),ip=class{constructor(t){Object.defineProperty(this,bv.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(!bv.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"?BP.applyReviver(s,{"":c},"",c):c}};Rv.NodeBase=ip});var ya=I(Sv=>{"use strict";var UP=El(),KP=ma(),no=Ee(),zP=xl(),JP=Jr(),sp=class extends zP.NodeBase{constructor(t){super(no.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=[],KP.visit(t,{Node:(s,o)=>{(no.isAlias(o)||no.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||(JP.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=Al(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(UP.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 Al(e,t,n){if(no.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(no.isCollection(t)){let r=0;for(let i of t.items){let s=Al(e,i,n);s>r&&(r=s)}return r}else if(no.isPair(t)){let r=Al(e,t.key,n),i=Al(e,t.value,n);return Math.max(r,i)}return 1}Sv.Alias=sp});var pt=I(op=>{"use strict";var GP=Ee(),YP=xl(),XP=Jr(),QP=e=>!e||typeof e!="function"&&typeof e!="object",Gr=class extends YP.NodeBase{constructor(t){super(GP.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:XP.toJS(this.value,t,n)}toString(){return String(this.value)}};Gr.BLOCK_FOLDED="BLOCK_FOLDED";Gr.BLOCK_LITERAL="BLOCK_LITERAL";Gr.PLAIN="PLAIN";Gr.QUOTE_DOUBLE="QUOTE_DOUBLE";Gr.QUOTE_SINGLE="QUOTE_SINGLE";op.Scalar=Gr;op.isScalarValue=QP});var va=I(Ev=>{"use strict";var ZP=ya(),Vi=Ee(),Cv=pt(),eO="tag:yaml.org,2002:";function tO(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 nO(e,t,n){if(Vi.isDocument(e)&&(e=e.contents),Vi.isNode(e))return e;if(Vi.isPair(e)){let u=n.schema[Vi.MAP].createNode?.(n.schema,null,n);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 ZP.Alias(l.anchor);l={anchor:null,node:null},c.set(e,l)}t?.startsWith("!!")&&(t=eO+t.slice(2));let f=tO(e,t,o.tags);if(!f){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new Cv.Scalar(e);return l&&(l.node=u),u}f=e instanceof Map?o[Vi.MAP]:Symbol.iterator in Object(e)?o[Vi.SEQ]:o[Vi.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 Cv.Scalar(e);return t?a.tag=t:f.default||(a.tag=f.tag),l&&(l.node=a),a}Ev.createNode=nO});var _l=I(Il=>{"use strict";var rO=va(),dr=Ee(),iO=xl();function ap(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 rO.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 xv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,cp=class extends iO.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=>dr.isNode(r)||dr.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(xv(t))this.add(n);else{let[r,...i]=t,s=this.get(r,!0);if(dr.isCollection(s))s.addIn(i,n);else if(s===void 0&&this.schema)this.set(r,ap(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(dr.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&&dr.isScalar(s)?s.value:s:dr.isCollection(s)?s.getIn(i,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!dr.isPair(n))return!1;let r=n.value;return r==null||t&&dr.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 dr.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(dr.isCollection(s))s.setIn(i,n);else if(s===void 0&&this.schema)this.set(r,ap(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};Il.Collection=cp;Il.collectionFromPath=ap;Il.isEmptyPath=xv});var ka=I(Pl=>{"use strict";var sO=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function lp(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var oO=(e,t,n)=>e.endsWith(`
|
|
6
|
+
`)?lp(n,t):n.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+lp(n,t):(e.endsWith(" ")?"":" ")+n;Pl.indentComment=lp;Pl.lineComment=oO;Pl.stringifyComment=sO});var Iv=I(ba=>{"use strict";var aO="flow",up="block",Ol="quoted";function cO(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={},u=i-t.length;typeof r=="number"&&(r>i-Math.max(2,s)?f.push(0):u=i-r);let p,d,m=!1,h=-1,g=-1,w=-1;n===up&&(h=Av(e,h,t.length),h!==-1&&(u=h+l));for(let y;y=e[h+=1];){if(n===Ol&&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===up&&(h=Av(e,h,t.length)),u=h+t.length+l,p=void 0;else{if(y===" "&&d&&d!==" "&&d!==`
|
|
10
|
+
`&&d!==" "){let R=e[h+1];R&&R!==" "&&R!==`
|
|
11
|
+
`&&R!==" "&&(p=h)}if(h>=u)if(p)f.push(p),u=p+l,p=void 0;else if(n===Ol){for(;d===" "||d===" ";)d=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,u=R+l,p=void 0}else m=!0}d=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],S=f[y+1]||e.length;R===0?k=`
|
|
12
|
+
${t}${e.slice(0,S)}`:(n===Ol&&a[R]&&(k+=`${e[R]}\\`),k+=`
|
|
13
|
+
${t}${e.slice(R+1,S)}`)}return k}function Av(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}ba.FOLD_BLOCK=up;ba.FOLD_FLOW=aO;ba.FOLD_QUOTED=Ol;ba.foldFlowLines=cO});var Sa=I(_v=>{"use strict";var Kn=pt(),Yr=Iv(),Nl=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),$l=e=>/^(%|---|\.\.\.)/m.test(e);function lO(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 Ra(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||($l(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:Yr.foldFlowLines(o,s,Yr.FOLD_QUOTED,Nl(t,!1))}function dp(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Ra(e,t);let n=t.indent||($l(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${n}`)+"'";return t.implicitKey?r:Yr.foldFlowLines(r,n,Yr.FOLD_FLOW,Nl(t,!1))}function ro(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Ra;else{let i=e.includes('"'),s=e.includes("'");i&&!s?r=dp:s&&!i?r=Ra:r=n?dp:Ra}return r(e,t)}var fp;try{fp=new RegExp(`(^|(?<!
|
|
21
|
+
))
|
|
22
|
+
+(?!
|
|
23
|
+
|$)`,"g")}catch{fp=/\n+(?!\n|$)/g}function Tl({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 ro(n,r);let f=r.indent||(r.forceBlockIndent||$l(n)?" ":""),a=o==="literal"?!0:o==="folded"||t===Kn.Scalar.BLOCK_FOLDED?!1:t===Kn.Scalar.BLOCK_LITERAL?!0:!lO(n,l,f.length);if(!n)return a?`|
|
|
24
|
+
`:`>
|
|
25
|
+
`;let u,p;for(p=n.length;p>0;--p){let S=n[p-1];if(S!==`
|
|
26
|
+
`&&S!==" "&&S!==" ")break}let d=n.substring(p),m=d.indexOf(`
|
|
27
|
+
`);m===-1?u="-":n===d||m!==d.length-1?(u="+",s&&s()):u="",d&&(n=n.slice(0,-d.length),d[d.length-1]===`
|
|
28
|
+
`&&(d=d.slice(0,-1)),d=d.replace(fp,`$&${f}`));let h=!1,g,w=-1;for(g=0;g<n.length;++g){let S=n[g];if(S===" ")h=!0;else if(S===`
|
|
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":"")+u;if(e&&(R+=" "+c(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!a){let S=n.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${f}`),C=!1,q=Nl(r,!0);o!=="folded"&&t!==Kn.Scalar.BLOCK_FOLDED&&(q.onOverflow=()=>{C=!0});let T=Yr.foldFlowLines(`${k}${S}${d}`,f,Yr.FOLD_BLOCK,q);if(!C)return`>${R}
|
|
31
|
+
${f}${T}`}return n=n.replace(/\n+/g,`$&${f}`),`|${R}
|
|
32
|
+
${f}${k}${n}${d}`}function uO(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 ro(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return c||a||!s.includes(`
|
|
34
|
+
`)?ro(s,t):Tl(e,t,n,r);if(!c&&!a&&i!==Kn.Scalar.PLAIN&&s.includes(`
|
|
35
|
+
`))return Tl(e,t,n,r);if($l(s)){if(l==="")return t.forceBlockIndent=!0,Tl(e,t,n,r);if(c&&l===f)return ro(s,t)}let u=s.replace(/\n+/g,`$&
|
|
36
|
+
${l}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:d,tags:m}=t.doc.schema;if(m.some(p)||d?.some(p))return ro(s,t)}return c?u:Yr.foldFlowLines(u,l,Yr.FOLD_FLOW,Nl(t,!1))}function dO(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!==Kn.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(c=Kn.Scalar.QUOTE_DOUBLE);let l=a=>{switch(a){case Kn.Scalar.BLOCK_FOLDED:case Kn.Scalar.BLOCK_LITERAL:return i||s?ro(o.value,t):Tl(o,t,n,r);case Kn.Scalar.QUOTE_DOUBLE:return Ra(o.value,t);case Kn.Scalar.QUOTE_SINGLE:return dp(o.value,t);case Kn.Scalar.PLAIN:return uO(o,t,n,r);default:return null}},f=l(c);if(f===null){let{defaultKeyType:a,defaultStringType:u}=t.options,p=i&&a||u;if(f=l(p),f===null)throw new Error(`Unsupported default string type ${p}`)}return f}_v.stringifyString=dO});var Ca=I(pp=>{"use strict";var fO=El(),Xr=Ee(),pO=ka(),mO=Sa();function hO(e,t){let n=Object.assign({blockQuote:!0,commentString:pO.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 gO(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(Xr.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 wO(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],s=(Xr.isScalar(e)||Xr.isCollection(e))&&e.anchor;s&&fO.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 yO(e,t,n,r){if(Xr.isPair(e))return e.toString(t,n,r);if(Xr.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=Xr.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>i=l});i??(i=gO(t.doc.schema.tags,s));let o=wO(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):Xr.isScalar(s)?mO.stringifyString(s,t,n,r):s.toString(t,n,r);return o?Xr.isScalar(s)||c[0]==="{"||c[0]==="["?`${o} ${c}`:`${o}
|
|
37
|
+
${t.indent}${c}`:c}pp.createStringifyContext=hO;pp.stringify=yO});var Nv=I(Tv=>{"use strict";var Or=Ee(),Pv=pt(),Ov=Ca(),Ea=ka();function vO({key:e,value:t},n,r,i){let{allNullValues:s,doc:o,indent:c,indentStep:l,options:{commentString:f,indentSeq:a,simpleKeys:u}}=n,p=Or.isNode(e)&&e.comment||null;if(u){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Or.isCollection(e)||!Or.isNode(e)&&typeof e=="object"){let q="With simple keys, collection cannot be used as a key value";throw new Error(q)}}let d=!u&&(!e||p&&t==null&&!n.inFlow||Or.isCollection(e)||(Or.isScalar(e)?e.type===Pv.Scalar.BLOCK_FOLDED||e.type===Pv.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!d&&(u||!s),indent:c+l});let m=!1,h=!1,g=Ov.stringify(e,n,()=>m=!0,()=>h=!0);if(!d&&!n.inFlow&&g.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");d=!0}if(n.inFlow){if(s||t==null)return m&&r&&r(),g===""?"?":d?`? ${g}`:g}else if(s&&!u||t==null&&d)return g=`? ${g}`,p&&!m?g+=Ea.lineComment(g,n.indent,f(p)):h&&i&&i(),g;m&&(p=null),d?(p&&(g+=Ea.lineComment(g,n.indent,f(p))),g=`? ${g}
|
|
38
|
+
${c}:`):(g=`${g}:`,p&&(g+=Ea.lineComment(g,n.indent,f(p))));let w,k,y;Or.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,!d&&!p&&Or.isScalar(t)&&(n.indentAtStart=g.length+1),h=!1,!a&&l.length>=2&&!n.inFlow&&!d&&Or.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let R=!1,S=Ov.stringify(t,n,()=>R=!0,()=>h=!0),C=" ";if(p||w||k){if(C=w?`
|
|
39
|
+
`:"",k){let q=f(k);C+=`
|
|
40
|
+
${Ea.indentComment(q,n.indent)}`}S===""&&!n.inFlow?C===`
|
|
41
|
+
`&&y&&(C=`
|
|
42
|
+
|
|
43
|
+
`):C+=`
|
|
44
|
+
${n.indent}`}else if(!d&&Or.isCollection(t)){let q=S[0],T=S.indexOf(`
|
|
45
|
+
`),F=T!==-1,B=n.inFlow??t.flow??t.items.length===0;if(F||!B){let X=!1;if(F&&(q==="&"||q==="!")){let Y=S.indexOf(" ");q==="&"&&Y!==-1&&Y<T&&S[Y+1]==="!"&&(Y=S.indexOf(" ",Y+1)),(Y===-1||T<Y)&&(X=!0)}X||(C=`
|
|
46
|
+
${n.indent}`)}}else(S===""||S[0]===`
|
|
47
|
+
`)&&(C="");return g+=C+S,n.inFlow?R&&r&&r():y&&!R?g+=Ea.lineComment(g,n.indent,f(y)):h&&i&&i(),g}Tv.stringifyPair=vO});var hp=I(mp=>{"use strict";var $v=kl("process");function kO(e,...t){e==="debug"&&console.log(...t)}function bO(e,t){(e==="debug"||e==="warn")&&(typeof $v.emitWarning=="function"?$v.emitWarning(t):console.warn(t))}mp.debug=kO;mp.warn=bO});var Wl=I(Ll=>{"use strict";var ql=Ee(),jv=pt(),jl="<<",Dl={identify:e=>e===jl||typeof e=="symbol"&&e.description===jl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new jv.Scalar(Symbol(jl)),{addToJSMap:Dv}),stringify:()=>jl},RO=(e,t)=>(Dl.identify(t)||ql.isScalar(t)&&(!t.type||t.type===jv.Scalar.PLAIN)&&Dl.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Dl.tag&&n.default);function Dv(e,t,n){let r=qv(e,n);if(ql.isSeq(r))for(let i of r.items)gp(e,t,i);else if(Array.isArray(r))for(let i of r)gp(e,t,i);else gp(e,t,r)}function gp(e,t,n){let r=qv(e,n);if(!ql.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 qv(e,t){return e&&ql.isAlias(t)?t.resolve(e.doc,e):t}Ll.addMergeToJSMap=Dv;Ll.isMergeKey=RO;Ll.merge=Dl});var yp=I(Mv=>{"use strict";var SO=hp(),Lv=Wl(),CO=Ca(),Wv=Ee(),wp=Jr();function EO(e,t,{key:n,value:r}){if(Wv.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Lv.isMergeKey(e,n))Lv.addMergeToJSMap(e,t,r);else{let i=wp.toJS(n,"",e);if(t instanceof Map)t.set(i,wp.toJS(r,i,e));else if(t instanceof Set)t.add(i);else{let s=xO(n,i,e),o=wp.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 xO(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Wv.isNode(e)&&n?.doc){let r=CO.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)+'..."'),SO.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)}Mv.addPairToJSMap=EO});var Qr=I(vp=>{"use strict";var Fv=va(),AO=Nv(),IO=yp(),Ml=Ee();function _O(e,t,n){let r=Fv.createNode(e,void 0,n),i=Fv.createNode(t,void 0,n);return new Fl(r,i)}var Fl=class e{constructor(t,n=null){Object.defineProperty(this,Ml.NODE_TYPE,{value:Ml.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return Ml.isNode(n)&&(n=n.clone(t)),Ml.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return IO.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?AO.stringifyPair(this,t,n,r):JSON.stringify(this)}};vp.Pair=Fl;vp.createPair=_O});var kp=I(Bv=>{"use strict";var Ui=Ee(),Hv=Ca(),Hl=ka();function PO(e,t,n){return(t.inFlow??e.flow?TO: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}),u=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(Ui.isNode(h))!u&&h.spaceBefore&&p.push(""),Bl(n,p,h.commentBefore,u),h.comment&&(g=h.comment);else if(Ui.isPair(h)){let k=Ui.isNode(h.key)?h.key:null;k&&(!u&&k.spaceBefore&&p.push(""),Bl(n,p,k.commentBefore,u))}u=!1;let w=Hv.stringify(h,a,()=>g=null,()=>u=!0);g&&(w+=Hl.lineComment(w,s,f(g))),u&&g&&(u=!1),p.push(r+w)}let d;if(p.length===0)d=i.start+i.end;else{d=p[0];for(let m=1;m<p.length;++m){let h=p[m];d+=h?`
|
|
48
|
+
${l}${h}`:`
|
|
49
|
+
`}}return e?(d+=`
|
|
50
|
+
`+Hl.indentComment(f(e),l),c&&c()):u&&o&&o(),d}function TO({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,u=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(Ui.isNode(h))h.spaceBefore&&u.push(""),Bl(t,u,h.commentBefore,!1),h.comment&&(g=h.comment);else if(Ui.isPair(h)){let k=Ui.isNode(h.key)?h.key:null;k&&(k.spaceBefore&&u.push(""),Bl(t,u,k.commentBefore,!1),k.comment&&(f=!0));let y=Ui.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=Hv.stringify(h,l,()=>g=null);f||(f=u.length>a||w.includes(`
|
|
51
|
+
`)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(f||(f=u.reduce((k,y)=>k+y.length+2,2)+(w.length+2)>t.options.lineWidth)),f&&(w+=",")),g&&(w+=Hl.lineComment(w,r,c(g))),u.push(w),a=u.length}let{start:p,end:d}=n;if(u.length===0)return p+d;if(!f){let m=u.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 u)m+=h?`
|
|
52
|
+
${s}${i}${h}`:`
|
|
53
|
+
`;return`${m}
|
|
54
|
+
${i}${d}`}else return`${p}${o}${u.join(" ")}${o}${d}`}function Bl({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let s=Hl.indentComment(t(r),e);n.push(s.trimStart())}}Bv.stringifyCollection=PO});var ei=I(Rp=>{"use strict";var NO=kp(),$O=yp(),jO=_l(),Zr=Ee(),Vl=Qr(),DO=pt();function xa(e,t){let n=Zr.isScalar(t)?t.value:t;for(let r of e)if(Zr.isPair(r)&&(r.key===t||r.key===n||Zr.isScalar(r.key)&&r.key.value===n))return r}var bp=class extends jO.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Zr.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(Vl.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;Zr.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Vl.Pair(t,t?.value):r=new Vl.Pair(t.key,t.value);let i=xa(this.items,r.key),s=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${r.key} already set`);Zr.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=xa(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let i=xa(this.items,t)?.value;return(!n&&Zr.isScalar(i)?i.value:i)??void 0}has(t){return!!xa(this.items,t)}set(t,n){this.add(new Vl.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)$O.addPairToJSMap(n,i,s);return i}toString(t,n,r){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Zr.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})),NO.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};Rp.YAMLMap=bp;Rp.findPair=xa});var io=I(Uv=>{"use strict";var qO=Ee(),Vv=ei(),LO={collection:"map",default:!0,nodeClass:Vv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return qO.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>Vv.YAMLMap.from(e,t,n)};Uv.map=LO});var ti=I(Kv=>{"use strict";var WO=va(),MO=kp(),FO=_l(),Kl=Ee(),HO=pt(),BO=Jr(),Sp=class extends FO.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Kl.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Ul(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Ul(t);if(typeof r!="number")return;let i=this.items[r];return!n&&Kl.isScalar(i)?i.value:i}has(t){let n=Ul(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Ul(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[r];Kl.isScalar(i)&&HO.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(BO.toJS(s,String(i++),n));return r}toString(t,n,r){return t?MO.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(WO.createNode(c,void 0,r))}}return s}};function Ul(e){let t=Kl.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Kv.YAMLSeq=Sp});var so=I(Jv=>{"use strict";var VO=Ee(),zv=ti(),UO={collection:"seq",default:!0,nodeClass:zv.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)=>zv.YAMLSeq.from(e,t,n)};Jv.seq=UO});var Aa=I(Gv=>{"use strict";var KO=Sa(),zO={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),KO.stringifyString(e,t,n,r)}};Gv.string=zO});var zl=I(Qv=>{"use strict";var Yv=pt(),Xv={identify:e=>e==null,createNode:()=>new Yv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Yv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Xv.test.test(e)?e:t.options.nullStr};Qv.nullTag=Xv});var Cp=I(ek=>{"use strict";var JO=pt(),Zv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new JO.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&Zv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};ek.boolTag=Zv});var oo=I(tk=>{"use strict";function GO({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}tk.stringifyNumber=GO});var xp=I(Jl=>{"use strict";var YO=pt(),Ep=oo(),XO={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:Ep.stringifyNumber},QO={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():Ep.stringifyNumber(e)}},ZO={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 YO.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:Ep.stringifyNumber};Jl.float=ZO;Jl.floatExp=QO;Jl.floatNaN=XO});var Ip=I(Yl=>{"use strict";var nk=oo(),Gl=e=>typeof e=="bigint"||Number.isInteger(e),Ap=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function rk(e,t,n){let{value:r}=e;return Gl(r)&&r>=0?n+r.toString(t):nk.stringifyNumber(e)}var e0={identify:e=>Gl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Ap(e,2,8,n),stringify:e=>rk(e,8,"0o")},t0={identify:Gl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Ap(e,0,10,n),stringify:nk.stringifyNumber},n0={identify:e=>Gl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Ap(e,2,16,n),stringify:e=>rk(e,16,"0x")};Yl.int=t0;Yl.intHex=n0;Yl.intOct=e0});var sk=I(ik=>{"use strict";var r0=io(),i0=zl(),s0=so(),o0=Aa(),a0=Cp(),_p=xp(),Pp=Ip(),c0=[r0.map,s0.seq,o0.string,i0.nullTag,a0.boolTag,Pp.intOct,Pp.int,Pp.intHex,_p.floatNaN,_p.floatExp,_p.float];ik.schema=c0});var ck=I(ak=>{"use strict";var l0=pt(),u0=io(),d0=so();function ok(e){return typeof e=="bigint"||Number.isInteger(e)}var Xl=({value:e})=>JSON.stringify(e),f0=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Xl},{identify:e=>e==null,createNode:()=>new l0.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Xl},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Xl},{identify:ok,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})=>ok(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:Xl}],p0={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},m0=[u0.map,d0.seq].concat(f0,p0);ak.schema=m0});var Tp=I(lk=>{"use strict";var Ia=kl("buffer"),Op=pt(),h0=Sa(),g0={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ia.Buffer=="function")return Ia.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 Ia.Buffer=="function")c=o instanceof Ia.Buffer?o.toString("base64"):Ia.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=Op.Scalar.BLOCK_LITERAL),t!==Op.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 u=0,p=0;u<f;++u,p+=l)a[u]=c.substr(p,l);c=a.join(t===Op.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return h0.stringifyString({comment:e,type:t,value:c},r,i,s)}};lk.binary=g0});var eu=I(Zl=>{"use strict";var Ql=Ee(),Np=Qr(),w0=pt(),y0=ti();function uk(e,t){if(Ql.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Ql.isPair(r)){if(Ql.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let i=r.items[0]||new Np.Pair(new w0.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]=Ql.isPair(r)?r:new Np.Pair(r)}}else t("Expected a sequence for this tag");return e}function dk(e,t,n){let{replacer:r}=n,i=new y0.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(Np.createPair(c,l,n))}return i}var v0={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:uk,createNode:dk};Zl.createPairs=dk;Zl.pairs=v0;Zl.resolvePairs=uk});var Dp=I(jp=>{"use strict";var fk=Ee(),$p=Jr(),_a=ei(),k0=ti(),pk=eu(),Ki=class e extends k0.YAMLSeq{constructor(){super(),this.add=_a.YAMLMap.prototype.add.bind(this),this.delete=_a.YAMLMap.prototype.delete.bind(this),this.get=_a.YAMLMap.prototype.get.bind(this),this.has=_a.YAMLMap.prototype.has.bind(this),this.set=_a.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(fk.isPair(i)?(s=$p.toJS(i.key,"",n),o=$p.toJS(i.value,s,n)):s=$p.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=pk.createPairs(t,n,r),s=new this;return s.items=i.items,s}};Ki.tag="tag:yaml.org,2002:omap";var b0={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ki,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=pk.resolvePairs(e,t),r=[];for(let{key:i}of n.items)fk.isScalar(i)&&(r.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new Ki,n)},createNode:(e,t,n)=>Ki.from(e,t,n)};jp.YAMLOMap=Ki;jp.omap=b0});var yk=I(qp=>{"use strict";var mk=pt();function hk({value:e,source:t},n){return t&&(e?gk:wk).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var gk={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 mk.Scalar(!0),stringify:hk},wk={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 mk.Scalar(!1),stringify:hk};qp.falseTag=wk;qp.trueTag=gk});var vk=I(tu=>{"use strict";var R0=pt(),Lp=oo(),S0={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:Lp.stringifyNumber},C0={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():Lp.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 R0.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:Lp.stringifyNumber};tu.float=E0;tu.floatExp=C0;tu.floatNaN=S0});var bk=I(Oa=>{"use strict";var kk=oo(),Pa=e=>typeof e=="bigint"||Number.isInteger(e);function nu(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 Wp(e,t,n){let{value:r}=e;if(Pa(r)){let i=r.toString(t);return r<0?"-"+n+i.substr(1):n+i}return kk.stringifyNumber(e)}var x0={identify:Pa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>nu(e,2,2,n),stringify:e=>Wp(e,2,"0b")},A0={identify:Pa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>nu(e,1,8,n),stringify:e=>Wp(e,8,"0")},I0={identify:Pa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>nu(e,0,10,n),stringify:kk.stringifyNumber},_0={identify:Pa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>nu(e,2,16,n),stringify:e=>Wp(e,16,"0x")};Oa.int=I0;Oa.intBin=x0;Oa.intHex=_0;Oa.intOct=A0});var Fp=I(Mp=>{"use strict";var su=Ee(),ru=Qr(),iu=ei(),zi=class e extends iu.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;su.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new ru.Pair(t.key,null):n=new ru.Pair(t,null),iu.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=iu.findPair(this.items,t);return!n&&su.isPair(r)?su.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=iu.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new ru.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(ru.createPair(o,null,r));return s}};zi.tag="tag:yaml.org,2002:set";var P0={collection:"map",identify:e=>e instanceof Set,nodeClass:zi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>zi.from(e,t,n),resolve(e,t){if(su.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new zi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Mp.YAMLSet=zi;Mp.set=P0});var Bp=I(ou=>{"use strict";var O0=oo();function Hp(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 Rk(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 T0={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})=>Hp(e,n),stringify:Rk},N0={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=>Hp(e,!1),stringify:Rk},Sk={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(Sk.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 u=Hp(a,!1);Math.abs(u)<30&&(u*=60),f-=6e4*u}return new Date(f)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ou.floatTime=N0;ou.intTime=T0;ou.timestamp=Sk});var xk=I(Ek=>{"use strict";var $0=io(),j0=zl(),D0=so(),q0=Aa(),L0=Tp(),Ck=yk(),Vp=vk(),au=bk(),W0=Wl(),M0=Dp(),F0=eu(),H0=Fp(),Up=Bp(),B0=[$0.map,D0.seq,q0.string,j0.nullTag,Ck.trueTag,Ck.falseTag,au.intBin,au.intOct,au.int,au.intHex,Vp.floatNaN,Vp.floatExp,Vp.float,L0.binary,W0.merge,M0.omap,F0.pairs,H0.set,Up.intTime,Up.floatTime,Up.timestamp];Ek.schema=B0});var Dk=I(Jp=>{"use strict";var Pk=io(),V0=zl(),Ok=so(),U0=Aa(),K0=Cp(),Kp=xp(),zp=Ip(),z0=sk(),J0=ck(),Tk=Tp(),Ta=Wl(),Nk=Dp(),$k=eu(),Ak=xk(),jk=Fp(),cu=Bp(),Ik=new Map([["core",z0.schema],["failsafe",[Pk.map,Ok.seq,U0.string]],["json",J0.schema],["yaml11",Ak.schema],["yaml-1.1",Ak.schema]]),_k={binary:Tk.binary,bool:K0.boolTag,float:Kp.float,floatExp:Kp.floatExp,floatNaN:Kp.floatNaN,floatTime:cu.floatTime,int:zp.int,intHex:zp.intHex,intOct:zp.intOct,intTime:cu.intTime,map:Pk.map,merge:Ta.merge,null:V0.nullTag,omap:Nk.omap,pairs:$k.pairs,seq:Ok.seq,set:jk.set,timestamp:cu.timestamp},G0={"tag:yaml.org,2002:binary":Tk.binary,"tag:yaml.org,2002:merge":Ta.merge,"tag:yaml.org,2002:omap":Nk.omap,"tag:yaml.org,2002:pairs":$k.pairs,"tag:yaml.org,2002:set":jk.set,"tag:yaml.org,2002:timestamp":cu.timestamp};function Y0(e,t,n){let r=Ik.get(t);if(r&&!e)return n&&!r.includes(Ta.merge)?r.concat(Ta.merge):r.slice();let i=r;if(!i)if(Array.isArray(e))i=[];else{let s=Array.from(Ik.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(Ta.merge)),i.reduce((s,o)=>{let c=typeof o=="string"?_k[o]:o;if(!c){let l=JSON.stringify(o),f=Object.keys(_k).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},[])}Jp.coreKnownTags=G0;Jp.getTags=Y0});var Xp=I(qk=>{"use strict";var Gp=Ee(),X0=io(),Q0=so(),Z0=Aa(),lu=Dk(),eT=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Yp=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:c}){this.compat=Array.isArray(t)?lu.getTags(t,"compat"):t?lu.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?lu.coreKnownTags:{},this.tags=lu.getTags(n,this.name,r),this.toStringOptions=c??null,Object.defineProperty(this,Gp.MAP,{value:X0.map}),Object.defineProperty(this,Gp.SCALAR,{value:Z0.string}),Object.defineProperty(this,Gp.SEQ,{value:Q0.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?eT:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};qk.Schema=Yp});var Wk=I(Lk=>{"use strict";var tT=Ee(),Qp=Ca(),Na=ka();function nT(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=Qp.createStringifyContext(e,t),{commentString:s}=i.options;if(e.commentBefore){n.length!==1&&n.unshift("");let l=s(e.commentBefore);n.unshift(Na.indentComment(l,""))}let o=!1,c=null;if(e.contents){if(tT.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let a=s(e.contents.commentBefore);n.push(Na.indentComment(a,""))}i.forceBlockIndent=!!e.comment,c=e.contents.comment}let l=c?void 0:()=>o=!0,f=Qp.stringify(e.contents,i,()=>c=null,l);c&&(f+=Na.lineComment(f,"",s(c))),(f[0]==="|"||f[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${f}`:n.push(f)}else n.push(Qp.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let l=s(e.comment);l.includes(`
|
|
58
|
+
`)?(n.push("..."),n.push(Na.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(Na.indentComment(s(l),"")))}return n.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}Lk.stringifyDocument=nT});var $a=I(Mk=>{"use strict";var rT=ya(),ao=_l(),En=Ee(),iT=Qr(),sT=Jr(),oT=Xp(),aT=Wk(),Zp=El(),cT=rp(),lT=va(),em=np(),tm=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,En.NODE_TYPE,{value:En.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 em.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,{[En.NODE_TYPE]:{value:En.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=En.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){co(this.contents)&&this.contents.add(t)}addIn(t,n){co(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Zp.anchorNames(this);t.anchor=!n||r.has(n)?Zp.findNewAnchor(n||"a",r):n}return new rT.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:u,setAnchors:p,sourceObjects:d}=Zp.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:s??!0,keepUndefined:l??!1,onAnchor:u,onTagObj:f,replacer:i,schema:this.schema,sourceObjects:d},h=lT.createNode(t,a,m);return c&&En.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 iT.Pair(i,s)}delete(t){return co(this.contents)?this.contents.delete(t):!1}deleteIn(t){return ao.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):co(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return En.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return ao.isEmptyPath(t)?!n&&En.isScalar(this.contents)?this.contents.value:this.contents:En.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return En.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return ao.isEmptyPath(t)?this.contents!==void 0:En.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=ao.collectionFromPath(this.schema,[t],n):co(this.contents)&&this.contents.set(t,n)}setIn(t,n){ao.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=ao.collectionFromPath(this.schema,Array.from(t),n):co(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 em.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 em.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 oT.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=sT.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"?cT.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 aT.stringifyDocument(this,t)}};function co(e){if(En.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Mk.Document=tm});var qa=I(Da=>{"use strict";var ja=class extends Error{constructor(t,n,r,i){super(),this.name=t,this.code=r,this.message=i,this.pos=n}},nm=class extends ja{constructor(t,n,r){super("YAMLParseError",t,n,r)}},rm=class extends ja{constructor(t,n,r){super("YAMLWarning",t,n,r)}},uT=(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
|
+
`}};Da.YAMLError=ja;Da.YAMLParseError=nm;Da.YAMLWarning=rm;Da.prettifyError=uT});var La=I(Fk=>{"use strict";function dT(e,{flow:t,indicator:n,next:r,offset:i,onError:s,parentIndent:o,startOnNewline:c}){let l=!1,f=c,a=c,u="",p="",d=!1,m=!1,h=null,g=null,w=null,k=null,y=null,R=null,S=null;for(let T of e)switch(m&&(T.type!=="space"&&T.type!=="newline"&&T.type!=="comma"&&s(T.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(f&&T.type!=="comment"&&T.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),T.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&T.source.includes(" ")&&(h=T),a=!0;break;case"comment":{a||s(T,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let F=T.source.substring(1)||" ";u?u+=p+F:u=F,p="",f=!1;break}case"newline":f?u?u+=T.source:(!R||n!=="seq-item-ind")&&(l=!0):p+=T.source,f=!0,d=!0,(g||w)&&(k=T),a=!0;break;case"anchor":g&&s(T,"MULTIPLE_ANCHORS","A node can have at most one anchor"),T.source.endsWith(":")&&s(T.offset+T.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=T,S??(S=T.offset),f=!1,a=!1,m=!0;break;case"tag":{w&&s(T,"MULTIPLE_TAGS","A node can have at most one tag"),w=T,S??(S=T.offset),f=!1,a=!1,m=!0;break}case n:(g||w)&&s(T,"BAD_PROP_ORDER",`Anchors and tags must be after the ${T.source} indicator`),R&&s(T,"UNEXPECTED_TOKEN",`Unexpected ${T.source} in ${t??"collection"}`),R=T,f=n==="seq-item-ind"||n==="explicit-key-ind",a=!1;break;case"comma":if(t){y&&s(T,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=T,f=!1,a=!1;break}default:s(T,"UNEXPECTED_TOKEN",`Unexpected ${T.type} token`),f=!1,a=!1}let C=e[e.length-1],q=C?C.offset+C.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:u,hasNewline:d,anchor:g,tag:w,newlineAfterProp:k,end:q,start:S??q}}Fk.resolveProps=dT});var uu=I(Hk=>{"use strict";function im(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(im(t.key)||im(t.value))return!0}return!1;default:return!0}}Hk.containsNewline=im});var sm=I(Bk=>{"use strict";var fT=uu();function pT(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&fT.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Bk.flowIndentCheck=pT});var om=I(Uk=>{"use strict";var Vk=Ee();function mT(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r=="function"?r:(s,o)=>s===o||Vk.isScalar(s)&&Vk.isScalar(o)&&s.value===o.value;return t.some(s=>i(s.key,n))}Uk.mapIncludes=mT});var Xk=I(Yk=>{"use strict";var Kk=Qr(),hT=ei(),zk=La(),gT=uu(),Jk=sm(),wT=om(),Gk="All mapping items must start at the same column";function yT({composeNode:e,composeEmptyNode:t},n,r,i,s){let o=s?.nodeClass??hT.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:u,key:p,sep:d,value:m}=a,h=zk.resolveProps(u,{indicator:"explicit-key-ind",next:p??d?.[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",Gk)),!h.anchor&&!h.tag&&!d){f=h.end,h.comment&&(c.comment?c.comment+=`
|
|
67
|
+
`+h.comment:c.comment=h.comment);continue}(h.newlineAfterProp||gT.containsNewline(p))&&i(p??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&i(l,"BAD_INDENT",Gk);n.atKey=!0;let w=h.end,k=p?e(n,p,h,i):t(n,w,u,null,h,i);n.schema.compat&&Jk.flowIndentCheck(r.indent,p,i),n.atKey=!1,wT.mapIncludes(n,c.items,k)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let y=zk.resolveProps(d??[],{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,d,null,y,i);n.schema.compat&&Jk.flowIndentCheck(r.indent,m,i),l=R.range[2];let S=new Kk.Pair(k,R);n.options.keepSourceTokens&&(S.srcToken=a),c.items.push(S)}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 Kk.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}Yk.resolveBlockMap=yT});var Zk=I(Qk=>{"use strict";var vT=ti(),kT=La(),bT=sm();function RT({composeNode:e,composeEmptyNode:t},n,r,i,s){let o=s?.nodeClass??vT.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:u}of r.items){let p=kT.resolveProps(a,{indicator:"seq-item-ind",next:u,offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||u)u?.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 d=u?e(n,u,p,i):t(n,p.end,a,null,p,i);n.schema.compat&&bT.flowIndentCheck(r.indent,u,i),l=d.range[2],c.items.push(d)}return c.range=[r.offset,l,f??l],c}Qk.resolveBlockSeq=RT});var lo=I(eb=>{"use strict";function ST(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}}eb.resolveEnd=ST});var ib=I(rb=>{"use strict";var CT=Ee(),ET=Qr(),tb=ei(),xT=ti(),AT=lo(),nb=La(),IT=uu(),_T=om(),am="Block collections are not allowed within flow collections",cm=e=>e&&(e.type==="block-map"||e.type==="block-seq");function PT({composeNode:e,composeEmptyNode:t},n,r,i,s){let o=r.start.source==="{",c=o?"flow map":"flow sequence",l=s?.nodeClass??(o?tb.YAMLMap:xT.YAMLSeq),f=new l(n.schema);f.flow=!0;let a=n.atRoot;a&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=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:S}=w,C=nb.resolveProps(k,{flow:c,indicator:"explicit-key-ind",next:y??R?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!R&&!S){g===0&&C.comma?i(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`):g<r.items.length-1&&i(C.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${c}`),C.comment&&(f.comment?f.comment+=`
|
|
69
|
+
`+C.comment:f.comment=C.comment),u=C.end;continue}!o&&n.options.strict&&IT.containsNewline(y)&&i(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)C.comma&&i(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`);else if(C.comma||i(C.start,"MISSING_CHAR",`Missing , between ${c} items`),C.comment){let q="";e:for(let T of k)switch(T.type){case"comma":case"space":break;case"comment":q=T.source.substring(1);break e;default:break e}if(q){let T=f.items[f.items.length-1];CT.isPair(T)&&(T=T.value??T.key),T.comment?T.comment+=`
|
|
70
|
+
`+q:T.comment=q,C.comment=C.comment.substring(q.length+1)}}if(!o&&!R&&!C.found){let q=S?e(n,S,C,i):t(n,C.end,R,null,C,i);f.items.push(q),u=q.range[2],cm(S)&&i(q.range,"BLOCK_IN_FLOW",am)}else{n.atKey=!0;let q=C.end,T=y?e(n,y,C,i):t(n,q,k,null,C,i);cm(y)&&i(T.range,"BLOCK_IN_FLOW",am),n.atKey=!1;let F=nb.resolveProps(R??[],{flow:c,indicator:"map-value-ind",next:S,offset:T.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(F.found){if(!o&&!C.found&&n.options.strict){if(R)for(let Y of R){if(Y===F.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}}C.start<F.found.offset-1024&&i(F.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?i(S,"MISSING_CHAR",`Missing space after : in ${c}`):i(F.start,"MISSING_CHAR",`Missing , or : between ${c} items`));let B=S?e(n,S,F,i):F.found?t(n,F.end,R,null,F,i):null;B?cm(S)&&i(B.range,"BLOCK_IN_FLOW",am):F.comment&&(T.comment?T.comment+=`
|
|
71
|
+
`+F.comment:T.comment=F.comment);let X=new ET.Pair(T,B);if(n.options.keepSourceTokens&&(X.srcToken=w),o){let Y=f;_T.mapIncludes(n,Y.items,T)&&i(q,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(X)}else{let Y=new tb.YAMLMap(n.schema);Y.flow=!0,Y.items.push(X);let de=(B??T).range;Y.range=[T.range[0],de[1],de[2]],f.items.push(Y)}u=B?B.range[2]:F.end}}let p=o?"}":"]",[d,...m]=r.end,h=u;if(d?.source===p)h=d.offset+d.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(u,a?"MISSING_CHAR":"BAD_INDENT",w),d&&d.source.length!==1&&m.unshift(d)}if(m.length>0){let g=AT.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}rb.resolveFlowCollection=PT});var ob=I(sb=>{"use strict";var OT=Ee(),TT=pt(),NT=ei(),$T=ti(),jT=Xk(),DT=Zk(),qT=ib();function lm(e,t,n,r,i,s){let o=n.type==="block-map"?jT.resolveBlockMap(e,t,n,r,s):n.type==="block-seq"?DT.resolveBlockSeq(e,t,n,r,s):qT.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 LT(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:d}=r,m=p&&s?p.offset>s.offset?p:s:p??s;m&&(!d||d.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===NT.YAMLMap.tagName&&c==="map"||o===$T.YAMLSeq.tagName&&c==="seq")return lm(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),lm(e,t,n,i,o)}let f=lm(e,t,n,i,o,l),a=l.resolve?.(f,p=>i(s,"TAG_RESOLVE_FAILED",p),t.options)??f,u=OT.isNode(a)?a:new TT.Scalar(a);return u.range=f.range,u.tag=o,l?.format&&(u.format=l.format),u}sb.composeCollection=LT});var dm=I(ab=>{"use strict";var um=pt();function WT(e,t,n){let r=t.offset,i=MT(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let s=i.mode===">"?um.Scalar.BLOCK_FOLDED:um.Scalar.BLOCK_LITERAL,o=t.source?FT(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 u="",p="",d=!1;for(let h=0;h<a;++h)u+=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===um.Scalar.BLOCK_LITERAL?(u+=p+g.slice(l)+w,p=`
|
|
75
|
+
`):g.length>l||w[0]===" "?(p===" "?p=`
|
|
76
|
+
`:!d&&p===`
|
|
77
|
+
`&&(p=`
|
|
78
|
+
|
|
79
|
+
`),u+=p+g.slice(l)+w,p=`
|
|
80
|
+
`,d=!0):w===""?p===`
|
|
81
|
+
`?u+=`
|
|
82
|
+
`:p=`
|
|
83
|
+
`:(u+=p+w,p=" ",d=!1)}switch(i.chomp){case"-":break;case"+":for(let h=c;h<o.length;++h)u+=`
|
|
84
|
+
`+o[h][0].slice(l);u[u.length-1]!==`
|
|
85
|
+
`&&(u+=`
|
|
86
|
+
`);break;default:u+=`
|
|
87
|
+
`}let m=r+i.length+t.source.length;return{value:u,type:s,comment:i.comment,range:[r,m,m]}}function MT({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 d=i[p];if(!c&&(d==="-"||d==="+"))c=d;else{let m=Number(d);!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="",u=i.length;for(let p=1;p<t.length;++p){let d=t[p];switch(d.type){case"space":f=!0;case"newline":u+=d.source.length;break;case"comment":n&&!f&&r(d,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=d.source.length,a=d.source.substring(1);break;case"error":r(d,"UNEXPECTED_TOKEN",d.message),u+=d.source.length;break;default:{let m=`Unexpected token in block scalar header: ${d.type}`;r(d,"UNEXPECTED_TOKEN",m);let h=d.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:s,indent:o,chomp:c,comment:a,length:u}}function FT(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}ab.resolveBlockScalar=WT});var pm=I(lb=>{"use strict";var fm=pt(),HT=lo();function BT(e,t,n){let{offset:r,type:i,source:s,end:o}=e,c,l,f=(p,d,m)=>n(r+p,d,m);switch(i){case"scalar":c=fm.Scalar.PLAIN,l=VT(s,f);break;case"single-quoted-scalar":c=fm.Scalar.QUOTE_SINGLE,l=UT(s,f);break;case"double-quoted-scalar":c=fm.Scalar.QUOTE_DOUBLE,l=KT(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,u=HT.resolveEnd(o,a,t,n);return{value:l,type:c,comment:u.comment,range:[r,a,u.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}`),cb(e)}function UT(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),cb(e.slice(1,-1)).replace(/''/g,"'")}function cb(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 KT(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}=zT(e,r);n+=s,r=o}else if(i==="\\"){let s=e[++r],o=JT[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+=GT(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 zT(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 JT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function GT(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}}lb.resolveFlowScalar=BT});var fb=I(db=>{"use strict";var Ji=Ee(),ub=pt(),YT=dm(),XT=pm();function QT(e,t,n,r){let{value:i,type:s,comment:o,range:c}=t.type==="block-scalar"?YT.resolveBlockScalar(e,t,r):XT.resolveFlowScalar(t,e.options.strict,r),l=n?e.directives.tagName(n.source,u=>r(n,"TAG_RESOLVE_FAILED",u)):null,f;e.options.stringKeys&&e.atKey?f=e.schema[Ji.SCALAR]:l?f=ZT(e.schema,i,l,n,r):t.type==="scalar"?f=eN(e,i,t,r):f=e.schema[Ji.SCALAR];let a;try{let u=f.resolve(i,p=>r(n??t,"TAG_RESOLVE_FAILED",p),e.options);a=Ji.isScalar(u)?u:new ub.Scalar(u)}catch(u){let p=u instanceof Error?u.message:String(u);r(n??t,"TAG_RESOLVE_FAILED",p),a=new ub.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 ZT(e,t,n,r,i){if(n==="!")return e[Ji.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[Ji.SCALAR])}function eN({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[Ji.SCALAR];if(n.compat){let c=n.compat.find(l=>l.default&&l.test?.test(r))??n[Ji.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}db.composeScalar=QT});var mb=I(pb=>{"use strict";function tN(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}pb.emptyScalarPosition=tN});var wb=I(hm=>{"use strict";var nN=ya(),rN=Ee(),iN=ob(),hb=fb(),sN=lo(),oN=mb(),aN={composeNode:gb,composeEmptyNode:mm};function gb(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=cN(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=hb.composeScalar(e,t,l,r),c&&(f.anchor=c.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{f=iN.composeCollection(aN,e,t,n,r),c&&(f.anchor=c.source.substring(1))}catch(u){let p=u instanceof Error?u.message:String(u);r(t,"RESOURCE_EXHAUSTION",p)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",u),a=!1}}return f??(f=mm(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&&(!rN.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 mm(e,t,n,r,{spaceBefore:i,comment:s,anchor:o,tag:c,end:l},f){let a={type:"scalar",offset:oN.emptyScalarPosition(t,n,r),indent:-1,source:""},u=hb.composeScalar(e,a,c,f);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&f(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=l),u}function cN({options:e},{offset:t,source:n,end:r},i){let s=new nN.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=sN.resolveEnd(r,o,e.strict,i);return s.range=[t,o,c.offset],c.comment&&(s.comment=c.comment),s}hm.composeEmptyNode=mm;hm.composeNode=gb});var kb=I(vb=>{"use strict";var lN=$a(),yb=wb(),uN=lo(),dN=La();function fN(e,t,{offset:n,start:r,value:i,end:s},o){let c=Object.assign({_directives:t},e),l=new lN.Document(void 0,c),f={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},a=dN.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?yb.composeNode(f,i,a,o):yb.composeEmptyNode(f,a.end,r,null,a,o);let u=l.contents.range[2],p=uN.resolveEnd(s,u,!1,o);return p.comment&&(l.comment=p.comment),l.range=[n,u,p.offset],l}vb.composeDoc=fN});var wm=I(Sb=>{"use strict";var pN=kl("process"),mN=np(),hN=$a(),Wa=qa(),bb=Ee(),gN=kb(),wN=lo();function Ma(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 Rb(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 gm=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,i,s)=>{let o=Ma(n);s?this.warnings.push(new Wa.YAMLWarning(o,r,i)):this.errors.push(new Wa.YAMLParseError(o,r,i))},this.directives=new mN.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:i}=Rb(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(bb.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];bb.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:Rb(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(pN.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,i)=>{let s=Ma(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=gN.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 Wa.YAMLParseError(Ma(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 Wa.YAMLParseError(Ma(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=wN.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 Wa.YAMLParseError(Ma(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 hN.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}}};Sb.Composer=gm});var xb=I(du=>{"use strict";var yN=dm(),vN=pm(),kN=qa(),Cb=Sa();function bN(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 kN.YAMLParseError([c,c+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return vN.resolveFlowScalar(e,t,r);case"block-scalar":return yN.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function RN(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:s=-1,type:o="PLAIN"}=t,c=Cb.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),u=c.substring(f+1)+`
|
|
112
|
+
`,p=[{type:"block-scalar-header",offset:s,indent:r,source:a}];return Eb(p,l)||p.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:s,indent:r,props:p,source:u}}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 SN(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=Cb.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">":CN(e,l);break;case'"':ym(e,l,"double-quoted-scalar");break;case"'":ym(e,l,"single-quoted-scalar");break;default:ym(e,l,"scalar")}}function CN(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}];Eb(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 Eb(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 ym(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})}}}du.createScalarToken=RN;du.resolveAsScalar=bN;du.setScalarValue=SN});var Ib=I(Ab=>{"use strict";var EN=e=>"type"in e?pu(e):fu(e);function pu(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=pu(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=fu(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=fu(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=fu(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 fu({start:e,key:t,sep:n,value:r}){let i="";for(let s of e)i+=s.source;if(t&&(i+=pu(t)),n)for(let s of n)i+=s.source;return r&&(i+=pu(r)),i}Ab.stringify=EN});var Tb=I(Ob=>{"use strict";var vm=Symbol("break visit"),xN=Symbol("skip children"),_b=Symbol("remove item");function Gi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Pb(Object.freeze([]),e,t)}Gi.BREAK=vm;Gi.SKIP=xN;Gi.REMOVE=_b;Gi.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};Gi.parentCollection=(e,t)=>{let n=Gi.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 Pb(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=Pb(Object.freeze(e.concat([[i,o]])),s.items[o],n);if(typeof c=="number")o=c-1;else{if(c===vm)return vm;c===_b&&(s.items.splice(o,1),o-=1)}}typeof r=="function"&&i==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Ob.visit=Gi});var mu=I(sn=>{"use strict";var km=xb(),AN=Ib(),IN=Tb(),bm="\uFEFF",Rm="",Sm="",Cm="",_N=e=>!!e&&"items"in e,PN=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 bm:return"<BOM>";case Rm:return"<DOC>";case Sm:return"<FLOW_END>";case Cm:return"<SCALAR>";default:return JSON.stringify(e)}}function TN(e){switch(e){case bm:return"byte-order-mark";case Rm:return"doc-mode";case Sm:return"flow-error-end";case Cm: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}sn.createScalarToken=km.createScalarToken;sn.resolveAsScalar=km.resolveAsScalar;sn.setScalarValue=km.setScalarValue;sn.stringify=AN.stringify;sn.visit=IN.visit;sn.BOM=bm;sn.DOCUMENT=Rm;sn.FLOW_END=Sm;sn.SCALAR=Cm;sn.isCollection=_N;sn.isScalar=PN;sn.prettyToken=ON;sn.tokenType=TN});var Am=I($b=>{"use strict";var Fa=mu();function zn(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Nb=new Set("0123456789ABCDEFabcdef"),NN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),hu=new Set(",[]{}"),$N=new Set(` ,[]{}
|
|
121
|
+
\r `),Em=e=>!e||$N.has(e),xm=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==="...")&&zn(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]===Fa.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 Fa.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==="...")&&zn(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&&!zn(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===":")&&zn(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(Em),"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("..."))&&zn(i[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Fa.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(Em),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||zn(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=>zn(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 Fa.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(zn(s)||t&&hu.has(s))break;n=r}else if(zn(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&&hu.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&&hu.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Fa.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(Em),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(zn(r)||n&&hu.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(;!zn(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(NN.has(n))n=this.buffer[++t];else if(n==="%"&&Nb.has(this.buffer[t+1])&&Nb.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)}};$b.Lexer=xm});var _m=I(jb=>{"use strict";var Im=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}}}};jb.LineCounter=Im});var Om=I(Mb=>{"use strict";var jN=kl("process"),Db=mu(),DN=Am();function ni(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function qb(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 Wb(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 gu(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 uo(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 wu(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 Lb(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!ni(t.start,"explicit-key-ind")&&!ni(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Wb(t.value)?t.value.end?wu(t.value.end,t.sep):t.value.end=t.sep:wu(t.start,t.sep),delete t.sep)}var Pm=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,jN.env.LOG_TOKENS&&console.log("|",Db.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=Db.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"&&Lb(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&&qb(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":{qb(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=gu(this.peek(2)),r=uo(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)){wu(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(ni(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(Wb(n.key)&&!ni(n.sep,"newline")){let o=uo(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(ni(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=uo(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]}):ni(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&&!ni(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)){wu(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||ni(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=gu(r),s=uo(i);Lb(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=gu(t),r=uo(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=gu(t),r=uo(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())}}};Mb.Parser=Pm});var Ub=I(Ba=>{"use strict";var Fb=wm(),qN=$a(),Ha=qa(),LN=hp(),WN=Ee(),MN=_m(),Hb=Om();function Bb(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new MN.LineCounter||null,prettyErrors:t}}function FN(e,t={}){let{lineCounter:n,prettyErrors:r}=Bb(t),i=new Hb.Parser(n?.addNewLine),s=new Fb.Composer(t),o=Array.from(s.compose(i.parse(e)));if(r&&n)for(let c of o)c.errors.forEach(Ha.prettifyError(e,n)),c.warnings.forEach(Ha.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Vb(e,t={}){let{lineCounter:n,prettyErrors:r}=Bb(t),i=new Hb.Parser(n?.addNewLine),s=new Fb.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 Ha.YAMLParseError(c.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(Ha.prettifyError(e,n)),o.warnings.forEach(Ha.prettifyError(e,n))),o}function HN(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let i=Vb(e,n);if(!i)return null;if(i.warnings.forEach(s=>LN.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 BN(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 WN.isDocument(e)&&!r?e.toString(n):new qN.Document(e,r,n).toString(n)}Ba.parse=HN;Ba.parseAllDocuments=FN;Ba.parseDocument=Vb;Ba.stringify=BN});var _t=I(Ne=>{"use strict";var VN=wm(),UN=$a(),KN=Xp(),Tm=qa(),zN=ya(),ri=Ee(),JN=Qr(),GN=pt(),YN=ei(),XN=ti(),QN=mu(),ZN=Am(),e$=_m(),t$=Om(),yu=Ub(),Kb=ma();Ne.Composer=VN.Composer;Ne.Document=UN.Document;Ne.Schema=KN.Schema;Ne.YAMLError=Tm.YAMLError;Ne.YAMLParseError=Tm.YAMLParseError;Ne.YAMLWarning=Tm.YAMLWarning;Ne.Alias=zN.Alias;Ne.isAlias=ri.isAlias;Ne.isCollection=ri.isCollection;Ne.isDocument=ri.isDocument;Ne.isMap=ri.isMap;Ne.isNode=ri.isNode;Ne.isPair=ri.isPair;Ne.isScalar=ri.isScalar;Ne.isSeq=ri.isSeq;Ne.Pair=JN.Pair;Ne.Scalar=GN.Scalar;Ne.YAMLMap=YN.YAMLMap;Ne.YAMLSeq=XN.YAMLSeq;Ne.CST=QN;Ne.Lexer=ZN.Lexer;Ne.LineCounter=e$.LineCounter;Ne.Parser=t$.Parser;Ne.parse=yu.parse;Ne.parseAllDocuments=yu.parseAllDocuments;Ne.parseDocument=yu.parseDocument;Ne.stringify=yu.stringify;Ne.visit=Kb.visit;Ne.visitAsync=Kb.visitAsync});import{existsSync as Nm,readFileSync as n$}from"node:fs";import xn from"node:path";function zb(e,t){let n=t.toLowerCase();return Object.entries(e).find(([r,i])=>r.toLowerCase()===n&&i!==void 0)?.[1]}function i$(e){let t=(zb(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(n=>n.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function s$(e,t,n){let i=xn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(zb(t,"PATH")??"").split(xn.delimiter).map(c=>c.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=xn.win32.extname(e)?[e]:i$(t).map(c=>`${e}${c}`);return i.flatMap(c=>o.map(l=>c?xn.join(c,l):xn.resolve(n,l)))}function fo(e,t,n){return s$(e,t,n).find(r=>Nm(r))??e}function o$(e){let t=e.replaceAll(`\r
|
|
143
|
+
`,`
|
|
144
|
+
`).trim(),n=/^@"([^"%\r\n]+)" "%~dp0([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(t);if(n&&xn.win32.isAbsolute(n[1])&&xn.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 Jb(e,t,n,r=process.execPath){let i=o$(n$(e,"utf8"));if(!i)return null;let s=i.target.replace(/^[/\\]+/u,"");if(xn.win32.parse(s).root)return null;let o=xn.resolve(xn.dirname(e),s);if(!Nm(o))throw new Error("Node CLI entry is missing: "+o);let c=xn.join(xn.dirname(e),"node.exe"),l={...n},f=Object.keys(l).find(u=>u.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??(Nm(c)?c:r),args:[o,...t],...i.nodePath?{env:l}:{}}}function Gb(e){if(e.some(t=>r$.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var r$,Pz,vu=re(()=>{"use strict";r$=/[&|<>()^%"!\r\n]/u,Pz=["$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 Yb,constants as $m,statSync as Xb,existsSync as Nz,readFileSync as $z}from"node:fs";import po from"node:path";function jm(e,t,n){if((n.platform??process.platform)!=="win32")return{command:e,args:[...t]};let r=fo(e,n.env??process.env,n.cwd),i=po.extname(r).toLowerCase();if([".mjs",".cjs",".js"].includes(i))return{command:process.execPath,args:[po.resolve(n.cwd,r),...t]};if(i===".cmd"){let s=Jb(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 ku(e,t,n){let r=jm(e,t,n),i=n.platform??process.platform,s=r.env??n.env??process.env,o=r.command;if(!(i==="win32"?[fo(o,s,n.cwd)]:o.includes("/")?[po.resolve(n.cwd,o)]:(s.PATH??"/usr/bin:/bin").split(po.delimiter).map(f=>po.resolve(n.cwd,f,o))).some(f=>{try{let a=po.resolve(n.cwd,f);return Xb(a).isFile()?(Yb(a,i==="win32"?$m.F_OK:$m.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(!Xb(f).isFile())throw new Error(`Node CLI entry is not a file: ${f}`);Yb(f,$m.R_OK)}}var Dm=re(()=>{"use strict";vu()});import{promises as a$}from"fs";async function bu(e){try{return await a$.access(e),!0}catch(t){if(c$(t))return!1;throw t}}function c$(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}var Qb=re(()=>{"use strict"});import ii from"path";function p$(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim();if(n.length===0||ii.posix.isAbsolute(n)||ii.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 Ru(e){let t=p$(e,"native.artifact_root");return t.length===0?".":t.join("/")}function sR(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 ot(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||ii.posix.isAbsolute(r)||ii.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 si(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function oR(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 m$(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 iR(e,t,n){let r=m$(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 h$(e){if(e===void 0)return;let t=si(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=si(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:Ru(r),toArtifactRoot:Ru(i),stage:s,...o?{cleanup:o}:{}}}function g$(e){if(e===void 0)return;let t=si(e,"native.finish");if(t.pull_request===void 0)return{};let n=si(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(ii.posix.isAbsolute(r[0])||ii.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??f$;if(!Number.isSafeInteger(i)||i<1||i>rR)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${rR}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:i}}}function w$(e,t={}){let n=si(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??l$;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?u$: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=h$(n.pending_root_move),a=g$(n.finish);return{artifact_root:Ru(r),language:oR(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 y$(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>nR)throw new Error(`${t} must be an integer between 1 and ${nR} milliseconds`);return e}function v$(e){let t=si(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&&y$(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:sR(t.artifact_layout),language:oR(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 k$(e){let n=si(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)=>ot(r,`hook.allow_paths[${i}]`)))]}}function b$(e){if(e===void 0)return{...qm};let t=si(e,"memory"),n=t.learning??qm.learning,r=t.retrieval??qm.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 Lm(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function R$(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")||ii.posix.isAbsolute(n)||ii.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>Zb)throw new Error(`${t} exceeds ${Zb} 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>eR)throw new Error(`${t} contains more than ${eR} wildcard tokens`);return n}function S$(e){let t=Lm(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)=>R$(i,`knowledge.local.include[${s}]`)))],max_file_mb:iR(t.max_file_mb,tR.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:iR(t.max_total_mb,tR.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 C$(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=Lm(e,"knowledge.remote"),n=C$(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 x$(e){if(e===void 0)return{...d$};let t=Lm(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:S$(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 aR(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function A$(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function I$(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 u=[...new Set(a)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,change_walkthrough:aR(e.change_walkthrough),...t?{hook:t}:{},memory:n,knowledge:r,...i?{native:i}:{},...s?{classic:s}:{}}}function cR(e){let t=(0,An.parseDocument)(e),n=r=>{let i=(0,An.isAlias)(r)?r.resolve(t):r;return(0,An.isScalar)(i)?i.value:void 0};return(0,An.isMap)(t.contents)&&t.contents.items.some(({key:r,value:i})=>n(r)==="schema"&&n(i)==="comet.project.v1")}function Xi(e,t={}){let n=(0,An.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=A$(i.ambient_resume),o=aR(i.change_walkthrough),c=i.hook===void 0?void 0:k$(i.hook),l=b$(i.memory),f=x$(i.knowledge),a=i.native===void 0?void 0:w$(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=i.classic===void 0?void 0:v$(i.classic),p=I$(i,c,l,f,a,u,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}:{},...u?{classic:u}:{}}}var An,Yi,Zb,eR,l$,u$,qm,tR,d$,nR,f$,rR,bn=re(()=>{"use strict";An=St(_t(),1),Yi=Number.MAX_SAFE_INTEGER,Zb=1024,eR=64,l$=5,u$=2,qm={learning:!0,retrieval:!0},tR={include:[],max_file_mb:1,max_total_mb:32},d$={provider:"local"},nR=36e5,f$=12e4,rR=6e5});function oi(e){return e!==0&&e!==0n&&e!=="0"}function Su(e,t){return oi(e.dev)&&oi(t.dev)&&oi(e.ino)&&oi(t.ino)}function In(e,t){let n=oi(e.dev)&&oi(t.dev);if(n&&e.dev!==t.dev)return!1;let r=oi(e.ino)&&oi(t.ino);return r&&e.ino!==t.ino?!1:n&&r?!0:e.birthtime===t.birthtime}var Va=re(()=>{"use strict"});import{constants as ai,promises as on}from"fs";import{createHash as _$}from"node:crypto";function Wm(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Cu(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function li(e){return{dev:e.dev,ino:e.ino,birthtime:Wm(e)}}function P$(e,t){let n=li(e),r=li(t);return Su(n,r)?In(n,r):In(n,r)&&Wm(e)===Wm(t)&&Cu(e)===Cu(t)&&e.size===t.size}function ci(e,t){let n=r=>"mtimeNs"in r?r.mtimeNs:r.mtimeMs;return P$(e,t)&&e.size===t.size&&e.mode===t.mode&&n(e)===n(t)&&Cu(e)===Cu(t)}async function ui(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 on.lstat(e,{bigint:i});if(!s.isFile()||s.isSymbolicLink())throw new Ct("not-regular-file",`${r} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new Ct("too-large",`${r} exceeds ${t} bytes`);let o=await on.realpath(e);await n.verify?.("pre-open",{realPath:o,identity:li(s)});let c=process.platform==="win32"?ai.O_RDONLY:ai.O_RDONLY|ai.O_NOFOLLOW|ai.O_NONBLOCK,l;try{l=await on.open(e,c)}catch(f){throw f.code==="ELOOP"?new Ct("not-regular-file",`${r} must be a regular file`,{cause:f}):f}try{let[f,a,u]=await Promise.all([l.stat({bigint:i}),on.lstat(e,{bigint:i}),on.realpath(e)]);if(!f.isFile()||!a.isFile()||a.isSymbolicLink()||u!==o||!ci(s,f)||!ci(s,a))throw new Ct("changed",`${r} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:li(f)}),await n.hooks?.afterOpen?.();let p=[],d=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-d,{bytesRead:R}=await l.read(m,0,Math.min(m.length,y),null);if(R===0)break;if(d+=R,d>t)throw new Ct("too-large",`${r} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,R)))}let h=Buffer.concat(p,d);if(await n.hooks?.beforeFinalCheck?.(),process.platform==="win32"){let y=0;for(;;){let{bytesRead:R}=await l.read(m,0,Math.min(m.length,d+1-y),y);if(R===0&&y===d)break;if(R===0||y+R>d||!m.subarray(0,R).equals(h.subarray(y,y+R)))throw new Ct("changed",`${r} changed while reading`);y+=R}}let[g,w,k]=await Promise.all([l.stat({bigint:i}),on.lstat(e,{bigint:i}),on.realpath(e)]);if(!w.isFile()||w.isSymbolicLink()||k!==o||!ci(s,g)||!ci(s,w))throw new Ct("changed",`${r} changed while reading`);return await n.verify?.("post-read",{realPath:k,identity:li(g)}),{bytes:h,stat:g,realPath:k}}finally{await l.close()}}async function uR(e,t={}){let n=t.label??"file",r=t.bigint===!0,i=await on.lstat(e,{bigint:r});if(!i.isFile()||i.isSymbolicLink())throw new Ct("not-regular-file",`${n} must be a regular file`);let s=await on.realpath(e);await t.verify?.("pre-open",{realPath:s,identity:li(i)});let o=process.platform==="win32"?ai.O_RDONLY:ai.O_RDONLY|ai.O_NOFOLLOW|ai.O_NONBLOCK,c;try{c=await on.open(e,o)}catch(l){throw l.code==="ELOOP"?new Ct("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,f,a]=await Promise.all([c.stat({bigint:r}),on.lstat(e,{bigint:r}),on.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||a!==s||!ci(i,l)||!ci(i,f))throw new Ct("changed",`${n} changed while opening`);await t.verify?.("post-open",{realPath:a,identity:li(l)}),await t.hooks?.afterOpen?.();let u=t.algorithm??"sha256",p=await lR(c,u);if(await t.hooks?.beforeFinalCheck?.(),process.platform==="win32"&&await lR(c,u)!==p)throw new Ct("changed",`${n} changed while reading`);let[d,m,h]=await Promise.all([c.stat({bigint:r}),on.lstat(e,{bigint:r}),on.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||h!==s||!ci(i,d)||!ci(i,m))throw new Ct("changed",`${n} changed while reading`);return await t.verify?.("post-read",{realPath:h,identity:li(d)}),{digest:p,stat:d,realPath:h}}finally{await c.close()}}async function lR(e,t){let n=_$(t),r=Buffer.allocUnsafe(64*1024),i=0;for(;;){let{bytesRead:s}=await e.read(r,0,r.length,i);if(s===0)break;n.update(r.subarray(0,s)),i+=s}return n.digest("hex")}var Ct,Qi=re(()=>{"use strict";Va();Ct=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 Eu(){let e=Mm.getStore();return e?.active?e:null}function dR(){Eu()?.entries.clear()}async function fR(e){if(Eu()!==null)return e();let t={entries:new Map,active:!0};return Mm.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function di(e){return Mm.run({entries:new Map,active:!1},e)}function pR(e,t){let n=e;for(let r of t)n+="\0"+(typeof r=="string"?r:JSON.stringify(r));return n}function Et(e,t){return(...n)=>{let r=Eu();if(r===null)return t(...n);let i=pR(`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 fr(e,t){return(...n)=>{let r=Eu();if(r===null)return t(...n);let i=pR(`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 Mm,Jn=re(()=>{"use strict";Mm=new O$});import{promises as an}from"fs";import $e from"path";import{AsyncLocalStorage as T$}from"node:async_hooks";async function Ua(e,t,n={}){let r=$e.resolve(e),i=await Hm(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,d)=>JSON.stringify((await an.readdir(p,{withFileTypes:!0})).filter(m=>!d(m)).map(m=>[m.name,m.isDirectory(),m.isSymbolicLink()]).sort((m,h)=>String(m[0]).localeCompare(String(h[0]),"en"))),a=p=>{let d=s.get(p);return d||(d=(async()=>{let m=await an.lstat(p,{bigint:!0});if(!m.isDirectory()||m.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${$e.relative(r,p)||"."}`);let h=await an.realpath(p);if(!mo(i,h))throw new Error(`${t} resolves outside the project root`);let g=n.ignoredDirectoryEntries?.($e.relative(r,p).replaceAll("\\","/")||".");return{stat:m,real:h,...g?{ignoreEntry:g,namespace:await f(p,g)}:{}}})(),d=d.catch(m=>{throw s.delete(p),m}),s.set(p,d)),d};await a(r);let u=async p=>{if(o)throw new Error(`${t} read session is already finished`);let d=ot(p,t),m=r;for(let h of d.split("/").slice(0,-1))m=$e.join(m,h),await a(m);return $e.resolve(r,...d.split("/"))};return{observePath:u,async observeDirectory(p){let d=await u(p);return await a(d),d},async stat(p){let d=await u(p),m=await an.lstat(d,{bigint:!0});if(!m.isFile()||m.isSymbolicLink())throw new Error(`${t} must be a real file: ${p}`);return{target:d,stat:m}},async hash(p){let d=await u(p);return uR(d,{bigint:!0,label:`${t} ${p}`,verify:async(m,h)=>{if(!mo(i,h.realPath))throw new Error(`${t} resolves outside the project root`);let g=r,w=[r];for(let k of $e.relative(r,$e.dirname(d)).split($e.sep).filter(Boolean))g=$e.join(g,k),w.push(g);for(let k of w){let y=await s.get(k),R=await an.lstat(k,{bigint:!0});if(!R.isDirectory()||R.isSymbolicLink()||l(R)!==l(y.stat))throw new Error(`${t} directory changed while reading: ${$e.relative(r,k)||"."}`)}}})},async read(p,d,m={}){let h=await u(p);return ui(h,d,{...m,label:`${t} ${p}`,verify:async(g,w)=>{if(!mo(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 $e.relative(r,$e.dirname(h)).split($e.sep).filter(Boolean))k=$e.join(k,R),y.push(k);for(let R of y){let S=await s.get(R),C=await an.lstat(R,{bigint:!0});if(!C.isDirectory()||C.isSymbolicLink()||l(C)!==l(S.stat))throw new Error(`${t} directory changed while reading: ${$e.relative(r,R)||"."}`)}}})},async finish(p={}){if(o)throw new Error(`${t} read session is already finished`);o=!0;let d=[];for(let[m,h]of s){let g=await h,w=await an.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 an.realpath(m)!==g.real)throw new Error(`${t} directory changed while observing: ${$e.relative(r,m)||"."}`);c(g.stat)!==c(w)&&d.push($e.relative(r,m).replaceAll("\\","/")||".")}return{changedDirectories:d}}}}function mR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function mo(e,t){let n=$e.relative(e,t);return n===""||!$e.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${$e.sep}`)}async function Hm(e,t){let n=$e.resolve(e),r=await hR(n);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return gR(n)}async function wR(e,t,n,r){let i=e;for(let s=0;s<n.length;s++){i=$e.join(i,n[s]);let o;try{o=await hR(i)}catch(f){if(mR(f))return{exists:!1,kind:"missing"};throw f}if(o.isSymbolicLink()){let f=$e.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=$e.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 gR(i);if(!$$(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 yR(e,t,n){let r=ot(t,n.label),i=$e.resolve(e),s=await Hm(i,n.label),o=r.split("/"),c=$e.resolve(i,...o);if(!mo(i,c))throw new Error(`${n.label} must stay inside the project root`);let l=await wR(i,s,o,n);return{projectRoot:i,target:c,relative:r,exists:l.exists,kind:l.kind}}async function V(e,t,n){if(n.expected===void 0)return yR(e,t,n);try{return await j$(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 Pt(e,t,n){let r=ot(t,n.label),i=$e.resolve(e),s=await Hm(i,n.label),o=r.split("/"),c=i;for(let l of o){c=$e.join(c,l);let f;try{f=await an.lstat(c)}catch(p){if(!mR(p))throw p;try{await an.mkdir(c)}catch(d){if(d.code!=="EEXIST")throw d}f=await an.lstat(c)}let a=$e.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 u=await an.realpath(c);if(!mo(s,u))throw new Error(`${n.label} resolves outside the project root`)}return await wR(i,s,o,{label:n.label,expected:"directory"}),c}async function Bm(e,t,n){return(await V(e,t,{...n,expected:"file"})).exists}async function vR(e,t,n,r){let i=!r.hooks&&!r.bigint?N$.getStore():void 0;if(i){let c=$e.resolve(e),l=i.get(c);return l||(l=Ua(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 Ua(e,r.label),o=await s.read(t,n,r);return await s.finish({allowDirectoryContentChanges:!0}),o}async function ue(e,t,n,r){if(r.hooks||r.bigint)return vR(e,t,n,r);try{return await D$(e,t,n)}catch(i){throw i instanceof Error&&i.message.includes(Fm)&&(i.message=i.message.replaceAll(Fm,r.label)),i}}var N$,hR,gR,$$,j$,Fm,D$,Re=re(()=>{"use strict";Qi();bn();Jn();N$=new T$;hR=Et("protectedChainLstat",e=>an.lstat(e)),gR=Et("protectedChainRealpath",e=>an.realpath(e)),$$=fr("protectedChainInside",mo);j$=Et("protectedInspectPath",(e,t,n)=>yR(e,t,{label:"Protected project path",expected:n}));Fm="Cached protected project read",D$=Et("protectedReadFile",(e,t,n)=>vR(e,t,n,{label:Fm}))});import{createHash as q$}from"crypto";function L$(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ho(e,t={}){return(await xu(e,t)).document}async function W$(e){try{return(await ue(e,Ka,Yi,{label:Ka})).bytes}catch(t){if(L$(t))return null;throw t}}function M$(e){return e?{exists:!0,sha256:q$("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function xu(e,t={}){let n=await W$(e);return{source:n?.toString("utf8")??null,document:n?Xi(n.toString("utf8"),t):null,identity:M$(n)}}async function Vm(e){return(await ho(e))?.config??null}var Ka,Zi=re(()=>{"use strict";bn();Re();Ka=".comet/config.yaml"});import{promises as Km}from"node:fs";async function zm(e,t){let n;for(let r=0;r<=Um.length;r+=1)try{return await e()}catch(i){n=i;let s=i.code;if(r===Um.length||!F$.has(s??""))throw i;await new Promise(o=>setTimeout(o,Um[r]))}throw n}async function Jm(e,t){await zm(()=>Km.rename(e,t),`rename ${t}`)}async function Gm(e){await zm(()=>Km.unlink(e),`unlink ${e}`)}async function Au(e,t){await zm(()=>Km.link(e,t),`link ${t}`)}var F$,Um,kR=re(()=>{"use strict";F$=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Um=[50,100,200]});import{randomUUID as bR}from"crypto";import{constants as H$,promises as Je}from"fs";import Qe from"path";async function Ym(e,t){try{return await Au(e,t),{linked:!0}}catch(n){let r=n.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw n}return await Je.copyFile(e,t,H$.COPYFILE_EXCL),{linked:!1}}function ts(e,t){let n=Qe.relative(e,t);return n===""||!Qe.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Qe.sep}`)}function Iu(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function B$(e,t){return In(e,Iu(t))}function es(e,t){return In(Iu(e),Iu(t))}function RR(e,t){return es(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function _u(e){let t=await Je.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 Je.realpath(e),...Iu(t)}}async function qt(e){for(let t of e){let n=await Je.lstat(t.path);if(!n.isDirectory()||n.isSymbolicLink()||!B$(t,n)||await Je.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([Je.lstat(e),Je.realpath(e),qt(n)]);if(!r.isFile()||r.isSymbolicLink()||!es(r,t)||!ts(n[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return r}async function SR(e,t){let n=await Xm(e,t);if(n)return n;let r=Qe.resolve(e),i=Qe.resolve(t);if(!ts(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let s=[await _u(r)],o=Qe.relative(r,i).split(Qe.sep).filter(Boolean),c=r;for(let l of o){await qt(s),c=Qe.join(c,l);try{await Je.mkdir(c)}catch(a){if(a.code!=="EEXIST")throw a}let f=await _u(c);if(!ts(s[0].realPath,f.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${c}`);s.push(f)}return await qt(s),s}async function Xm(e,t){let n=Qe.resolve(e),r=Qe.resolve(t);if(!ts(n,r))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await _u(n)],s=Qe.relative(n,r).split(Qe.sep).filter(Boolean),o=n;for(let c of s){o=Qe.join(o,c);try{let l=await _u(o);if(!ts(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 qt(i),i}async function Qm(e){let t;try{t=await Je.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 U$(e,t,n){let r=Qe.dirname(e),i=await SR(n.containedRoot,r),s=Qe.join(r,`.${Qe.basename(e)}.${bR()}.tmp`),o,c,l;try{await n.beforeTemporaryOpen?.(),o=await Je.open(s,"wx"),c=await o.stat();let[f,a]=await Promise.all([Je.lstat(s),Je.realpath(s)]);if(await qt(i),!f.isFile()||f.isSymbolicLink()||!es(c,f)||!ts(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(),!es(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 qt(i);let u=await Je.lstat(s);if(!u.isFile()||u.isSymbolicLink()||!l||!RR(u,l))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(n.requireAtomicPublication?await Au(s,e):await Ym(s,e),await Je.unlink(s)):await Jm(s,e),await Qm(r)}catch(f){await o?.close();try{await qt(i),await Je.rm(s,{force:!0})}catch{}throw f}}async function We(e,t,n){await U$(e,t,n)}async function CR(e,t,n){let r=await Xm(n.containedRoot,Qe.dirname(e));if(!r)throw Object.assign(new Error("Contained link source directory is missing"),{code:"ENOENT"});let i=await SR(n.containedRoot,Qe.dirname(t)),s=await Je.lstat(e);if(!s.isFile()||s.isSymbolicLink())throw new Error("Contained link source must be a regular file");let o=Qe.join(Qe.dirname(t),`.${Qe.basename(t)}.${bR()}.tmp`);try{await qt(r),await qt(i),await Au(e,o),await n.beforeCommit?.(),await qt(r),await qt(i);let c=await Je.lstat(o),l=await Je.lstat(e);if(!c.isFile()||c.isSymbolicLink()||!l.isFile()||l.isSymbolicLink()||!es(s,l)||!es(l,c)||s.size!==l.size||s.mtimeMs!==l.mtimeMs)throw new Error("Contained link source changed before publication");let f=await Je.lstat(t).catch(a=>{if(a.code==="ENOENT")return null;throw a});f?.isFile()&&!f.isSymbolicLink()&&es(l,f)?await Gm(o):await Jm(o,t),await Qm(Qe.dirname(t)),await qt(r),await qt(i)}catch(c){try{await qt(i),await Je.unlink(o)}catch{}throw c}}async function pr(e,t){let n=Qe.dirname(e),r=await Xm(t.containedRoot,n);if(!r)return!1;let i,s;try{i=await Je.lstat(e),s=await Je.realpath(e)}catch(l){if(l.code==="ENOENT")return!1;throw l}if(!i.isFile()||i.isSymbolicLink()||!ts(r[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await qt(r);let[o,c]=await Promise.all([Je.lstat(e),Je.realpath(e)]);if(!o.isFile()||o.isSymbolicLink()||!RR(i,o)||c!==s)throw new Error("Contained file removal target changed before removal");return await Gm(e),await qt(r),await Qm(n),!0}var cn=re(()=>{"use strict";kR();Va()});var wJ,Zm=re(()=>{"use strict";cn();Zi();Re();wJ=Number.MAX_SAFE_INTEGER});var th=re(()=>{"use strict";cn();bn();Zi();Re();Zm()});import{promises as IR}from"fs";import tt from"path";import Y$ from"os";function nh(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Pu(e,t){let n=tt.resolve(e),r=t==="docs"?tt.join(n,"docs"):n,i=tt.join(r,"openspec"),s=tt.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:t,openSpecBase:r,openSpecRoot:i,changesDir:tt.join(i,"changes"),archiveDir:tt.join(i,"changes","archive"),specsDir:tt.join(i,"specs"),superpowersRoot:s,superpowersSpecsDir:tt.join(s,"specs"),superpowersPlansDir:tt.join(s,"plans"),superpowersReportsDir:tt.join(s,"reports")}}async function X$(e){let t=await ho(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new za;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new za("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function Gn(e,t){return Pu(e,t??await X$(e))}async function Q$(e){try{return await IR.lstat(e),!0}catch(t){if(nh(t))return!1;throw t}}async function Z$(e,t){let n=await Gn(e,t),r=n.artifactLayout==="legacy"?"docs":"legacy",i=Pu(e,r).openSpecRoot,[s,o]=await Promise.all([V(n.projectRoot,at(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Q$(i)]),c=s.exists;return{paths:n,configuredRootExists:c,alternateRoot:i,alternateRootExists:o,dualRoots:c&&o}}async function ej(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=at(e.projectRoot,n);await V(e.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Gt(e,t){let n=await Z$(e,t);if(await ej(n.paths),!n.configuredRootExists){let r=at(n.paths.projectRoot,n.paths.openSpecRoot),i=at(n.paths.projectRoot,n.alternateRoot);throw new za(`Configured Classic OpenSpec root is missing: ${r} (alternate ${i} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function Tr(e,t){let n=tt.join(tt.resolve(e),".comet","classic-root-move.json");if(await bu(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await Gt(e,t);if(!await bu(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${at(r.projectRoot,r.openSpecRoot)}`);return r}async function ct(e){let t=tt.resolve(e),n=null;try{(await IR.lstat(t)).isDirectory()||(t=tt.dirname(t))}catch(s){if(!nh(s))throw s}let r=t,i=tt.resolve(Y$.homedir());for(;;){tt.basename(t)==="openspec"&&(n=tt.dirname(t));let s=!1,o=t===i&&t!==r,c=null;if(!o)try{let{bytes:f}=await ue(t,AR,Yi,{label:AR});c=f.toString("utf8")}catch(f){if(!nh(f))throw f}if(c!==null)try{let f=Xi(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 ns(f);if(cR(c))throw new ns(f)}if(s||await bu(tt.join(t,".git")))return t;let l=tt.dirname(t);if(l===t)return n??tt.resolve(e);t=l}}function at(e,t){return tt.relative(tt.resolve(e),t).replaceAll("\\","/")}var za,ns,AR,nt=re(()=>{"use strict";Qb();bn();Zi();th();Re();za=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},ns=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="ClassicProjectConfigError"}},AR=".comet/config.yaml"});import tj from"path";async function Ou(e,t){let n=t??await Gt(e),r=tj.join(n.openSpecRoot,"config.yaml"),i=at(n.projectRoot,r),s;try{s=(await ue(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,_R.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 _R,rh=re(()=>{"use strict";_R=St(_t(),1);Re();nt()});import{spawnSync as nj}from"child_process";async function go(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 ct(t),i=await Tr(r);await Ou(r,i);let s=process.env.COMET_OPENSPEC||"openspec",o;try{ku(s,n,{cwd:i.openSpecBase}),o=jm(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=nj(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 Tu=re(()=>{"use strict";Dm();nt();rh()});import{promises as rj}from"node:fs";import ih from"node:path";function $u(e){return wo.some(t=>t===e)}async function ij(e,t={}){let n=[],r=[];for(let i of wo)try{let s=await rj.lstat(ih.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 sh(`Classic state files are ambiguous in ${e}: ${wo.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: ${ih.join(e,r[0])}`);return ih.join(e,n[0]??t.defaultFileName??PR)}async function le(e,t={}){return sj(e,t)}var PR,Nu,wo,sh,sj,Ot=re(()=>{"use strict";Jn();PR="comet-state.yaml",Nu=".comet.yaml",wo=[PR,Nu],sh=class extends Error{};sj=Et("classicStateFile",(e,t)=>ij(e,t))});import{AsyncLocalStorage as oj}from"async_hooks";import{promises as OR}from"fs";import Ja from"path";function aj(e,t){let n=Ja.relative(e,t);return n===""||!Ja.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ja.sep}`)}async function cj(e){let t=Ja.resolve(e.invocationCwd??process.cwd()),n=Ja.resolve(e.projectRoot??await ct(t)),[r,i]=await Promise.all([OR.realpath(t),OR.realpath(n)]);if(!aj(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 lj(e,t){let n=rs.getStore();if(n)return t(n);let r=await cj(e);return rs.run(r,()=>t(r))}function De(){let e=rs.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}function ju(){let e=rs.getStore();if(!e)throw new Error("Classic command invocation context is unavailable");return e.invocationCwd}async function TR(e,t){let n=rs.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 Ga(e){let t=rs.getStore();if(!t)return e();t.observations?.clear();try{return await rs.run({...t,observations:null},e)}finally{t.observations?.clear()}}function yo(e){return(t,n)=>lj(n,()=>e(t,n))}var rs,vo=re(()=>{"use strict";nt();rs=new oj});var Du=re(()=>{"use strict"});var NR=re(()=>{"use strict"});var oh=re(()=>{"use strict";Du()});var $R=re(()=>{"use strict";Du();oh()});var gj,jR=re(()=>{"use strict";gj=St(_t(),1);cn();bn();Re()});var fG,DR=re(()=>{"use strict";cn();Re();fG=Number.MAX_SAFE_INTEGER});var qR=re(()=>{"use strict"});var LR=re(()=>{"use strict"});var WR=re(()=>{"use strict";qR();LR()});var MR=re(()=>{"use strict";WR()});var _G,FR=re(()=>{"use strict";Jn();Zi();MR();_G=Et("hookWritePolicy",async e=>(await Vm(e))?.hook??{allow_paths:[]})});import{promises as wj}from"node:fs";import yj from"node:path";function ah(e){return yj.join(e,".comet","current-change.json")}function vj(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function HR(e){return e===null||typeof e=="string"}function kj(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(!vj(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&&!HR(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:qu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==qu)throw new Error(`current change selection schema must be ${qu}`);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(!HR(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 Lu(e){let t;try{let r=ah(e),{bytes:i}=await ui(r,BR,{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",...kj(t)}}async function VR(e){await wj.rm(ah(e),{force:!0})}async function ch(e,t,n){let r=await Lu(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==n?!1:(await VR(e),!0)}var qu,BR,bj,Wu=re(()=>{"use strict";Jn();Qi();qu="comet.selection.v2",BR=Number.MAX_SAFE_INTEGER;bj=Et("readCometCurrentSelection",e=>Lu(e))});var UR=re(()=>{"use strict";Du();cn();NR();$R();bn();jR();Re();Zi();th();DR();FR();Wu();Zm();oh()});import{TextDecoder as Sj}from"util";function KR(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function Cj(e,t){try{return new Sj("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t} is not valid UTF-8`,{cause:n})}}async function lh(e,t,n,r,i={}){try{let s=await ue(e,t,n,{label:r,hooks:i.hooks});return{result:s,text:Cj(s,r)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function is(e,t,n,r,i={}){return(await lh(e,t,n,r,i))?.text??null}async function ss(e,t,n,r,i,s={}){if(Buffer.byteLength(n,"utf8")>r)throw new Error(`${i} exceeds ${r} bytes`);let o=await lh(e,t,r,i),c=await V(e,t,{label:i,expected:"file"});await We(c.target,n,{containedRoot:c.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let l=await lh(e,t,r,i);if(!(!o&&!l)){if(!o||!l)throw new Error(`${i} changed before commit`);if(o.result.realPath!==l.result.realPath||!In(KR(o.result.stat),KR(l.result.stat))||o.text!==l.text)throw new Error(`${i} changed before commit`)}}})}async function Mu(e,t,n,r,i,s={}){let o=await is(e,t,r,i);await ss(e,t,`${o??""}${n}`,r,i,s)}async function Fu(e,t,n,r={}){let i=await V(e,t,{label:n,expected:"file"});return i.exists?pr(i.target,{containedRoot:i.projectRoot,beforeRemove:r.beforeRemove}):!1}var Hu=re(()=>{"use strict";UR();Va()});var GR={};AP(GR,{RUN_STATE_FILE:()=>Bu,applyRunStateToDocument:()=>uh,readRunState:()=>Qa,removeRunState:()=>Za,runStateFromDocument:()=>os,writeRunState:()=>as});import Ej from"path";function Xa(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 Ya(e,t){let n=Xa(e,t);if(Ej.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 xj(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 os(e){if(!e.run_id)return null;let t=Xa(e,"run_id"),n=Xa(e,"skill"),r=Xa(e,"skill_version"),i=Xa(e,"skill_hash"),s=Ya(e,"pending_ref"),o=Ya(e,"trajectory_ref"),c=Ya(e,"context_ref"),l=Ya(e,"artifacts_ref"),f=Ya(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:zR(e,"current_step"),iteration:a,pending:zR(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:c,artifactsRef:l,checkpointRef:f,status:e.run_status,retries:xj(e)}}function uh(e,t){t?e.run_id=t.runId:delete e.run_id}function Aj(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 Ij(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 os(t)}async function Qa(e,t={}){let n=await is(e,Bu,JR,"Run state",t);if(n===null)return null;let r=JSON.parse(n);return Ij(r)}async function as(e,t,n={}){await ss(e,Bu,JSON.stringify(Aj(t),null,2),JR,"Run state",n)}async function Za(e,t={}){await Fu(e,Bu,"Run state",t)}var zR,Bu,JR,Vu=re(()=>{"use strict";Hu();zR=(e,t)=>{let n=e[t];return n==null?null:String(n)};Bu=".comet/run-state.json",JR=Number.MAX_SAFE_INTEGER});function Lt(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}function dh(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ko(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 Yt(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 fh(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 XR(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 Uu(e,t){let n=ko(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 Bj(e,t){let n=ko(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 Vj(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==cs)throw new Error(`Invalid Classic state: classic_migration must be ${cs}`);return t}function Uj(e){if(!mr.some(n=>dh(e,n)))return null;for(let n of QR)if(!dh(e,n))return null;return{workflow:Yt(e,"workflow",YR,!1),language:Yt(e,"language",Pj),phase:Yt(e,"phase",_j,!1),contextCompression:Yt(e,"context_compression",Oj),buildMode:Yt(e,"build_mode",Tj),buildPause:Yt(e,"build_pause",Nj),subagentDispatch:Yt(e,"subagent_dispatch",$j),tddMode:Yt(e,"tdd_mode",jj),reviewMode:Yt(e,"review_mode",Dj),isolation:Yt(e,"isolation",qj),boundBranch:ko(e,"bound_branch"),verifyMode:Yt(e,"verify_mode",Lj),autoTransition:fh(e,"auto_transition"),baseRef:ko(e,"base_ref"),designDoc:Uu(e,"design_doc"),plan:Uu(e,"plan"),verifyResult:Yt(e,"verify_result",Wj,!1),verifyFailures:XR(e,"verify_failures"),...dh(e,"check_epoch")?{checkEpoch:XR(e,"check_epoch")}:{},verificationReport:Uu(e,"verification_report"),branchStatus:Yt(e,"branch_status",Mj),createdAt:ko(e,"created_at"),verifiedAt:ko(e,"verified_at"),archiveConfirmation:Yt(e,"archive_confirmation",Fj),archived:fh(e,"archived",!1),directOverride:fh(e,"direct_override"),handoffContext:Uu(e,"handoff_context"),handoffHash:Bj(e,"handoff_hash"),classicProfile:Yt(e,"classic_profile",YR),classicMigration:Vj(e)}}function ln(e,t){if(e.change_id!==void 0&&(typeof e.change_id!="string"||!ec.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=os(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:Uj(e),run:n,unknownKeys:Object.keys(e).filter(r=>!Hj.has(r))}}function Ku(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 YR,cs,ec,ph,_j,Pj,Oj,Tj,Nj,$j,jj,Dj,qj,Lj,Wj,Mj,Fj,mr,ls,Hj,QR,Tt=re(()=>{"use strict";Vu();YR=["full","hotfix","tweak"],cs=1,ec=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u,ph=`# comet-execution: managed-run
|
|
145
|
+
`;_j=["open","design","build","verify","archive"],Pj=["en","zh-CN"],Oj=["off","beta"],Tj=["subagent-driven-development","executing-plans","direct","autonomous"],Nj=["plan-ready"],$j=["confirmed"],jj=["tdd","direct"],Dj=["off","standard","thorough"],qj=["current","branch","worktree"],Lj=["light","full"],Wj=["pending","pass","fail"],Mj=["pending","handled"],Fj=["pending","confirmed"],mr=["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"],ls=["change_id","run_id","run_checkpoint","application_checkpoint"],Hj=new Set([...mr,...ls]),QR=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"]});import{createHash as Kj}from"node:crypto";import{lstatSync as tc,readFileSync as zj,realpathSync as ZR}from"node:fs";import Jj from"node:os";import Xt from"node:path";function mh(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function zu(e){return process.platform==="win32"?ZR.native(e):ZR(e)}function Yj(e){return Gj(e)}function Xj(e){let t=zu(Xt.resolve(e)),n=tc(t,{bigint:!0});if(!n.isDirectory())throw new Error(`工作区必须是目录:${e}`);let r=mh(n),i=(l,f)=>({projectRoot:t,workspaceId:Kj("sha256").update(JSON.stringify(["comet.workspace.v2",t,r,l,f])).digest("hex")}),s=Xt.join(t,".git"),o,c;try{let l=tc(s);if(l.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${s}`);if(l.isDirectory())o=zu(s),c=mh(tc(o,{bigint:!0}));else if(l.isFile()){let f=/^gitdir: (.+)\r?\n?$/u.exec(zj(s,"utf8"));if(!f)throw new Error(`工作区 .git 文件格式无效:${s}`);o=zu(Xt.resolve(t,f[1].trim()));let a=tc(o,{bigint:!0});if(!a.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${o}`);c=mh(a)}else throw new Error(`工作区 .git 类型无效:${s}`)}catch(l){if(l.code!=="ENOENT")throw l;try{tc(s)}catch(f){if(f.code==="ENOENT")return i(s,null);throw f}throw l}return i(o,c)}function eS(e){let t=Xt.dirname(e);if(t===e)return e;try{return Xt.join(zu(t),Xt.basename(e))}catch(n){if(n.code!=="ENOENT")throw n;return Xt.join(eS(t),Xt.basename(e))}}function hh(e){let t=Yj(e),n=process.env.COMET_DATA_DIR;if(n!==void 0&&(!n.trim()||!Xt.isAbsolute(n)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let r=Qj(n??Xt.join(Jj.homedir(),".comet")),i=Xt.relative(t.projectRoot,r);if(i===""||!Xt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xt.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${r};工作区:${t.projectRoot}`);let s=Xt.join(r,"workspaces",t.workspaceId);return{...t,dataRoot:r,workspaceRoot:s,runtimeRoot:Xt.join(s,"runtime")}}function mt(e){return hh(e).runtimeRoot}var Gj,Qj,gh=re(()=>{"use strict";Jn();Gj=fr("workspaceIdentity",Xj);Qj=fr("workspaceRuntimeParent",eS)});import{promises as nc}from"node:fs";import tS from"node:path";async function Nr(e){return mt(e)}async function wh(e){return[mt(e)]}async function nS(e){let t=tS.dirname(e);if(t!==e){await nS(t);try{await nc.mkdir(e,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r}}let n=await nc.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function hr(e){let t=mt(e);return await nS(t),t}async function rS(e,t,n){try{let r=await nc.lstat(e);if(r.isSymbolicLink())throw new Error("旧 Runtime 路径不能是符号链接:"+e);let i=r.isDirectory()?tS.join(e,".comet-runtime-migration.json"):e,s=await nc.lstat(i);if(!s.isFile()||s.isSymbolicLink())return!1;let o;try{o=JSON.parse((await ui(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 nc.readdir(e)).every(c=>c===".comet-runtime-migration.json")}catch(r){if(r.code==="ENOENT")return!1;throw r}}var un=re(()=>{"use strict";gh();Qi()});import{createHash as Zj,randomUUID as eD}from"node:crypto";import Te from"node:path";function Ju(e){let t=Zj("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 sS(e,t){let n=await le(t),r=Te.relative(e,n).replaceAll("\\","/"),i=null;try{i=(await ue(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,iS.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"||!ec.test(o)))throw new Error("Invalid Classic change_id: expected an immutable UUID");return{source:i,document:s,id:o}}async function tD(e,t){let n=await le(t),r=Te.relative(e,n).replaceAll("\\","/"),i=()=>sS(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?Ju(`classic-run:${l}`):eD();return c.get("archived")===!0||Te.basename(Te.dirname(t))==="archive"?typeof l=="string"&&l?f:Ju(`classic-archive:${r}`):(c.set("change_id",f),await We(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 vh(e,t,n={}){let r=t??await ct(e),i;try{i=await sS(r,e)}catch(m){if(m.code==="ENOENT")return null;throw m}let{document:s,id:o}=i,c=Te.relative(r,e).replaceAll("\\","/"),l=s.get("run_id"),f=s.get("archived")===!0||Te.basename(Te.dirname(e))==="archive",a=o??(typeof l=="string"&&l?Ju(`classic-run:${l}`):f?Ju(`classic-archive:${c}`):null);if(!a)return e;let u=mt(r),p=Te.parse(u).root;if(!(await V(p,Te.relative(p,u).replaceAll("\\","/"),{label:"Classic read-only Runtime root",expected:"directory"})).exists)return n.includeMissing?Te.join(u,"classic-changes",a):e;let d=await V(u,`classic-changes/${a}`,{label:"Classic read-only Run directory",expected:"directory"});return d.exists||n.includeMissing?d.target:e}async function Pe(e,t){return nD(e,t)}async function nD(e,t){let n=t??await ct(e),r=Te.relative(n,e).replaceAll("\\","/");if(r&&!(await V(n,r,{label:"Classic change directory",expected:"directory"})).exists)throw Object.assign(new Error("Classic change directory does not exist"),{code:"ENOENT"});await le(e);let i=await hr(n),s=await tD(n,e),o=Te.join(i,"classic-changes",s);return await Pt(i,Te.relative(i,o),{label:"Classic local Run directory"}),o}async function bo(e,t,n={}){let r=mt(e),i=Te.relative(r,t);if(i===""||!i.startsWith(`..${Te.sep}`)&&i!==".."&&!Te.isAbsolute(i))return n.readOnly?{root:Te.dirname(r),target:t}:(await hr(e),{root:r,target:t});let s=Te.relative(Te.resolve(e),t).replaceAll("\\","/");if(s.startsWith(".comet/runtime/"))return{root:r,target:Te.join(r,s.slice(15))};let o=/^(?:(.*)\/)?\.comet\/([^/]+)(\/.*)?$/u.exec(s);if(!o||!yh.has(o[2]))return null;if(n.readOnly){let p=Te.parse(r).root;if(!(await V(p,Te.relative(p,Te.join(r,"classic-changes")),{label:"Classic local records",expected:"directory"})).exists)return null}let c=o[1]??"";if(!(await V(e,Te.relative(e,await le(Te.join(e,c))),{label:"Classic local change identity",expected:"file"})).exists)return null;let f=Te.join(e,c),a=n.readOnly?await vh(f,e,{includeMissing:!0}):await Pe(f,e);if(!a||n.readOnly&&a===f)return null;let u=Te.relative(r,a);if(Te.isAbsolute(u)||u===".."||u.startsWith(`..${Te.sep}`))throw new Error("Classic Runtime workspace changed while resolving a change-local target");return{root:n.readOnly?Te.dirname(r):r,target:Te.join(a,".comet",o[2],o[3]??"")}}var iS,yh,fi=re(()=>{"use strict";Ot();Tt();Re();iS=St(_t(),1);cn();Re();nt();un();yh=new Set(["run-state.json","pending-action.json","trajectory.jsonl","context.md","artifacts.json","checkpoint.json","coordination.json","subagent-progress.md"])});import Ro from"path";import{AsyncLocalStorage as rD}from"node:async_hooks";async function sD(e,t){let n=iD.getStore();if(!n||n.root!==Ro.resolve(e))return null;let r=ot(t,"Classic proposal source"),i=n.files.get(r);return i||(i=n.session.read(r,rc),n.files.set(r,i)),i}async function Gu(e,t,n,r=!1){let i=Ro.resolve(e),s=Ro.isAbsolute(t)?Ro.resolve(t):Ro.resolve(i,t),o=await bo(i,s,{readOnly:!r});o&&(i=o.root,s=o.target);let c=Ro.relative(i,s).replaceAll("\\","/");return{root:i,relative:ot(c,n),target:s}}async function $r(e,t,n){let r=await Gu(e,t,n.label,n.migrate);return V(r.root,r.relative,n)}async function lt(e,t,n){try{return(await $r(e,t,{label:n.label,expected:n.expected??"any"})).exists}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function Yn(e,t,n,r){return await lt(e,t,{label:n,expected:"file"})?(await oS(e,t,{label:n,hooks:r})).byteLength>0:!1}async function oe(e,t,n){return(await oS(e,t,n)).toString("utf8")}async function oS(e,t,n){let r=await Gu(e,t,n.label);if(!n.hooks){let i=await sD(r.root,r.relative);if(i){if(i.bytes.length>(n.maxBytes??rc))throw new Error(`${n.label} exceeds the read limit`);return i.bytes}}return(await ue(r.root,r.relative,n.maxBytes??rc,{label:n.label,hooks:n.hooks})).bytes}async function Yu(e,t,n){let r=await Gu(e,t,n,!0);return Pt(r.root,r.relative,{label:n})}async function Rn(e,t,n,r){let i=await Gu(e,t,r.label,!0);await V(i.root,i.relative,{label:r.label,expected:"file"}),await We(i.target,n,{containedRoot:i.root,beforeTemporaryOpen:r.beforeTemporaryOpen,beforeCommit:r.beforeCommit,exclusive:r.exclusive})}var rc,iD,Ze=re(()=>{"use strict";fi();cn();bn();Re();rc=Number.MAX_SAFE_INTEGER,iD=new rD});import{promises as Xu}from"fs";import gr from"path";async function So(e,t){let n=[],r=new Set;async function i(s,o){let c=await $r(e,s,{label:"Classic capability directory",expected:"directory"});if(!c.exists)return;let l=await Xu.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 $r(e,a,{label:"Classic capability spec",expected:"file"})).exists&&n.push(a)}let f=(await Xu.readdir(c.target,{withFileTypes:!0})).sort((a,u)=>a.name.localeCompare(u.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 us(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 Co(e){let t=us(e);if(t)throw new Error(t)}async function Xn(e,t){Co(t);let n=[],r=async i=>(await V(e,gr.relative(e,i),{label:"Classic change directory",expected:"directory"}),le(i));for(let i of["openspec/changes","docs/openspec/changes"]){n.push(await r(gr.join(e,i,t)));let s=gr.join(e,i,"archive"),o=await Zu(e,s,t);for(let c of o??[])c===t?await r(gr.join(s,c)):aS(c,t)&&n.push(await r(gr.join(s,c)))}return n}function oD(e,t){return{label:at(e,t),directory:t}}async function Qu(e,t,n){let r=oD(e,t);if(!(await $r(e,t,{label:n,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let s=await $r(e,await le(t),{label:`${n} state`,expected:"file"});return{change:r,exists:!0,stateExists:s.exists}}function aS(e,t){return e.slice(11)===t&&aD.test(e)}async function Zu(e,t,n){Co(n);let r=()=>V(e,gr.relative(e,t),{label:"Classic Archive directory",expected:"directory"}),i=await r();if(!i.exists)return null;let s=async()=>{let l=await Xu.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 TR(`classic-archive:${JSON.stringify([i.target,n,o])}`,async()=>{let l=await Xu.readdir(i.target);if(await s()!==o)throw new Error("Classic Archive directory changed while inspecting state files");return l.filter(f=>f===n||aS(f,n))});if(!(await r()).exists||await s()!==o)throw new Error("Classic Archive directory changed while inspecting state files");return c}async function cD(e,t,n,r={}){if(!r.skipExactCompatibility){let o=await Qu(e,gr.join(t,n),`Classic archived change ${n}`);if(o.exists)return o.change}let i=await Zu(e,t,n),s=[];for(let o of i??[]){if(o===n)continue;let c=await Qu(e,gr.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 cS(e,t=process.cwd()){Co(e);let n=await Gt(t),r=await Qu(n.projectRoot,gr.join(n.changesDir,e),`Classic active change ${e}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}async function Qn(e,t=process.cwd()){Co(e);let n=await Gt(t),r=await Qu(n.projectRoot,gr.join(n.changesDir,e),`Classic active change ${e}`);if(r.exists)return r.change;let i=await cD(n.projectRoot,n.archiveDir,e);return i||r.change}var aD,_n=re(()=>{"use strict";Ot();vo();Re();nt();Ze();aD=/^\d{4}-\d{2}-\d{2}-/u});import Pn from"node:path";async function dS(e,t){let n=await pi(e,t);if(n.problems.length)throw new Error(n.problems.join(`
|
|
147
|
+
`));n.source!=="legacy"&&await Rn(e,Pn.join(t,uS),JSON.stringify({schema:"comet.classic.archive-requirements.v1",files:n.files.map(r=>Pn.relative(t,r).replaceAll("\\","/"))})+`
|
|
148
|
+
`,{label:"Classic archive requirements"})}async function Eo(e,t){let n=Pn.join(t,uS),r=["proposal.md","design.md","tasks.md"];if(await lt(e,n,{label:"Classic archive requirements",expected:"file"})){let s=JSON.parse(await oe(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 Yn(e,Pn.join(t,s),"Classic archived required file")||i.push(`Required archived artifact is missing or empty: ${s}`);return i}function lD(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 pi(e,t,n){let r=Pn.join(t,".openspec.yaml");if(!await lt(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(u=>Pn.join(t,u)),problems:[]}}let i=(0,lS.parseDocument)(await oe(e,r,{label:"OpenSpec change metadata"}));if(i.errors.length)throw new Error(`Invalid OpenSpec metadata: ${i.errors[0].message}`);let s=await So(e,Pn.join(t,"specs")),o=n===void 0?await go(["status","--change",Pn.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"||Pn.resolve(c.changeRoot)!==Pn.resolve(t))throw new Error("OpenSpec status resolves outside the selected Classic change");let l=lD(c),f=s,a={source:"openspec",required:l.map(u=>u.id),skipped:[],designRequired:l.some(u=>u.id==="design"),files:[],problems:[]};for(let u of l){if(!["proposal","specs","design","tasks"].includes(u.id))throw new Error(`Unsupported Classic artifact: ${u.id}; use a schema with supported artifact roles`);if(u.id!=="specs"&&u.outputPath!==`${u.id}.md`)throw new Error(`Unsupported Classic artifact output: ${u.outputPath}`);if(u.status==="skipped"){if(u.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(u.id);continue}let p=u.outputPath.replaceAll("\\","/");if(Pn.posix.isAbsolute(p)||/^[A-Za-z]:/u.test(p)||p.split("/").includes(".."))throw new Error(`Unsafe OpenSpec artifact path: ${p}`);let d;if(u.id==="specs"&&["specs/**/*.md","specs/**/spec.md","specs/*/spec.md"].includes(p))d=f;else{if(["?","*","[","]","{","}"].some(m=>p.includes(m)))throw new Error(`Unsupported OpenSpec artifact pattern: ${p}`);d=[Pn.join(t,p)]}(u.status!=="done"||!d.length)&&a.problems.push(`Required OpenSpec artifact is not complete: ${u.id}`);for(let m of d)await Yn(e,m,`OpenSpec required artifact ${u.id}`)||a.problems.push(`Required OpenSpec file is missing or empty: ${m}`),a.files.push(m)}return a}var lS,uS,ic=re(()=>{"use strict";lS=St(_t(),1);Tu();_n();Ze();uS=".comet/archive-requirements.json"});import{AsyncLocalStorage as mS}from"node:async_hooks";import{performance as fS}from"node:perf_hooks";async function hS(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(pS.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 pS.run(n,e)}finally{clearInterval(i)}}function fD(e=0){uD+=1,dD+=e;for(let t of kh.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}async function gS(e){let t={gitCommands:0,gitDurationMs:0};return{result:await kh.run([...kh.getStore()??[],t],e),metrics:t}}function wr(e){let t=fS.now();try{return e()}finally{fD(fS.now()-t)}}var uD,dD,kh,pS,ds=re(()=>{"use strict";uD=0,dD=0,kh=new mS,pS=new mS});var SC=re(()=>{"use strict"});import{spawn as yY,execFileSync as Dq}from"node:child_process";import Dh from"node:path";function Wq(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function CC(e,t,n={}){let r=n.timeoutMs??qq,i=n.maxBufferBytes??Lq;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=Dh.resolve(n.cwd??process.cwd()),o=n.env??process.env,c=process.platform==="win32"?fo(e,o,s):e,l=Dh.win32.extname(c).toLowerCase(),f=l===".bat"||l===".cmd";process.platform==="win32"&&f&&Gb(t);try{let a=()=>Dq(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(Dh.win32.basename(e))?wr(a):a()}catch(a){let u=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new Ri(e,t,u,{cause:a,timedOut:Wq(a)})}}var qq,Lq,Ri,gd=re(()=>{"use strict";SC();ds();vu();qq=6e4,Lq=8*1024*1024,Ri=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}});function EC(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>{let n=t.toUpperCase();return!Mq.has(n)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(n)}))}function xC(e){return{...EC(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"}}var Mq,qh=re(()=>{"use strict";Mq=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"])});var Sc=I(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.regexpCode=Oe.getEsmExportName=Oe.getProperty=Oe.safeStringify=Oe.stringify=Oe.strConcat=Oe.addCodeArg=Oe.str=Oe._=Oe.nil=Oe._Code=Oe.Name=Oe.IDENTIFIER=Oe._CodeOrName=void 0;var bc=class{};Oe._CodeOrName=bc;Oe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var bs=class extends bc{constructor(t){if(super(),!Oe.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}}};Oe.Name=bs;var Ln=class extends bc{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 bs&&(n[r.str]=(n[r.str]||0)+1),n),{})}};Oe._Code=Ln;Oe.nil=new Ln("");function yE(e,...t){let n=[e[0]],r=0;for(;r<t.length;)eg(n,t[r]),n.push(e[++r]);return new Ln(n)}Oe._=yE;var Zh=new Ln("+");function vE(e,...t){let n=[Rc(e[0])],r=0;for(;r<t.length;)n.push(Zh),eg(n,t[r]),n.push(Zh,Rc(e[++r]));return k1(n),new Ln(n)}Oe.str=vE;function eg(e,t){t instanceof Ln?e.push(...t._items):t instanceof bs?e.push(t):e.push(S1(t))}Oe.addCodeArg=eg;function k1(e){let t=1;for(;t<e.length-1;){if(e[t]===Zh){let n=b1(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function b1(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof bs||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 bs))return`"${e}${t.slice(1)}`}function R1(e,t){return t.emptyStr()?e:e.emptyStr()?t:vE`${e}${t}`}Oe.strConcat=R1;function S1(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Rc(Array.isArray(e)?e.join(","):e)}function C1(e){return new Ln(Rc(e))}Oe.stringify=C1;function Rc(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Oe.safeStringify=Rc;function E1(e){return typeof e=="string"&&Oe.IDENTIFIER.test(e)?new Ln(`.${e}`):yE`[${e}]`}Oe.getProperty=E1;function x1(e){if(typeof e=="string"&&Oe.IDENTIFIER.test(e))return new Ln(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}Oe.getEsmExportName=x1;function A1(e){return new Ln(e.toString())}Oe.regexpCode=A1});var rg=I(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.ValueScope=hn.ValueScopeName=hn.Scope=hn.varKinds=hn.UsedValueState=void 0;var mn=Sc(),tg=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Nd;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Nd||(hn.UsedValueState=Nd={}));hn.varKinds={const:new mn.Name("const"),let:new mn.Name("let"),var:new mn.Name("var")};var $d=class{constructor({prefixes:t,parent:n}={}){this._names={},this._prefixes=t,this._parent=n}toName(t){return t instanceof mn.Name?t:this.name(t)}name(t){return new mn.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}}};hn.Scope=$d;var jd=class extends mn.Name{constructor(t,n){super(n),this.prefix=t}setValue(t,{property:n,itemIndex:r}){this.value=t,this.scopePath=(0,mn._)`.${new mn.Name(n)}[${r}]`}};hn.ValueScopeName=jd;var I1=(0,mn._)`\n`,ng=class extends $d{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?I1:mn.nil}}get(){return this._scope}name(t){return new jd(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,mn._)`${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=mn.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,Nd.Started);let a=n(f);if(a){let u=this.opts.es5?hn.varKinds.var:hn.varKinds.const;s=(0,mn._)`${s}${u} ${f} = ${a};${this.opts._n}`}else if(a=i?.(f))s=(0,mn._)`${s}${a}${this.opts._n}`;else throw new tg(f);l.set(f,Nd.Completed)})}return s}};hn.ValueScope=ng});var ge=I(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 Ce=Sc(),rr=rg(),Ii=Sc();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return Ii._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return Ii.str}});Object.defineProperty(he,"strConcat",{enumerable:!0,get:function(){return Ii.strConcat}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return Ii.nil}});Object.defineProperty(he,"getProperty",{enumerable:!0,get:function(){return Ii.getProperty}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return Ii.stringify}});Object.defineProperty(he,"regexpCode",{enumerable:!0,get:function(){return Ii.regexpCode}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return Ii.Name}});var Wd=rg();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 Ce._Code(">"),GTE:new Ce._Code(">="),LT:new Ce._Code("<"),LTE:new Ce._Code("<="),EQ:new Ce._Code("==="),NEQ:new Ce._Code("!=="),NOT:new Ce._Code("!"),OR:new Ce._Code("||"),AND:new Ce._Code("&&"),ADD:new Ce._Code("+")};var Lr=class{optimizeNodes(){return this}optimizeNames(t,n){return this}},ig=class extends Lr{constructor(t,n,r){super(),this.varKind=t,this.name=n,this.rhs=r}render({es5:t,_n:n}){let r=t?rr.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=qo(this.rhs,t,n)),this}get names(){return this.rhs instanceof Ce._CodeOrName?this.rhs.names:{}}},Dd=class extends Lr{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 Ce.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=qo(this.rhs,t,n),this}get names(){let t=this.lhs instanceof Ce.Name?{}:{...this.lhs.names};return Ld(t,this.rhs)}},sg=class extends Dd{constructor(t,n,r,i){super(t,r,i),this.op=n}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},og=class extends Lr{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},ag=class extends Lr{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},cg=class extends Lr{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},lg=class extends Lr{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=qo(this.code,t,n),this}get names(){return this.code instanceof Ce._CodeOrName?this.code.names:{}}},Cc=class extends Lr{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)||(_1(t,s.names),r.splice(i,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((t,n)=>Cs(t,n.names),{})}},Wr=class extends Cc{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},ug=class extends Cc{},Do=class extends Wr{};Do.kind="else";var Rs=class e extends Wr{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 Do(r):r}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(kE(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=qo(this.condition,t,n),this}get names(){let t=super.names;return Ld(t,this.condition),this.else&&Cs(t,this.else.names),t}};Rs.kind="if";var Ss=class extends Wr{};Ss.kind="for";var dg=class extends Ss{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=qo(this.iteration,t,n),this}get names(){return Cs(super.names,this.iteration.names)}},fg=class extends Ss{constructor(t,n,r,i){super(),this.varKind=t,this.name=n,this.from=r,this.to=i}render(t){let n=t.es5?rr.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=Ld(super.names,this.from);return Ld(t,this.to)}},qd=class extends Ss{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=qo(this.iterable,t,n),this}get names(){return Cs(super.names,this.iterable.names)}},Ec=class extends Wr{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)}};Ec.kind="func";var xc=class extends Cc{render(t){return"return "+super.render(t)}};xc.kind="return";var pg=class extends Wr{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&&Cs(t,this.catch.names),this.finally&&Cs(t,this.finally.names),t}},Ac=class extends Wr{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};Ac.kind="catch";var Ic=class extends Wr{render(t){return"finally"+super.render(t)}};Ic.kind="finally";var mg=class{constructor(t,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
150
|
+
`:""},this._extScope=t,this._scope=new rr.Scope({parent:t}),this._nodes=[new ug]}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 ig(t,s,r)),s}const(t,n,r){return this._def(rr.varKinds.const,t,n,r)}let(t,n,r){return this._def(rr.varKinds.let,t,n,r)}var(t,n,r){return this._def(rr.varKinds.var,t,n,r)}assign(t,n,r){return this._leafNode(new Dd(t,n,r))}add(t,n){return this._leafNode(new sg(t,he.operators.ADD,n))}code(t){return typeof t=="function"?t():t!==Ce.nil&&this._leafNode(new lg(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,Ce.addCodeArg)(n,i));return n.push("}"),new Ce._Code(n)}if(t,n,r){if(this._blockNode(new Rs(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 Rs(t))}else(){return this._elseNode(new Do)}endIf(){return this._endBlockNode(Rs,Do)}_for(t,n){return this._blockNode(t),n&&this.code(n).endFor(),this}for(t,n){return this._for(new dg(t),n)}forRange(t,n,r,i,s=this.opts.es5?rr.varKinds.var:rr.varKinds.let){let o=this._scope.toName(t);return this._for(new fg(s,o,n,r),()=>i(o))}forOf(t,n,r,i=rr.varKinds.const){let s=this._scope.toName(t);if(this.opts.es5){let o=n instanceof Ce.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,Ce._)`${o}.length`,c=>{this.var(s,(0,Ce._)`${o}[${c}]`),r(s)})}return this._for(new qd("of",i,s,n),()=>r(s))}forIn(t,n,r,i=this.opts.es5?rr.varKinds.var:rr.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Ce._)`Object.keys(${n})`,r);let s=this._scope.toName(t);return this._for(new qd("in",i,s,n),()=>r(s))}endFor(){return this._endBlockNode(Ss)}label(t){return this._leafNode(new og(t))}break(t){return this._leafNode(new ag(t))}return(t){let n=new xc;if(this._blockNode(n),this.code(t),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(xc)}try(t,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new pg;if(this._blockNode(i),this.code(t),n){let s=this.name("e");this._currNode=i.catch=new Ac(s),n(s)}return r&&(this._currNode=i.finally=new Ic,this.code(r)),this._endBlockNode(Ac,Ic)}throw(t){return this._leafNode(new cg(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=Ce.nil,r,i){return this._blockNode(new Ec(t,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Ec)}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 Rs))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=mg;function Cs(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function Ld(e,t){return t instanceof Ce._CodeOrName?Cs(e,t.names):e}function qo(e,t,n){if(e instanceof Ce.Name)return r(e);if(!i(e))return e;return new Ce._Code(e._items.reduce((s,o)=>(o instanceof Ce.Name&&(o=r(o)),o instanceof Ce._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 Ce._Code&&s._items.some(o=>o instanceof Ce.Name&&t[o.str]===1&&n[o.str]!==void 0)}}function _1(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function kE(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Ce._)`!${hg(e)}`}he.not=kE;var P1=bE(he.operators.AND);function O1(...e){return e.reduce(P1)}he.and=O1;var T1=bE(he.operators.OR);function N1(...e){return e.reduce(T1)}he.or=N1;function bE(e){return(t,n)=>t===Ce.nil?n:n===Ce.nil?t:(0,Ce._)`${hg(t)} ${e} ${hg(n)}`}function hg(e){return e instanceof Ce.Name?e:(0,Ce._)`(${e})`}});var xe=I(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 Me=ge(),$1=Sc();function j1(e){let t={};for(let n of e)t[n]=!0;return t}we.toHash=j1;function D1(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(CE(e,t),!EE(t,e.self.RULES.all))}we.alwaysValidSchema=D1;function CE(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]||IE(e,`unknown keyword: "${s}"`)}we.checkUnknownRules=CE;function EE(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}we.schemaHasRules=EE;function q1(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=q1;function L1({topSchemaRef:e,schemaPath:t},n,r,i){if(!i){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,Me._)`${n}`}return(0,Me._)`${e}${t}${(0,Me.getProperty)(r)}`}we.schemaRefOrVal=L1;function W1(e){return xE(decodeURIComponent(e))}we.unescapeFragment=W1;function M1(e){return encodeURIComponent(wg(e))}we.escapeFragment=M1;function wg(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}we.escapeJsonPointer=wg;function xE(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}we.unescapeJsonPointer=xE;function F1(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}we.eachItem=F1;function RE({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(i,s,o,c)=>{let l=o===void 0?s:o instanceof Me.Name?(s instanceof Me.Name?e(i,s,o):t(i,s,o),o):s instanceof Me.Name?(t(i,o,s),s):n(s,o);return c===Me.Name&&!(l instanceof Me.Name)?r(i,l):l}}we.mergeEvaluated={props:RE({mergeNames:(e,t,n)=>e.if((0,Me._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,Me._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,Me._)`${n} || {}`).code((0,Me._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,Me._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,Me._)`${n} || {}`),yg(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:AE}),items:RE({mergeNames:(e,t,n)=>e.if((0,Me._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,Me._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,Me._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,Me._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function AE(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",(0,Me._)`{}`);return t!==void 0&&yg(e,n,t),n}we.evaluatedPropsToName=AE;function yg(e,t,n){Object.keys(n).forEach(r=>e.assign((0,Me._)`${t}${(0,Me.getProperty)(r)}`,!0))}we.setEvaluated=yg;var SE={};function H1(e,t){return e.scopeValue("func",{ref:t,code:SE[t.code]||(SE[t.code]=new $1._Code(t.code))})}we.useFunc=H1;var gg;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(gg||(we.Type=gg={}));function B1(e,t,n){if(e instanceof Me.Name){let r=t===gg.Num;return n?r?(0,Me._)`"[" + ${e} + "]"`:(0,Me._)`"['" + ${e} + "']"`:r?(0,Me._)`"/" + ${e}`:(0,Me._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,Me.getProperty)(e).toString():"/"+wg(e)}we.getErrorPath=B1;function IE(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=IE});var Mr=I(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var Ht=ge(),V1={data:new Ht.Name("data"),valCxt:new Ht.Name("valCxt"),instancePath:new Ht.Name("instancePath"),parentData:new Ht.Name("parentData"),parentDataProperty:new Ht.Name("parentDataProperty"),rootData:new Ht.Name("rootData"),dynamicAnchors:new Ht.Name("dynamicAnchors"),vErrors:new Ht.Name("vErrors"),errors:new Ht.Name("errors"),this:new Ht.Name("this"),self:new Ht.Name("self"),scope:new Ht.Name("scope"),json:new Ht.Name("json"),jsonPos:new Ht.Name("jsonPos"),jsonLen:new Ht.Name("jsonLen"),jsonPart:new Ht.Name("jsonPart")};vg.default=V1});var _c=I(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.extendErrors=Bt.resetErrorsCount=Bt.reportExtraError=Bt.reportError=Bt.keyword$DataError=Bt.keywordError=void 0;var Ae=ge(),Md=xe(),en=Mr();Bt.keywordError={message:({keyword:e})=>(0,Ae.str)`must pass "${e}" keyword validation`};Bt.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,Ae.str)`"${e}" keyword must be ${t} ($data)`:(0,Ae.str)`"${e}" keyword is invalid ($data)`};function U1(e,t=Bt.keywordError,n,r){let{it:i}=e,{gen:s,compositeRule:o,allErrors:c}=i,l=OE(e,t,n);r??(o||c)?_E(s,l):PE(i,(0,Ae._)`[${l}]`)}Bt.reportError=U1;function K1(e,t=Bt.keywordError,n){let{it:r}=e,{gen:i,compositeRule:s,allErrors:o}=r,c=OE(e,t,n);_E(i,c),s||o||PE(r,en.default.vErrors)}Bt.reportExtraError=K1;function z1(e,t){e.assign(en.default.errors,t),e.if((0,Ae._)`${en.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Ae._)`${en.default.vErrors}.length`,t),()=>e.assign(en.default.vErrors,null)))}Bt.resetErrorsCount=z1;function J1({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,en.default.errors,c=>{e.const(o,(0,Ae._)`${en.default.vErrors}[${c}]`),e.if((0,Ae._)`${o}.instancePath === undefined`,()=>e.assign((0,Ae._)`${o}.instancePath`,(0,Ae.strConcat)(en.default.instancePath,s.errorPath))),e.assign((0,Ae._)`${o}.schemaPath`,(0,Ae.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,Ae._)`${o}.schema`,n),e.assign((0,Ae._)`${o}.data`,r))})}Bt.extendErrors=J1;function _E(e,t){let n=e.const("err",t);e.if((0,Ae._)`${en.default.vErrors} === null`,()=>e.assign(en.default.vErrors,(0,Ae._)`[${n}]`),(0,Ae._)`${en.default.vErrors}.push(${n})`),e.code((0,Ae._)`${en.default.errors}++`)}function PE(e,t){let{gen:n,validateName:r,schemaEnv:i}=e;i.$async?n.throw((0,Ae._)`new ${e.ValidationError}(${t})`):(n.assign((0,Ae._)`${r}.errors`,t),n.return(!1))}var Es={keyword:new Ae.Name("keyword"),schemaPath:new Ae.Name("schemaPath"),params:new Ae.Name("params"),propertyName:new Ae.Name("propertyName"),message:new Ae.Name("message"),schema:new Ae.Name("schema"),parentSchema:new Ae.Name("parentSchema")};function OE(e,t,n){let{createErrors:r}=e.it;return r===!1?(0,Ae._)`{}`:G1(e,t,n)}function G1(e,t,n={}){let{gen:r,it:i}=e,s=[Y1(i,n),X1(e,n)];return Q1(e,t,s),r.object(...s)}function Y1({errorPath:e},{instancePath:t}){let n=t?(0,Ae.str)`${e}${(0,Md.getErrorPath)(t,Md.Type.Str)}`:e;return[en.default.instancePath,(0,Ae.strConcat)(en.default.instancePath,n)]}function X1({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:r}){let i=r?t:(0,Ae.str)`${t}/${e}`;return n&&(i=(0,Ae.str)`${i}${(0,Md.getErrorPath)(n,Md.Type.Str)}`),[Es.schemaPath,i]}function Q1(e,{params:t,message:n},r){let{keyword:i,data:s,schemaValue:o,it:c}=e,{opts:l,propertyName:f,topSchemaRef:a,schemaPath:u}=c;r.push([Es.keyword,i],[Es.params,typeof t=="function"?t(e):t||(0,Ae._)`{}`]),l.messages&&r.push([Es.message,typeof n=="function"?n(e):n]),l.verbose&&r.push([Es.schema,o],[Es.parentSchema,(0,Ae._)`${a}${u}`],[en.default.data,s]),f&&r.push([Es.propertyName,f])}});var NE=I(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.boolOrEmptySchema=Lo.topBoolOrEmptySchema=void 0;var Z1=_c(),eL=ge(),tL=Mr(),nL={message:"boolean schema is false"};function rL(e){let{gen:t,schema:n,validateName:r}=e;n===!1?TE(e,!1):typeof n=="object"&&n.$async===!0?t.return(tL.default.data):(t.assign((0,eL._)`${r}.errors`,null),t.return(!0))}Lo.topBoolOrEmptySchema=rL;function iL(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),TE(e)):n.var(t,!0)}Lo.boolOrEmptySchema=iL;function TE(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,Z1.reportError)(i,nL,void 0,t)}});var kg=I(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.getRules=Wo.isJSONType=void 0;var sL=["string","number","integer","boolean","null","object","array"],oL=new Set(sL);function aL(e){return typeof e=="string"&&oL.has(e)}Wo.isJSONType=aL;function cL(){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:{}}}Wo.getRules=cL});var bg=I(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.shouldUseRule=_i.shouldUseGroup=_i.schemaHasRulesForType=void 0;function lL({schema:e,self:t},n){let r=t.RULES.types[n];return r&&r!==!0&&$E(e,r)}_i.schemaHasRulesForType=lL;function $E(e,t){return t.rules.some(n=>jE(e,n))}_i.shouldUseGroup=$E;function jE(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))}_i.shouldUseRule=jE});var Pc=I(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.reportTypeError=Vt.checkDataTypes=Vt.checkDataType=Vt.coerceAndCheckDataType=Vt.getJSONTypes=Vt.getSchemaTypes=Vt.DataType=void 0;var uL=kg(),dL=bg(),fL=_c(),fe=ge(),DE=xe(),Mo;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Mo||(Vt.DataType=Mo={}));function pL(e){let t=qE(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}Vt.getSchemaTypes=pL;function qE(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(uL.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Vt.getJSONTypes=qE;function mL(e,t){let{gen:n,data:r,opts:i}=e,s=hL(t,i.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,dL.schemaHasRulesForType)(e,t[0]));if(o){let c=Sg(t,r,i.strictNumbers,Mo.Wrong);n.if(c,()=>{s.length?gL(e,t,s):Cg(e)})}return o}Vt.coerceAndCheckDataType=mL;var LE=new Set(["string","number","integer","boolean","null"]);function hL(e,t){return t?e.filter(n=>LE.has(n)||t==="array"&&n==="array"):[]}function gL(e,t,n){let{gen:r,data:i,opts:s}=e,o=r.let("dataType",(0,fe._)`typeof ${i}`),c=r.let("coerced",(0,fe._)`undefined`);s.coerceTypes==="array"&&r.if((0,fe._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>r.assign(i,(0,fe._)`${i}[0]`).assign(o,(0,fe._)`typeof ${i}`).if(Sg(t,i,s.strictNumbers),()=>r.assign(c,i))),r.if((0,fe._)`${c} !== undefined`);for(let f of n)(LE.has(f)||f==="array"&&s.coerceTypes==="array")&&l(f);r.else(),Cg(e),r.endIf(),r.if((0,fe._)`${c} !== undefined`,()=>{r.assign(i,c),wL(e,c)});function l(f){switch(f){case"string":r.elseIf((0,fe._)`${o} == "number" || ${o} == "boolean"`).assign(c,(0,fe._)`"" + ${i}`).elseIf((0,fe._)`${i} === null`).assign(c,(0,fe._)`""`);return;case"number":r.elseIf((0,fe._)`${o} == "boolean" || ${i} === null
|
|
151
|
+
|| (${o} == "string" && ${i} && ${i} == +${i})`).assign(c,(0,fe._)`+${i}`);return;case"integer":r.elseIf((0,fe._)`${o} === "boolean" || ${i} === null
|
|
152
|
+
|| (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(c,(0,fe._)`+${i}`);return;case"boolean":r.elseIf((0,fe._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(c,!1).elseIf((0,fe._)`${i} === "true" || ${i} === 1`).assign(c,!0);return;case"null":r.elseIf((0,fe._)`${i} === "" || ${i} === 0 || ${i} === false`),r.assign(c,null);return;case"array":r.elseIf((0,fe._)`${o} === "string" || ${o} === "number"
|
|
153
|
+
|| ${o} === "boolean" || ${i} === null`).assign(c,(0,fe._)`[${i}]`)}}}function wL({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,fe._)`${t} !== undefined`,()=>e.assign((0,fe._)`${t}[${n}]`,r))}function Rg(e,t,n,r=Mo.Correct){let i=r===Mo.Correct?fe.operators.EQ:fe.operators.NEQ,s;switch(e){case"null":return(0,fe._)`${t} ${i} null`;case"array":s=(0,fe._)`Array.isArray(${t})`;break;case"object":s=(0,fe._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o((0,fe._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return(0,fe._)`typeof ${t} ${i} ${e}`}return r===Mo.Correct?s:(0,fe.not)(s);function o(c=fe.nil){return(0,fe.and)((0,fe._)`typeof ${t} == "number"`,c,n?(0,fe._)`isFinite(${t})`:fe.nil)}}Vt.checkDataType=Rg;function Sg(e,t,n,r){if(e.length===1)return Rg(e[0],t,n,r);let i,s=(0,DE.toHash)(e);if(s.array&&s.object){let o=(0,fe._)`typeof ${t} != "object"`;i=s.null?o:(0,fe._)`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else i=fe.nil;s.number&&delete s.integer;for(let o in s)i=(0,fe.and)(i,Rg(o,t,n,r));return i}Vt.checkDataTypes=Sg;var yL={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,fe._)`{type: ${e}}`:(0,fe._)`{type: ${t}}`};function Cg(e){let t=vL(e);(0,fL.reportError)(t,yL)}Vt.reportTypeError=Cg;function vL(e){let{gen:t,data:n,schema:r}=e,i=(0,DE.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}});var ME=I(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});Fd.assignDefaults=void 0;var Fo=ge(),kL=xe();function bL(e,t){let{properties:n,items:r}=e.schema;if(t==="object"&&n)for(let i in n)WE(e,i,n[i].default);else t==="array"&&Array.isArray(r)&&r.forEach((i,s)=>WE(e,s,i.default))}Fd.assignDefaults=bL;function WE(e,t,n){let{gen:r,compositeRule:i,data:s,opts:o}=e;if(n===void 0)return;let c=(0,Fo._)`${s}${(0,Fo.getProperty)(t)}`;if(i){(0,kL.checkStrictMode)(e,`default is ignored for: ${c}`);return}let l=(0,Fo._)`${c} === undefined`;o.useDefaults==="empty"&&(l=(0,Fo._)`${l} || ${c} === null || ${c} === ""`),r.if(l,(0,Fo._)`${c} = ${(0,Fo.stringify)(n)}`)}});var Wn=I(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.validateUnion=Le.validateArray=Le.usePattern=Le.callValidateCode=Le.schemaProperties=Le.allSchemaProperties=Le.noPropertyInData=Le.propertyInData=Le.isOwnProperty=Le.hasPropFunc=Le.reportMissingProp=Le.checkMissingProp=Le.checkReportMissingProp=void 0;var Be=ge(),Eg=xe(),Pi=Mr(),RL=xe();function SL(e,t){let{gen:n,data:r,it:i}=e;n.if(Ag(n,r,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,Be._)`${t}`},!0),e.error()})}Le.checkReportMissingProp=SL;function CL({gen:e,data:t,it:{opts:n}},r,i){return(0,Be.or)(...r.map(s=>(0,Be.and)(Ag(e,t,s,n.ownProperties),(0,Be._)`${i} = ${s}`)))}Le.checkMissingProp=CL;function EL(e,t){e.setParams({missingProperty:t},!0),e.error()}Le.reportMissingProp=EL;function FE(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Be._)`Object.prototype.hasOwnProperty`})}Le.hasPropFunc=FE;function xg(e,t,n){return(0,Be._)`${FE(e)}.call(${t}, ${n})`}Le.isOwnProperty=xg;function xL(e,t,n,r){let i=(0,Be._)`${t}${(0,Be.getProperty)(n)} !== undefined`;return r?(0,Be._)`${i} && ${xg(e,t,n)}`:i}Le.propertyInData=xL;function Ag(e,t,n,r){let i=(0,Be._)`${t}${(0,Be.getProperty)(n)} === undefined`;return r?(0,Be.or)(i,(0,Be.not)(xg(e,t,n))):i}Le.noPropertyInData=Ag;function HE(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}Le.allSchemaProperties=HE;function AL(e,t){return HE(t).filter(n=>!(0,Eg.alwaysValidSchema)(e,t[n]))}Le.schemaProperties=AL;function IL({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:i,errorPath:s},it:o},c,l,f){let a=f?(0,Be._)`${e}, ${t}, ${r}${i}`:t,u=[[Pi.default.instancePath,(0,Be.strConcat)(Pi.default.instancePath,s)],[Pi.default.parentData,o.parentData],[Pi.default.parentDataProperty,o.parentDataProperty],[Pi.default.rootData,Pi.default.rootData]];o.opts.dynamicRef&&u.push([Pi.default.dynamicAnchors,Pi.default.dynamicAnchors]);let p=(0,Be._)`${a}, ${n.object(...u)}`;return l!==Be.nil?(0,Be._)`${c}.call(${l}, ${p})`:(0,Be._)`${c}(${p})`}Le.callValidateCode=IL;var _L=(0,Be._)`new RegExp`;function PL({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,Be._)`${i.code==="new RegExp"?_L:(0,RL.useFunc)(e,i)}(${n}, ${r})`})}Le.usePattern=PL;function OL(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,Be._)`${n}.length`);t.forRange("i",0,l,f=>{e.subschema({keyword:r,dataProp:f,dataPropType:Eg.Type.Num},s),t.if((0,Be.not)(s),c)})}}Le.validateArray=OL;function TL(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,Eg.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,Be._)`${o} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,Be.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}Le.validateUnion=TL});var UE=I(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.validateKeywordUsage=Rr.validSchemaType=Rr.funcKeywordCode=Rr.macroKeywordCode=void 0;var tn=ge(),xs=Mr(),NL=Wn(),$L=_c();function jL(e,t){let{gen:n,keyword:r,schema:i,parentSchema:s,it:o}=e,c=t.macro.call(o.self,i,s,o),l=VE(n,r,c);o.opts.validateSchema!==!1&&o.self.validateSchema(c,!0);let f=n.name("valid");e.subschema({schema:c,schemaPath:tn.nil,errSchemaPath:`${o.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},f),e.pass(f,()=>e.error(!0))}Rr.macroKeywordCode=jL;function DL(e,t){var n;let{gen:r,keyword:i,schema:s,parentSchema:o,$data:c,it:l}=e;LL(l,t);let f=!c&&t.compile?t.compile.call(l.self,s,o,l):t.validate,a=VE(r,i,f),u=r.let("valid");e.block$data(u,p),e.ok((n=t.valid)!==null&&n!==void 0?n:u);function p(){if(t.errors===!1)h(),t.modifying&&BE(e),g(()=>e.error());else{let w=t.async?d():m();t.modifying&&BE(e),g(()=>qL(e,w))}}function d(){let w=r.let("ruleErrs",null);return r.try(()=>h((0,tn._)`await `),k=>r.assign(u,!1).if((0,tn._)`${k} instanceof ${l.ValidationError}`,()=>r.assign(w,(0,tn._)`${k}.errors`),()=>r.throw(k))),w}function m(){let w=(0,tn._)`${a}.errors`;return r.assign(w,null),h(tn.nil),w}function h(w=t.async?(0,tn._)`await `:tn.nil){let k=l.opts.passContext?xs.default.this:xs.default.self,y=!("compile"in t&&!c||t.schema===!1);r.assign(u,(0,tn._)`${w}${(0,NL.callValidateCode)(e,a,k,y)}`,t.modifying)}function g(w){var k;r.if((0,tn.not)((k=t.valid)!==null&&k!==void 0?k:u),w)}}Rr.funcKeywordCode=DL;function BE(e){let{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,tn._)`${r.parentData}[${r.parentDataProperty}]`))}function qL(e,t){let{gen:n}=e;n.if((0,tn._)`Array.isArray(${t})`,()=>{n.assign(xs.default.vErrors,(0,tn._)`${xs.default.vErrors} === null ? ${t} : ${xs.default.vErrors}.concat(${t})`).assign(xs.default.errors,(0,tn._)`${xs.default.vErrors}.length`),(0,$L.extendErrors)(e)},()=>e.error())}function LL({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function VE(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,tn.stringify)(n)})}function WL(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")}Rr.validSchemaType=WL;function ML({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)}}Rr.validateKeywordUsage=ML});var zE=I(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.extendSubschemaMode=Oi.extendSubschemaData=Oi.getSubschema=void 0;var Sr=ge(),KE=xe();function FL(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,Sr._)`${e.schemaPath}${(0,Sr.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[n],schemaPath:(0,Sr._)`${e.schemaPath}${(0,Sr.getProperty)(t)}${(0,Sr.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,KE.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')}Oi.getSubschema=FL;function HL(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:u}=t,p=c.let("data",(0,Sr._)`${t.data}${(0,Sr.getProperty)(n)}`,!0);l(p),e.errorPath=(0,Sr.str)`${f}${(0,KE.getErrorPath)(n,r,u.jsPropertySyntax)}`,e.parentDataProperty=(0,Sr._)`${n}`,e.dataPathArr=[...a,e.parentDataProperty]}if(i!==void 0){let f=i instanceof Sr.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]}}Oi.extendSubschemaData=HL;function BL(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}Oi.extendSubschemaMode=BL});var Ig=I((M5,JE)=>{"use strict";JE.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 YE=I((F5,GE)=>{"use strict";var Ti=GE.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(){};Hd(t,r,i,e,"",e)};Ti.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ti.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ti.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ti.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 Hd(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 u=r[a];if(Array.isArray(u)){if(a in Ti.arrayKeywords)for(var p=0;p<u.length;p++)Hd(e,t,n,u[p],i+"/"+a+"/"+p,s,i,a,r,p)}else if(a in Ti.propsKeywords){if(u&&typeof u=="object")for(var d in u)Hd(e,t,n,u[d],i+"/"+a+"/"+VL(d),s,i,a,r,d)}else(a in Ti.keywords||e.allKeys&&!(a in Ti.skipKeywords))&&Hd(e,t,n,u,i+"/"+a,s,i,a,r)}n(r,i,s,o,c,l,f)}}function VL(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Oc=I(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.getSchemaRefs=gn.resolveUrl=gn.normalizeId=gn._getFullPath=gn.getFullPath=gn.inlineRef=void 0;var UL=xe(),KL=Ig(),zL=YE(),JL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function GL(e,t=!0){return typeof e=="boolean"?!0:t===!0?!_g(e):t?XE(e)<=t:!1}gn.inlineRef=GL;var YL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function _g(e){for(let t in e){if(YL.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(_g)||typeof n=="object"&&_g(n))return!0}return!1}function XE(e){let t=0;for(let n in e){if(n==="$ref")return 1/0;if(t++,!JL.has(n)&&(typeof e[n]=="object"&&(0,UL.eachItem)(e[n],r=>t+=XE(r)),t===1/0))return 1/0}return t}function QE(e,t="",n){n!==!1&&(t=Ho(t));let r=e.parse(t);return ZE(e,r)}gn.getFullPath=QE;function ZE(e,t){return e.serialize(t).split("#")[0]+"#"}gn._getFullPath=ZE;var XL=/#\/?$/;function Ho(e){return e?e.replace(XL,""):""}gn.normalizeId=Ho;function QL(e,t,n){return n=Ho(n),e.resolve(t,n)}gn.resolveUrl=QL;var ZL=/^[a-z_][-a-z0-9._]*$/i;function eW(e,t){if(typeof e=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,i=Ho(e[n]||t),s={"":i},o=QE(r,i,!1),c={},l=new Set;return zL(e,{allKeys:!0},(u,p,d,m)=>{if(m===void 0)return;let h=o+p,g=s[m];typeof u[n]=="string"&&(g=w.call(this,u[n])),k.call(this,u.$anchor),k.call(this,u.$dynamicAnchor),s[p]=g;function w(y){let R=this.opts.uriResolver.resolve;if(y=Ho(g?R(g,y):y),l.has(y))throw a(y);l.add(y);let S=this.refs[y];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?f(u,S.schema,y):y!==Ho(h)&&(y[0]==="#"?(f(u,c[y],y),c[y]=u):this.refs[y]=h),y}function k(y){if(typeof y=="string"){if(!ZL.test(y))throw new Error(`invalid anchor "${y}"`);w.call(this,`#${y}`)}}}),c;function f(u,p,d){if(p!==void 0&&!KL(u,p))throw a(d)}function a(u){return new Error(`reference "${u}" resolves to more than one schema`)}}gn.getSchemaRefs=eW});var $c=I(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.getData=Ni.KeywordCxt=Ni.validateFunctionCode=void 0;var ix=NE(),ex=Pc(),Og=bg(),Bd=Pc(),tW=ME(),Nc=UE(),Pg=zE(),te=ge(),ae=Mr(),nW=Oc(),Fr=xe(),Tc=_c();function rW(e){if(ax(e)&&(cx(e),ox(e))){oW(e);return}sx(e,()=>(0,ix.topBoolOrEmptySchema)(e))}Ni.validateFunctionCode=rW;function sx({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},s){i.code.es5?e.func(t,(0,te._)`${ae.default.data}, ${ae.default.valCxt}`,r.$async,()=>{e.code((0,te._)`"use strict"; ${tx(n,i)}`),sW(e,i),e.code(s)}):e.func(t,(0,te._)`${ae.default.data}, ${iW(i)}`,r.$async,()=>e.code(tx(n,i)).code(s))}function iW(e){return(0,te._)`{${ae.default.instancePath}="", ${ae.default.parentData}, ${ae.default.parentDataProperty}, ${ae.default.rootData}=${ae.default.data}${e.dynamicRef?(0,te._)`, ${ae.default.dynamicAnchors}={}`:te.nil}}={}`}function sW(e,t){e.if(ae.default.valCxt,()=>{e.var(ae.default.instancePath,(0,te._)`${ae.default.valCxt}.${ae.default.instancePath}`),e.var(ae.default.parentData,(0,te._)`${ae.default.valCxt}.${ae.default.parentData}`),e.var(ae.default.parentDataProperty,(0,te._)`${ae.default.valCxt}.${ae.default.parentDataProperty}`),e.var(ae.default.rootData,(0,te._)`${ae.default.valCxt}.${ae.default.rootData}`),t.dynamicRef&&e.var(ae.default.dynamicAnchors,(0,te._)`${ae.default.valCxt}.${ae.default.dynamicAnchors}`)},()=>{e.var(ae.default.instancePath,(0,te._)`""`),e.var(ae.default.parentData,(0,te._)`undefined`),e.var(ae.default.parentDataProperty,(0,te._)`undefined`),e.var(ae.default.rootData,ae.default.data),t.dynamicRef&&e.var(ae.default.dynamicAnchors,(0,te._)`{}`)})}function oW(e){let{schema:t,opts:n,gen:r}=e;sx(e,()=>{n.$comment&&t.$comment&&ux(e),dW(e),r.let(ae.default.vErrors,null),r.let(ae.default.errors,0),n.unevaluated&&aW(e),lx(e),mW(e)})}function aW(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 tx(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 cW(e,t){if(ax(e)&&(cx(e),ox(e))){lW(e,t);return}(0,ix.boolOrEmptySchema)(e,t)}function ox({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 ax(e){return typeof e.schema!="boolean"}function lW(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&ux(e),fW(e),pW(e);let s=r.const("_errs",ae.default.errors);lx(e,s),r.var(t,(0,te._)`${s} === ${ae.default.errors}`)}function cx(e){(0,Fr.checkUnknownRules)(e),uW(e)}function lx(e,t){if(e.opts.jtd)return nx(e,[],!1,t);let n=(0,ex.getSchemaTypes)(e.schema),r=(0,ex.coerceAndCheckDataType)(e,n);nx(e,n,!r,t)}function uW(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,Fr.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function dW(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Fr.checkStrictMode)(e,"default is ignored in the schema root")}function fW(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,nW.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function pW(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function ux({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let s=n.$comment;if(i.$comment===!0)e.code((0,te._)`${ae.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._)`${ae.default.self}.opts.$comment(${s}, ${o}, ${c}.schema)`)}}function mW(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:s}=e;n.$async?t.if((0,te._)`${ae.default.errors} === 0`,()=>t.return(ae.default.data),()=>t.throw((0,te._)`new ${i}(${ae.default.vErrors})`)):(t.assign((0,te._)`${r}.errors`,ae.default.vErrors),s.unevaluated&&hW(e),t.return((0,te._)`${ae.default.errors} === 0`))}function hW({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 nx(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,Fr.schemaHasRulesButRef)(s,a))){i.block(()=>fx(e,"$ref",a.all.$ref.definition));return}l.jtd||gW(e,t),i.block(()=>{for(let p of a.rules)u(p);u(a.post)});function u(p){(0,Og.shouldUseGroup)(s,p)&&(p.type?(i.if((0,Bd.checkDataType)(p.type,o,l.strictNumbers)),rx(e,p),t.length===1&&t[0]===p.type&&n&&(i.else(),(0,Bd.reportTypeError)(e)),i.endIf()):rx(e,p),c||i.if((0,te._)`${ae.default.errors} === ${r||0}`))}}function rx(e,t){let{gen:n,schema:r,opts:{useDefaults:i}}=e;i&&(0,tW.assignDefaults)(e,t.type),n.block(()=>{for(let s of t.rules)(0,Og.shouldUseRule)(r,s)&&fx(e,s.keyword,s.definition,t.type)})}function gW(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(wW(e,t),e.opts.allowUnionTypes||yW(e,t),vW(e,e.dataTypes))}function wW(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{dx(e.dataTypes,n)||Tg(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),bW(e,t)}}function yW(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Tg(e,"use allowUnionTypes to allow union type keyword")}function vW(e,t){let n=e.self.RULES.all;for(let r in n){let i=n[r];if(typeof i=="object"&&(0,Og.shouldUseRule)(e.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>kW(t,o))&&Tg(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function kW(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function dx(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function bW(e,t){let n=[];for(let r of e.dataTypes)dx(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function Tg(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,Fr.checkStrictMode)(e,t,e.opts.strictTypes)}var Vd=class{constructor(t,n,r){if((0,Nc.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,Fr.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",px(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Nc.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",ae.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?Tc.reportExtraError:Tc.reportError)(this,this.def.error,n)}$dataError(){(0,Tc.reportError)(this,this.def.$dataError||Tc.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Tc.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,Pg.getSubschema)(this.it,t);(0,Pg.extendSubschemaData)(r,this.it,t),(0,Pg.extendSubschemaMode)(r,t);let i={...this.it,...r,items:void 0,props:void 0};return cW(i,n),i}mergeEvaluated(t,n){let{it:r,gen:i}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=Fr.mergeEvaluated.props(i,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=Fr.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}};Ni.KeywordCxt=Vd;function fx(e,t,n,r){let i=new Vd(e,n,t);"code"in n?n.code(i,r):i.$data&&n.validate?(0,Nc.funcKeywordCode)(i,n):"macro"in n?(0,Nc.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,Nc.funcKeywordCode)(i,n)}var RW=/^\/(?:[^~]|~0|~1)*$/,SW=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function px(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,s;if(e==="")return ae.default.rootData;if(e[0]==="/"){if(!RW.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,s=ae.default.rootData}else{let f=SW.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,Fr.unescapeJsonPointer)(f))}`,o=(0,te._)`${o} && ${s}`);return o;function l(f,a){return`Cannot access ${f} ${a} levels up, current level is ${t}`}}Ni.getData=px});var Ud=I($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var Ng=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};$g.default=Ng});var jc=I(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var jg=Oc(),Dg=class extends Error{constructor(t,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,jg.resolveUrl)(t,n,r),this.missingSchema=(0,jg.normalizeId)((0,jg.getFullPath)(t,this.missingRef))}};qg.default=Dg});var zd=I(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.resolveSchema=Mn.getCompilingSchema=Mn.resolveRef=Mn.compileSchema=Mn.SchemaEnv=void 0;var ir=ge(),CW=Ud(),As=Mr(),sr=Oc(),mx=xe(),EW=$c(),Bo=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,sr.normalizeId)(r?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r?.$async,this.refs={}}};Mn.SchemaEnv=Bo;function Wg(e){let t=hx.call(this,e);if(t)return t;let n=(0,sr.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new ir.CodeGen(this.scope,{es5:r,lines:i,ownProperties:s}),c;e.$async&&(c=o.scopeValue("Error",{ref:CW.default,code:(0,ir._)`require("ajv/dist/runtime/validation_error").default`}));let l=o.scopeName("validate");e.validateName=l;let f={gen:o,allErrors:this.opts.allErrors,data:As.default.data,parentData:As.default.parentData,parentDataProperty:As.default.parentDataProperty,dataNames:[As.default.data],dataPathArr:[ir.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,ir.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:ir.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ir._)`""`,opts:this.opts,self:this},a;try{this._compilations.add(e),(0,EW.validateFunctionCode)(f),o.optimize(this.opts.code.optimize);let u=o.toString();a=`${o.scopeRefs(As.default.scope)}return ${u}`,this.opts.code.process&&(a=this.opts.code.process(a,e));let d=new Function(`${As.default.self}`,`${As.default.scope}`,a)(this,this.scope.get());if(this.scope.value(l,{ref:d}),d.errors=null,d.schema=e.schema,d.schemaEnv=e,e.$async&&(d.$async=!0),this.opts.code.source===!0&&(d.source={validateName:l,validateCode:u,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=f;d.evaluated={props:m instanceof ir.Name?void 0:m,items:h instanceof ir.Name?void 0:h,dynamicProps:m instanceof ir.Name,dynamicItems:h instanceof ir.Name},d.source&&(d.source.evaluated=(0,ir.stringify)(d.evaluated))}return e.validate=d,e}catch(u){throw delete e.validate,delete e.validateName,a&&this.logger.error("Error compiling schema, function code:",a),u}finally{this._compilations.delete(e)}}Mn.compileSchema=Wg;function xW(e,t,n){var r;n=(0,sr.resolveUrl)(this.opts.uriResolver,t,n);let i=e.refs[n];if(i)return i;let s=_W.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 Bo({schema:o,schemaId:c,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=AW.call(this,s)}Mn.resolveRef=xW;function AW(e){return(0,sr.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Wg.call(this,e)}function hx(e){for(let t of this._compilations)if(IW(t,e))return t}Mn.getCompilingSchema=hx;function IW(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function _W(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Kd.call(this,e,t)}function Kd(e,t){let n=this.opts.uriResolver.parse(t),r=(0,sr._getFullPath)(this.opts.uriResolver,n),i=(0,sr.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===i)return Lg.call(this,n,e);let s=(0,sr.normalizeId)(r),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let c=Kd.call(this,e,o);return typeof c?.schema!="object"?void 0:Lg.call(this,n,c)}if(typeof o?.schema=="object"){if(o.validate||Wg.call(this,o),s===(0,sr.normalizeId)(t)){let{schema:c}=o,{schemaId:l}=this.opts,f=c[l];return f&&(i=(0,sr.resolveUrl)(this.opts.uriResolver,i,f)),new Bo({schema:c,schemaId:l,root:e,baseId:i})}return Lg.call(this,n,o)}}Mn.resolveSchema=Kd;var PW=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Lg(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,mx.unescapeFragment)(c)];if(l===void 0)return;n=l;let f=typeof n=="object"&&n[this.opts.schemaId];!PW.has(c)&&f&&(t=(0,sr.resolveUrl)(this.opts.uriResolver,t,f))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,mx.schemaHasRulesButRef)(n,this.RULES)){let c=(0,sr.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Kd.call(this,r,c)}let{schemaId:o}=this.opts;if(s=s||new Bo({schema:n,schemaId:o,root:r,baseId:t}),s.schema!==s.root.schema)return s}});var gx=I((z5,OW)=>{OW.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 Ug=I((J5,Cx)=>{"use strict";var TW=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Fg=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),NW=RegExp.prototype.test.bind(/^\d*$/u),Is=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Hg=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),yx=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Bg=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),$W=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),wn=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)wn[t]="%"+e[t>>4]+e[t&15]}function Ut(e){return e<2048?wn[192|e>>6]+wn[128|e&63]:e<65536?wn[224|e>>12]+wn[128|e>>6&63]+wn[128|e&63]:wn[240|e>>18]+wn[128|e>>12&63]+wn[128|e>>6&63]+wn[128|e&63]}function jW(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 DW=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),qW=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),LW=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),WW=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function MW(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!LW(e[t])){if(e[t]==="%"&&t+2<e.length&&Is(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function wx(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 FW(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||!Fg(l))return;s+=2;continue}if(!DW(l))return;i[c]=parseInt(l,16).toString(16),s++}if(t===-1)return s!==8?void 0:wx(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 wx(o)}function Mg(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&&qW(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:!1,isIPVFuture:!0};if(HW(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),!MW(i))return{host:e,isIPV6:!1,error:!0};r=r.slice(0,s)}let o=FW(r);return o===void 0?{host:e,isIPV6:!1,error:!0}:{host:o+(i?"%"+i:""),escapedHost:o+(i?"%25"+i:""),isIPV6:!0}}function HW(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function vx(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 BW(e){if(e===""||e[0]==="/")return vx(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 VW={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},UW=/[@/?#:]/g,KW=/[@/?#]/g;function kx(e,t){let n=t?KW:UW;return n.lastIndex=0,e.replace(n,r=>VW[r])}function bx(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(Is(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));t&&Hg(o)?n+=o:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function zW(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(Is(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Hg(o)?t+=o:t+="%"+s,n+=2;continue}}if(yx(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=Sx(i)?r:wn[i];else if(i<55296||i>57343)t+=Ut(i);else if(i<=56319&&n+1<e.length){let s=e.charCodeAt(n+1);s>=56320&&s<=57343?(t+=Ut(65536+(i-55296<<10)+(s-56320)),n++):t+=Ut(65533)}else t+=Ut(65533)}}return t}function JW(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(Is(o)){n+="%"+o.toUpperCase(),i+=2;continue}}if(s==="/"&&(r=!1),yx(s)&&(s!==":"||!r))n+=s;else{let o=e.charCodeAt(i);if(o<128)n+=wn[o];else if(o<55296||o>57343)n+=Ut(o);else if(o<=56319&&i+1<e.length){let c=e.charCodeAt(i+1);c>=56320&&c<=57343?(n+=Ut(65536+(o-55296<<10)+(c-56320)),i++):n+=Ut(65533)}else n+=Ut(65533)}}return n}function Vg(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(Is(s)){n+="%"+s.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let s=e.charCodeAt(r);if(s<128)n+=wn[s];else if(s<55296||s>57343)n+=Ut(s);else if(s<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);o>=56320&&o<=57343?(n+=Ut(65536+(s-55296<<10)+(o-56320)),r++):n+=Ut(65533)}else n+=Ut(65533)}}return n}function Rx(e){return Vg(e,$W)}function GW(e){return Vg(e,Bg)}function YW(e){return Vg(e,Bg)}function Sx(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 XW(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(Is(i)){let s=i.toUpperCase(),o=String.fromCharCode(parseInt(s,16));Hg(o)?t+=o:t+="%"+s,n+=2;continue}}if(Bg(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=Sx(i)?r:wn[i];else if(i<55296||i>57343)t+=Ut(i);else if(i<=56319&&n+1<e.length){let s=e.charCodeAt(n+1);s>=56320&&s<=57343?(t+=Ut(65536+(i-55296<<10)+(s-56320)),n++):t+=Ut(65533)}else t+=Ut(65533)}}return t}function QW(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(Is(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ZW(e){let t=[];if(e.userinfo!==void 0&&(t.push(Rx(e.userinfo)),t.push("@")),e.host!==void 0){let n=e.host;if(!Fg(n)){let r=Mg(n);r.isIPV6!==!0&&r.isIPVFuture!==!0&&(n=bx(n,!0),r=Mg(n)),r.isIPV6===!0||r.isIPVFuture===!0?n=`[${r.escapedHost}]`:n=kx(n,!1)}t.push(n)}if(typeof e.port=="number"||typeof e.port=="string"){let n=String(e.port);if(!NW(n))throw new TypeError("URI port is malformed.");t.push(":"),t.push(n)}return t.length?t.join(""):void 0}Cx.exports={nonSimpleDomain:WW,recomposeAuthority:ZW,reescapeHostDelimiters:kx,normalizePercentEncoding:bx,normalizePathEncoding:zW,serializePathEncoding:JW,normalizeQueryFragmentEncoding:XW,encodeUserinfo:Rx,encodeQuery:GW,encodeFragment:YW,escapePreservingEscapes:QW,removeDotSegments:vx,removeDotSegmentsRelative:BW,isIPv4:Fg,isUUID:TW,normalizeIPv6:Mg,stringArrayToHexStripped:jW}});var _x=I((G5,Ix)=>{"use strict";var{isUUID:eM}=Ug(),tM=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,nM=["http","https","ws","wss","urn","urn:uuid"];function rM(e){return nM.indexOf(e)!==-1}function Kg(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 Ex(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function xx(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 iM(e){return e.secure=Kg(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function sM(e){if((e.port===(Kg(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 oM(e,t){if(!e.path)return e.error="URN can not be parsed",e;let n=e.path.match(tM);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=zg(i);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function aM(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=zg(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 cM(e,t){let n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!eM(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function lM(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Ax={scheme:"http",domainHost:!0,parse:Ex,serialize:xx},uM={scheme:"https",domainHost:Ax.domainHost,parse:Ex,serialize:xx},Jd={scheme:"ws",domainHost:!0,parse:iM,serialize:sM},dM={scheme:"wss",domainHost:Jd.domainHost,parse:Jd.parse,serialize:Jd.serialize},fM={scheme:"urn",parse:oM,serialize:aM,skipNormalize:!0},pM={scheme:"urn:uuid",parse:cM,serialize:lM,skipNormalize:!0},Gd={http:Ax,https:uM,ws:Jd,wss:dM,urn:fM,"urn:uuid":pM};Object.setPrototypeOf(Gd,null);function zg(e){return e&&(Gd[e]||Gd[e.toLowerCase()])||void 0}Ix.exports={wsIsSecure:Kg,SCHEMES:Gd,isValidSchemeName:rM,getSchemeHandler:zg}});var Vx=I((Y5,ef)=>{"use strict";var{normalizeIPv6:$x,removeDotSegments:qc,removeDotSegmentsRelative:jx,recomposeAuthority:mM,normalizePercentEncoding:Jg,normalizePathEncoding:hM,serializePathEncoding:Px,normalizeQueryFragmentEncoding:Ox,encodeQuery:gM,encodeFragment:wM,reescapeHostDelimiters:yM,isIPv4:Dx,nonSimpleDomain:vM}=Ug(),{SCHEMES:qx,getSchemeHandler:Gg}=_x(),Lx=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Wx="URI scheme is malformed.",Yd="URI host is malformed.",kM=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function Tx(e){let t=String(e);if(!Lx.test(t))throw new TypeError(Wx);return t}function bM(e,t){return typeof e=="string"?e=PM(e,t):typeof e=="object"&&(e=Qd(_s(e,t),t)),e}function RM(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}=Xd(e,r),{parsed:a,malformedAuthorityOrPort:u,malformedPercentEncoding:p,malformedSchemeSpecific:d,malformedHost:m,malformedScheme:h}=Xd(t,r);if(s||u||o||p||c||d||l||m||f||h)throw new Error(i.error||a.error||"URI is malformed.");let g=Mx(i,a,r,!0),w=Gg(n&&n.scheme||g.scheme),k=g.host,y=k!==void 0&&k!==""&&(Dx(k)||$x(k).isIPV6);if(Hx(g,n||{},w,y))throw new Error(Yd);Fx(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,_s(g,r)}function Mx(e,t,n,r){let i={};if(r||(e=Qd(_s(e,n),n),t=Qd(_s(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=qc(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=qc(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=qc(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]!=="/"?jx(i.path):qc(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 SM(e,t,n){let r=Nx(e,n),i=Nx(t,n);return r!==void 0&&i!==void 0&&r===i}function _s(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=Tx(n.scheme));let s=Gg(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=Jg(n.path):n.path=Px(n.path,l)),r.reference!=="suffix"&&n.scheme&&(n.scheme=Tx(n.scheme),i.push(n.scheme,":"));let f=mM(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]!=="/"?jx(a):qc(a)),c&&(a=Px(a,!0)),f===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return n.query!==void 0&&i.push("?",gM(n.query)),n.fragment!==void 0&&i.push("#",wM(n.fragment)),i.join("")}var CM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,EM=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,xM=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function AM(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 Dc(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 Zd(e){return e[0]==="["&&e[e.length-1]==="]"}function IM(e){let t=e[4];return Dc(e[3])||t!==void 0&&!Zd(t)&&Dc(t)||Dc(e[6])||Dc(e[7])||Dc(e[8])}function Fx(e,t,n,r){if(Hx(e,t,n,r))return e.error=e.error||Yd,!0;if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!Zd(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&vM(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(!_M(i))return e.error=e.error||Yd,!0;e.host=i.hostname}return!1}function Hx(e,t,n,r){return!!(e.host&&r===!1&&!Zd(e.host)&&(t.domainHost||n&&n.domainHost)&&kM.test(e.host))}function _M(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Xd(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 u=e.match(EM);u!==null&&u[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",i=!0);let p=e.match(xM);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 d=e.match(CM);if(d){r.scheme=d[1],r.userinfo=d[3],r.host=d[4],r.port=parseInt(d[5],10),r.path=d[6]||"",r.query=d[7],r.fragment=d[8],r.scheme!==void 0&&(Lx.test(r.scheme)?r.scheme=r.scheme.toLowerCase():(r.error=r.error||Wx,f=!0)),s=IM(d),s&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=d[5]);let m=AM(r,d);if(m!==void 0&&(r.error=r.error||m,i=!0),r.host)if(Dx(r.host)===!1){let w=Zd(r.host),k=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,y=$x(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||Yd,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=Gg(n.scheme||r.scheme);if(l||(c=Fx(r,n,h,a)),e.indexOf("%")!==-1&&r.host!==void 0&&!l){let g=a?r.host:Jg(r.host,!0);a||(g=Jg(g.toLowerCase())),r.host=a||n.scheme!=="null"?yM(g,a):g}(!h||h&&!h.skipNormalize)&&(r.path&&(r.path=hM(r.path)),r.query&&(r.query=Ox(r.query)),r.fragment&&(r.fragment=Ox(r.fragment))),h&&h.parse&&(h.parse(r,n),h===qx.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 Qd(e,t){return Xd(e,t).parsed}function PM(e,t){return Bx(e,t).normalized}function Bx(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:c}=Xd(e,t);return{normalized:r||i||s||o||c?e:_s(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:c}}function Nx(e,t){if(typeof e!="string"&&typeof e!="object")return;let n;try{n=typeof e=="string"?e:_s(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:c,malformedScheme:l}=Bx(n,t);return i||s||o||c||l?void 0:r}var Yg={SCHEMES:qx,normalize:bM,resolve:RM,resolveComponent:Mx,equal:SM,serialize:_s,parse:Qd};ef.exports=Yg;ef.exports.default=Yg;ef.exports.fastUri=Yg});var Kx=I(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});var Ux=Vx();Ux.code='require("ajv/dist/runtime/uri").default';Xg.default=Ux});var eA=I($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.CodeGen=$t.Name=$t.nil=$t.stringify=$t.str=$t._=$t.KeywordCxt=void 0;var OM=$c();Object.defineProperty($t,"KeywordCxt",{enumerable:!0,get:function(){return OM.KeywordCxt}});var Vo=ge();Object.defineProperty($t,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty($t,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty($t,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty($t,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty($t,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty($t,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var TM=Ud(),Xx=jc(),NM=kg(),Lc=zd(),$M=ge(),Wc=Oc(),tf=Pc(),Zg=xe(),zx=gx(),jM=Kx(),Qx=(e,t)=>new RegExp(e,t);Qx.code="new RegExp";var DM=["removeAdditional","useDefaults","coerceTypes"],qM=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),LM={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."},WM={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Jx=200;function MM(e){var t,n,r,i,s,o,c,l,f,a,u,p,d,m,h,g,w,k,y,R,S,C,q,T,F;let B=e.strict,X=(t=e.code)===null||t===void 0?void 0:t.optimize,Y=X===!0||X===void 0?1:X||0,de=(r=(n=e.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Qx,G=(i=e.uriResolver)!==null&&i!==void 0?i:jM.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:B)!==null&&o!==void 0?o:!0,strictNumbers:(l=(c=e.strictNumbers)!==null&&c!==void 0?c:B)!==null&&l!==void 0?l:!0,strictTypes:(a=(f=e.strictTypes)!==null&&f!==void 0?f:B)!==null&&a!==void 0?a:"log",strictTuples:(p=(u=e.strictTuples)!==null&&u!==void 0?u:B)!==null&&p!==void 0?p:"log",strictRequired:(m=(d=e.strictRequired)!==null&&d!==void 0?d:B)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Y,regExp:de}:{optimize:Y,regExp:de},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Jx,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Jx,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:(S=e.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(C=e.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(q=e.validateFormats)!==null&&q!==void 0?q:!0,unicodeRegExp:(T=e.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(F=e.int32range)!==null&&F!==void 0?F:!0,uriResolver:G}}var Mc=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,...MM(t)};let{es5:n,lines:r}=this.opts.code;this.scope=new $M.ValueScope({scope:{},prefixes:qM,es5:n,lines:r}),this.logger=KM(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,NM.getRules)(),Gx.call(this,LM,t,"NOT SUPPORTED"),Gx.call(this,WM,t,"DEPRECATED","warn"),this._metaOpts=VM.call(this),t.formats&&HM.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&BM.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),FM.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:n,schemaId:r}=this.opts,i=zx;r==="id"&&(i={...zx},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,u){await s.call(this,a.$schema);let p=this._addSchema(a,u);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(u){if(!(u instanceof Xx.default))throw u;return c.call(this,u),await l.call(this,u.missingSchema),o.call(this,a)}}function c({missingSchema:a,missingRef:u}){if(this.refs[a])throw new Error(`AnySchema ${a} is loaded but ${u} cannot be resolved`)}async function l(a){let u=await f.call(this,a);this.refs[a]||await s.call(this,u.$schema),this.refs[a]||this.addSchema(u,a,n)}async function f(a){let u=this._loading[a];if(u)return u;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,Wc.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=Yx.call(this,t))=="string";)t=n;if(n===void 0){let{schemaId:r}=this.opts,i=new Lc.SchemaEnv({schema:{},schemaId:r});if(n=Lc.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=Yx.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,Wc.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(JM.call(this,r,n),!n)return(0,Zg.eachItem)(r,s=>Qg.call(this,s)),this;YM.call(this,n);let i={...n,type:(0,tf.getJSONTypes)(n.type),schemaType:(0,tf.getJSONTypes)(n.schemaType)};return(0,Zg.eachItem)(r,i.type.length===0?s=>Qg.call(this,s,i):s=>i.type.forEach(o=>Qg.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]=Zx(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,Wc.normalizeId)(o||r);let f=Wc.getSchemaRefs.call(this,t,r);return l=new Lc.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):Lc.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{Lc.compileSchema.call(this,t)}finally{this.opts=n}}};Mc.ValidationError=TM.default;Mc.MissingRefError=Xx.default;$t.default=Mc;function Gx(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 Yx(e){return e=(0,Wc.normalizeId)(e),this.schemas[e]||this.refs[e]}function FM(){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 HM(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function BM(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 VM(){let e={...this.opts};for(let t of DM)delete e[t];return e}var UM={log(){},warn(){},error(){}};function KM(e){if(e===!1)return UM;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 zM=/^[a-z_$][a-z0-9_$:-]*$/i;function JM(e,t){let{RULES:n}=this;if((0,Zg.eachItem)(e,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!zM.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 Qg(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,tf.getJSONTypes)(t.type),schemaType:(0,tf.getJSONTypes)(t.schemaType)}};t.before?GM.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 GM(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 YM(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Zx(t)),e.validateSchema=this.compile(t,!0))}var XM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Zx(e){return{anyOf:[e,XM]}}});var tA=I(ew=>{"use strict";Object.defineProperty(ew,"__esModule",{value:!0});var QM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ew.default=QM});var sA=I(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.callRef=Ps.getValidate=void 0;var ZM=jc(),nA=Wn(),yn=ge(),Uo=Mr(),rA=zd(),nf=xe(),eF={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 u();let a=rA.resolveRef.call(l,f,i,n);if(a===void 0)throw new ZM.default(r.opts.uriResolver,i,n);if(a instanceof rA.SchemaEnv)return p(a);return d(a);function u(){if(s===f)return rf(e,o,s,s.$async);let m=t.scopeValue("root",{ref:f});return rf(e,(0,yn._)`${m}.validate`,f,f.$async)}function p(m){let h=iA(e,m);rf(e,h,m,m.$async)}function d(m){let h=t.scopeValue("schema",c.code.source===!0?{ref:m,code:(0,yn.stringify)(m)}:{ref:m}),g=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:yn.nil,topSchemaRef:h,errSchemaPath:n},g);e.mergeEvaluated(w),e.ok(g)}}};function iA(e,t){let{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,yn._)`${n.scopeValue("wrapper",{ref:t})}.validate`}Ps.getValidate=iA;function rf(e,t,n,r){let{gen:i,it:s}=e,{allErrors:o,schemaEnv:c,opts:l}=s,f=l.passContext?Uo.default.this:yn.nil;r?a():u();function a(){if(!c.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,yn._)`await ${(0,nA.callValidateCode)(e,t,f)}`),d(t),o||i.assign(m,!0)},h=>{i.if((0,yn._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),p(h),o||i.assign(m,!1)}),e.ok(m)}function u(){e.result((0,nA.callValidateCode)(e,t,f),()=>d(t),()=>p(t))}function p(m){let h=(0,yn._)`${m}.errors`;i.assign(Uo.default.vErrors,(0,yn._)`${Uo.default.vErrors} === null ? ${h} : ${Uo.default.vErrors}.concat(${h})`),i.assign(Uo.default.errors,(0,yn._)`${Uo.default.vErrors}.length`)}function d(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=nf.mergeEvaluated.props(i,g.props,s.props));else{let w=i.var("props",(0,yn._)`${m}.evaluated.props`);s.props=nf.mergeEvaluated.props(i,w,s.props,yn.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=nf.mergeEvaluated.items(i,g.items,s.items));else{let w=i.var("items",(0,yn._)`${m}.evaluated.items`);s.items=nf.mergeEvaluated.items(i,w,s.items,yn.Name)}}}Ps.callRef=rf;Ps.default=eF});var oA=I(tw=>{"use strict";Object.defineProperty(tw,"__esModule",{value:!0});var tF=tA(),nF=sA(),rF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",tF.default,nF.default];tw.default=rF});var aA=I(nw=>{"use strict";Object.defineProperty(nw,"__esModule",{value:!0});var sf=ge(),$i=sf.operators,of={maximum:{okStr:"<=",ok:$i.LTE,fail:$i.GT},minimum:{okStr:">=",ok:$i.GTE,fail:$i.LT},exclusiveMaximum:{okStr:"<",ok:$i.LT,fail:$i.GTE},exclusiveMinimum:{okStr:">",ok:$i.GT,fail:$i.LTE}},iF={message:({keyword:e,schemaCode:t})=>(0,sf.str)`must be ${of[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,sf._)`{comparison: ${of[e].okStr}, limit: ${t}}`},sF={keyword:Object.keys(of),type:"number",schemaType:"number",$data:!0,error:iF,code(e){let{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,sf._)`${n} ${of[t].fail} ${r} || isNaN(${n})`)}};nw.default=sF});var cA=I(rw=>{"use strict";Object.defineProperty(rw,"__esModule",{value:!0});var Fc=ge(),oF={message:({schemaCode:e})=>(0,Fc.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,Fc._)`{multipleOf: ${e}}`},aF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:oF,code(e){let{gen:t,data:n,schemaCode:r,it:i}=e,s=i.opts.multipleOfPrecision,o=t.let("res"),c=s?(0,Fc._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,Fc._)`${o} !== parseInt(${o})`;e.fail$data((0,Fc._)`(${r} === 0 || (${o} = ${n}/${r}, ${c}))`)}};rw.default=aF});var sw=I(iw=>{"use strict";Object.defineProperty(iw,"__esModule",{value:!0});function lA(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}iw.default=lA;lA.code='require("ajv/dist/runtime/ucs2length").default'});var uA=I(ow=>{"use strict";Object.defineProperty(ow,"__esModule",{value:!0});var Os=ge(),cF=xe(),lF=sw(),uF={message({keyword:e,schemaCode:t}){let n=e==="maxLength"?"more":"fewer";return(0,Os.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,Os._)`{limit: ${e}}`},dF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:uF,code(e){let{keyword:t,data:n,schemaCode:r,it:i}=e,s=t==="maxLength"?Os.operators.GT:Os.operators.LT,o=i.opts.unicode===!1?(0,Os._)`${n}.length`:(0,Os._)`${(0,cF.useFunc)(e.gen,lF.default)}(${n})`;e.fail$data((0,Os._)`${o} ${s} ${r}`)}};ow.default=dF});var dA=I(aw=>{"use strict";Object.defineProperty(aw,"__esModule",{value:!0});var fF=Wn(),pF=xe(),Ko=ge(),mF={message:({schemaCode:e})=>(0,Ko.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,Ko._)`{pattern: ${e}}`},hF={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:mF,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,Ko._)`new RegExp`:(0,pF.useFunc)(t,l),a=t.let("valid");t.try(()=>t.assign(a,(0,Ko._)`${f}(${s}, ${c}).test(${n})`),()=>t.assign(a,!1)),e.fail$data((0,Ko._)`!${a}`)}else{let l=(0,fF.usePattern)(e,i);e.fail$data((0,Ko._)`!${l}.test(${n})`)}}};aw.default=hF});var fA=I(cw=>{"use strict";Object.defineProperty(cw,"__esModule",{value:!0});var Hc=ge(),gF={message({keyword:e,schemaCode:t}){let n=e==="maxProperties"?"more":"fewer";return(0,Hc.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,Hc._)`{limit: ${e}}`},wF={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:gF,code(e){let{keyword:t,data:n,schemaCode:r}=e,i=t==="maxProperties"?Hc.operators.GT:Hc.operators.LT;e.fail$data((0,Hc._)`Object.keys(${n}).length ${i} ${r}`)}};cw.default=wF});var pA=I(lw=>{"use strict";Object.defineProperty(lw,"__esModule",{value:!0});var Bc=Wn(),Vc=ge(),yF=xe(),vF={message:({params:{missingProperty:e}})=>(0,Vc.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Vc._)`{missingProperty: ${e}}`},kF={keyword:"required",type:"object",schemaType:"array",$data:!0,error:vF,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 d=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of n)if(d?.[h]===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,w=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,yF.checkStrictMode)(o,w,o.opts.strictRequired)}}function f(){if(l||s)e.block$data(Vc.nil,u);else for(let d of n)(0,Bc.checkReportMissingProp)(e,d)}function a(){let d=t.let("missing");if(l||s){let m=t.let("valid",!0);e.block$data(m,()=>p(d,m)),e.ok(m)}else t.if((0,Bc.checkMissingProp)(e,n,d)),(0,Bc.reportMissingProp)(e,d),t.else()}function u(){t.forOf("prop",r,d=>{e.setParams({missingProperty:d}),t.if((0,Bc.noPropertyInData)(t,i,d,c.ownProperties),()=>e.error())})}function p(d,m){e.setParams({missingProperty:d}),t.forOf(d,r,()=>{t.assign(m,(0,Bc.propertyInData)(t,i,d,c.ownProperties)),t.if((0,Vc.not)(m),()=>{e.error(),t.break()})},Vc.nil)}}};lw.default=kF});var mA=I(uw=>{"use strict";Object.defineProperty(uw,"__esModule",{value:!0});var Uc=ge(),bF={message({keyword:e,schemaCode:t}){let n=e==="maxItems"?"more":"fewer";return(0,Uc.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,Uc._)`{limit: ${e}}`},RF={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:bF,code(e){let{keyword:t,data:n,schemaCode:r}=e,i=t==="maxItems"?Uc.operators.GT:Uc.operators.LT;e.fail$data((0,Uc._)`${n}.length ${i} ${r}`)}};uw.default=RF});var af=I(dw=>{"use strict";Object.defineProperty(dw,"__esModule",{value:!0});var hA=Ig();hA.code='require("ajv/dist/runtime/equal").default';dw.default=hA});var gA=I(pw=>{"use strict";Object.defineProperty(pw,"__esModule",{value:!0});var fw=Pc(),jt=ge(),SF=xe(),CF=af(),EF={message:({params:{i:e,j:t}})=>(0,jt.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,jt._)`{i: ${e}, j: ${t}}`},xF={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:EF,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,fw.getSchemaTypes)(s.items):[];e.block$data(l,a,(0,jt._)`${o} === false`),e.ok(l);function a(){let m=t.let("i",(0,jt._)`${n}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(l,!0),t.if((0,jt._)`${m} > 1`,()=>(u()?p:d)(m,h))}function u(){return f.length>0&&!f.some(m=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),w=(0,fw.checkDataTypes)(f,g,c.opts.strictNumbers,fw.DataType.Wrong),k=t.const("indices",(0,jt._)`{}`);t.for((0,jt._)`;${m}--;`,()=>{t.let(g,(0,jt._)`${n}[${m}]`),t.if(w,(0,jt._)`continue`),f.length>1&&t.if((0,jt._)`typeof ${g} == "string"`,(0,jt._)`${g} += "_"`),t.if((0,jt._)`typeof ${k}[${g}] == "number"`,()=>{t.assign(h,(0,jt._)`${k}[${g}]`),e.error(),t.assign(l,!1).break()}).code((0,jt._)`${k}[${g}] = ${m}`)})}function d(m,h){let g=(0,SF.useFunc)(t,CF.default),w=t.name("outer");t.label(w).for((0,jt._)`;${m}--;`,()=>t.for((0,jt._)`${h} = ${m}; ${h}--;`,()=>t.if((0,jt._)`${g}(${n}[${m}], ${n}[${h}])`,()=>{e.error(),t.assign(l,!1).break(w)})))}}};pw.default=xF});var wA=I(hw=>{"use strict";Object.defineProperty(hw,"__esModule",{value:!0});var mw=ge(),AF=xe(),IF=af(),_F={message:"must be equal to constant",params:({schemaCode:e})=>(0,mw._)`{allowedValue: ${e}}`},PF={keyword:"const",$data:!0,error:_F,code(e){let{gen:t,data:n,$data:r,schemaCode:i,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,mw._)`!${(0,AF.useFunc)(t,IF.default)}(${n}, ${i})`):e.fail((0,mw._)`${s} !== ${n}`)}};hw.default=PF});var yA=I(gw=>{"use strict";Object.defineProperty(gw,"__esModule",{value:!0});var Kc=ge(),OF=xe(),TF=af(),NF={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Kc._)`{allowedValues: ${e}}`},$F={keyword:"enum",schemaType:"array",$data:!0,error:NF,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,OF.useFunc)(t,TF.default)),a;if(c||r)a=t.let("valid"),e.block$data(a,u);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let d=t.const("vSchema",s);a=(0,Kc.or)(...i.map((m,h)=>p(d,h)))}e.pass(a);function u(){t.assign(a,!1),t.forOf("v",s,d=>t.if((0,Kc._)`${f()}(${n}, ${d})`,()=>t.assign(a,!0).break()))}function p(d,m){let h=i[m];return typeof h=="object"&&h!==null?(0,Kc._)`${f()}(${n}, ${d}[${m}])`:(0,Kc._)`${n} === ${h}`}}};gw.default=$F});var vA=I(ww=>{"use strict";Object.defineProperty(ww,"__esModule",{value:!0});var jF=aA(),DF=cA(),qF=uA(),LF=dA(),WF=fA(),MF=pA(),FF=mA(),HF=gA(),BF=wA(),VF=yA(),UF=[jF.default,DF.default,qF.default,LF.default,WF.default,MF.default,FF.default,HF.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},BF.default,VF.default];ww.default=UF});var vw=I(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.validateAdditionalItems=void 0;var Ts=ge(),yw=xe(),KF={message:({params:{len:e}})=>(0,Ts.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Ts._)`{limit: ${e}}`},zF={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:KF,code(e){let{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,yw.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}kA(e,r)}};function kA(e,t){let{gen:n,schema:r,data:i,keyword:s,it:o}=e;o.items=!0;let c=n.const("len",(0,Ts._)`${i}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,Ts._)`${c} <= ${t.length}`);else if(typeof r=="object"&&!(0,yw.alwaysValidSchema)(o,r)){let f=n.var("valid",(0,Ts._)`${c} <= ${t.length}`);n.if((0,Ts.not)(f),()=>l(f)),e.ok(f)}function l(f){n.forRange("i",t.length,c,a=>{e.subschema({keyword:s,dataProp:a,dataPropType:yw.Type.Num},f),o.allErrors||n.if((0,Ts.not)(f),()=>n.break())})}}zc.validateAdditionalItems=kA;zc.default=zF});var kw=I(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.validateTuple=void 0;var bA=ge(),cf=xe(),JF=Wn(),GF={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:n}=e;if(Array.isArray(t))return RA(e,"additionalItems",t);n.items=!0,!(0,cf.alwaysValidSchema)(n,t)&&e.ok((0,JF.validateArray)(e))}};function RA(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=cf.mergeEvaluated.items(r,n.length,c.items));let l=r.name("valid"),f=r.const("len",(0,bA._)`${s}.length`);n.forEach((u,p)=>{(0,cf.alwaysValidSchema)(c,u)||(r.if((0,bA._)`${f} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},l)),e.ok(l))});function a(u){let{opts:p,errSchemaPath:d}=c,m=n.length,h=m===u.minItems&&(m===u.maxItems||u[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${d}"`;(0,cf.checkStrictMode)(c,g,p.strictTuples)}}}Jc.validateTuple=RA;Jc.default=GF});var SA=I(bw=>{"use strict";Object.defineProperty(bw,"__esModule",{value:!0});var YF=kw(),XF={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,YF.validateTuple)(e,"items")};bw.default=XF});var EA=I(Rw=>{"use strict";Object.defineProperty(Rw,"__esModule",{value:!0});var CA=ge(),QF=xe(),ZF=Wn(),eH=vw(),tH={message:({params:{len:e}})=>(0,CA.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,CA._)`{limit: ${e}}`},nH={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:tH,code(e){let{schema:t,parentSchema:n,it:r}=e,{prefixItems:i}=n;r.items=!0,!(0,QF.alwaysValidSchema)(r,t)&&(i?(0,eH.validateAdditionalItems)(e,i):e.ok((0,ZF.validateArray)(e)))}};Rw.default=nH});var xA=I(Sw=>{"use strict";Object.defineProperty(Sw,"__esModule",{value:!0});var Fn=ge(),lf=xe(),rH={message:({params:{min:e,max:t}})=>t===void 0?(0,Fn.str)`must contain at least ${e} valid item(s)`:(0,Fn.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Fn._)`{minContains: ${e}}`:(0,Fn._)`{minContains: ${e}, maxContains: ${t}}`},iH={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:rH,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,Fn._)`${i}.length`);if(e.setParams({min:o,max:c}),c===void 0&&o===0){(0,lf.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&o>c){(0,lf.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,lf.alwaysValidSchema)(s,n)){let h=(0,Fn._)`${a} >= ${o}`;c!==void 0&&(h=(0,Fn._)`${h} && ${a} <= ${c}`),e.pass(h);return}s.items=!0;let u=t.name("valid");c===void 0&&o===1?d(u,()=>t.if(u,()=>t.break())):o===0?(t.let(u,!0),c!==void 0&&t.if((0,Fn._)`${i}.length > 0`,p)):(t.let(u,!1),p()),e.result(u,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);d(h,()=>t.if(h,()=>m(g)))}function d(h,g){t.forRange("i",0,a,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:lf.Type.Num,compositeRule:!0},h),g()})}function m(h){t.code((0,Fn._)`${h}++`),c===void 0?t.if((0,Fn._)`${h} >= ${o}`,()=>t.assign(u,!0).break()):(t.if((0,Fn._)`${h} > ${c}`,()=>t.assign(u,!1).break()),o===1?t.assign(u,!0):t.if((0,Fn._)`${h} >= ${o}`,()=>t.assign(u,!0)))}}};Sw.default=iH});var _A=I(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.validateSchemaDeps=Cr.validatePropertyDeps=Cr.error=void 0;var Cw=ge(),sH=xe(),Gc=Wn();Cr.error={message:({params:{property:e,depsCount:t,deps:n}})=>{let r=t===1?"property":"properties";return(0,Cw.str)`must have ${r} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:n,missingProperty:r}})=>(0,Cw._)`{property: ${e},
|
|
154
|
+
missingProperty: ${r},
|
|
155
|
+
depsCount: ${t},
|
|
156
|
+
deps: ${n}}`};var oH={keyword:"dependencies",type:"object",schemaType:"object",error:Cr.error,code(e){let[t,n]=aH(e);AA(e,t),IA(e,n)}};function aH({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 AA(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,Gc.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,Gc.checkReportMissingProp)(e,f)}):(n.if((0,Cw._)`${l} && (${(0,Gc.checkMissingProp)(e,c,s)})`),(0,Gc.reportMissingProp)(e,s),n.else())}}Cr.validatePropertyDeps=AA;function IA(e,t=e.schema){let{gen:n,data:r,keyword:i,it:s}=e,o=n.name("valid");for(let c in t)(0,sH.alwaysValidSchema)(s,t[c])||(n.if((0,Gc.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))}Cr.validateSchemaDeps=IA;Cr.default=oH});var OA=I(Ew=>{"use strict";Object.defineProperty(Ew,"__esModule",{value:!0});var PA=ge(),cH=xe(),lH={message:"property name must be valid",params:({params:e})=>(0,PA._)`{propertyName: ${e.propertyName}}`},uH={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:lH,code(e){let{gen:t,schema:n,data:r,it:i}=e;if((0,cH.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,PA.not)(s),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(s)}};Ew.default=uH});var Aw=I(xw=>{"use strict";Object.defineProperty(xw,"__esModule",{value:!0});var uf=Wn(),or=ge(),dH=Mr(),df=xe(),fH={message:"must NOT have additional properties",params:({params:e})=>(0,or._)`{additionalProperty: ${e.additionalProperty}}`},pH={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:fH,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,df.alwaysValidSchema)(o,n))return;let f=(0,uf.allSchemaProperties)(r.properties),a=(0,uf.allSchemaProperties)(r.patternProperties);u(),e.ok((0,or._)`${s} === ${dH.default.errors}`);function u(){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,df.schemaRefOrVal)(o,r.properties,"properties");w=(0,uf.isOwnProperty)(t,k,g)}else f.length?w=(0,or.or)(...f.map(k=>(0,or._)`${g} === ${k}`)):w=or.nil;return a.length&&(w=(0,or.or)(w,...a.map(k=>(0,or._)`${(0,uf.usePattern)(e,k)}.test(${g})`))),(0,or.not)(w)}function d(g){t.code((0,or._)`delete ${i}[${g}]`)}function m(g){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){d(g);return}if(n===!1){e.setParams({additionalProperty:g}),e.error(),c||t.break();return}if(typeof n=="object"&&!(0,df.alwaysValidSchema)(o,n)){let w=t.name("valid");l.removeAdditional==="failing"?(h(g,w,!1),t.if((0,or.not)(w),()=>{e.reset(),d(g)})):(h(g,w),c||t.if((0,or.not)(w),()=>t.break()))}}function h(g,w,k){let y={keyword:"additionalProperties",dataProp:g,dataPropType:df.Type.Str};k===!1&&Object.assign(y,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(y,w)}}};xw.default=pH});var $A=I(_w=>{"use strict";Object.defineProperty(_w,"__esModule",{value:!0});var mH=$c(),TA=Wn(),Iw=xe(),NA=Aw(),hH={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&&NA.default.code(new mH.KeywordCxt(s,NA.default,"additionalProperties"));let o=(0,TA.allSchemaProperties)(n);for(let u of o)s.definedProperties.add(u);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Iw.mergeEvaluated.props(t,(0,Iw.toHash)(o),s.props));let c=o.filter(u=>!(0,Iw.alwaysValidSchema)(s,n[u]));if(c.length===0)return;let l=t.name("valid");for(let u of c)f(u)?a(u):(t.if((0,TA.propertyInData)(t,i,u,s.opts.ownProperties)),a(u),s.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(u),e.ok(l);function f(u){return s.opts.useDefaults&&!s.compositeRule&&n[u].default!==void 0}function a(u){e.subschema({keyword:"properties",schemaProp:u,dataProp:u},l)}}};_w.default=hH});var LA=I(Pw=>{"use strict";Object.defineProperty(Pw,"__esModule",{value:!0});var jA=Wn(),ff=ge(),DA=xe(),qA=xe(),gH={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,jA.allSchemaProperties)(n),l=c.filter(h=>(0,DA.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 ff.Name)&&(s.props=(0,qA.evaluatedPropsToName)(t,s.props));let{props:u}=s;p();function p(){for(let h of c)f&&d(h),s.allErrors?m(h):(t.var(a,!0),m(h),t.if(a))}function d(h){for(let g in f)new RegExp(h).test(g)&&(0,DA.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",r,g=>{t.if((0,ff._)`${(0,jA.usePattern)(e,h)}.test(${g})`,()=>{let w=l.includes(h);w||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:qA.Type.Str},a),s.opts.unevaluated&&u!==!0?t.assign((0,ff._)`${u}[${g}]`,!0):!w&&!s.allErrors&&t.if((0,ff.not)(a),()=>t.break())})})}}};Pw.default=gH});var WA=I(Ow=>{"use strict";Object.defineProperty(Ow,"__esModule",{value:!0});var wH=xe(),yH={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:n,it:r}=e;if((0,wH.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"}};Ow.default=yH});var MA=I(Tw=>{"use strict";Object.defineProperty(Tw,"__esModule",{value:!0});var vH=Wn(),kH={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:vH.validateUnion,error:{message:"must match a schema in anyOf"}};Tw.default=kH});var FA=I(Nw=>{"use strict";Object.defineProperty(Nw,"__esModule",{value:!0});var pf=ge(),bH=xe(),RH={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,pf._)`{passingSchemas: ${e.passing}}`},SH={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:RH,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,u)=>{let p;(0,bH.alwaysValidSchema)(i,a)?t.var(l,!0):p=e.subschema({keyword:"oneOf",schemaProp:u,compositeRule:!0},l),u>0&&t.if((0,pf._)`${l} && ${o}`).assign(o,!1).assign(c,(0,pf._)`[${c}, ${u}]`).else(),t.if(l,()=>{t.assign(o,!0),t.assign(c,u),p&&e.mergeEvaluated(p,pf.Name)})})}}};Nw.default=SH});var HA=I($w=>{"use strict";Object.defineProperty($w,"__esModule",{value:!0});var CH=xe(),EH={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,CH.alwaysValidSchema)(r,s))return;let c=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(c)})}};$w.default=EH});var UA=I(jw=>{"use strict";Object.defineProperty(jw,"__esModule",{value:!0});var mf=ge(),VA=xe(),xH={message:({params:e})=>(0,mf.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,mf._)`{failingKeyword: ${e.ifClause}}`},AH={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:xH,code(e){let{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,VA.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let i=BA(r,"then"),s=BA(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,mf.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,u){return()=>{let p=e.subschema({keyword:a},c);t.assign(o,c),e.mergeValidEvaluated(p,o),u?t.assign(u,(0,mf._)`${a}`):e.setParams({ifClause:a})}}}};function BA(e,t){let n=e.schema[t];return n!==void 0&&!(0,VA.alwaysValidSchema)(e,n)}jw.default=AH});var KA=I(Dw=>{"use strict";Object.defineProperty(Dw,"__esModule",{value:!0});var IH=xe(),_H={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,IH.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};Dw.default=_H});var zA=I(qw=>{"use strict";Object.defineProperty(qw,"__esModule",{value:!0});var PH=vw(),OH=SA(),TH=kw(),NH=EA(),$H=xA(),jH=_A(),DH=OA(),qH=Aw(),LH=$A(),WH=LA(),MH=WA(),FH=MA(),HH=FA(),BH=HA(),VH=UA(),UH=KA();function KH(e=!1){let t=[MH.default,FH.default,HH.default,BH.default,VH.default,UH.default,DH.default,qH.default,jH.default,LH.default,WH.default];return e?t.push(OH.default,NH.default):t.push(PH.default,TH.default),t.push($H.default),t}qw.default=KH});var JA=I(Lw=>{"use strict";Object.defineProperty(Lw,"__esModule",{value:!0});var ut=ge(),zH={message:({schemaCode:e})=>(0,ut.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ut._)`{format: ${e}}`},JH={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:zH,code(e,t){let{gen:n,data:r,$data:i,schema:s,schemaCode:o,it:c}=e,{opts:l,errSchemaPath:f,schemaEnv:a,self:u}=c;if(!l.validateFormats)return;i?p():d();function p(){let m=n.scopeValue("formats",{ref:u.formats,code:l.code.formats}),h=n.const("fDef",(0,ut._)`${m}[${o}]`),g=n.let("fType"),w=n.let("format");n.if((0,ut._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,ut._)`${h}.type || "string"`).assign(w,(0,ut._)`${h}.validate`),()=>n.assign(g,(0,ut._)`"string"`).assign(w,h)),e.fail$data((0,ut.or)(k(),y()));function k(){return l.strictSchema===!1?ut.nil:(0,ut._)`${o} && !${w}`}function y(){let R=a.$async?(0,ut._)`(${h}.async ? await ${w}(${r}) : ${w}(${r}))`:(0,ut._)`${w}(${r})`,S=(0,ut._)`(typeof ${w} == "function" ? ${R} : ${w}.test(${r}))`;return(0,ut._)`${w} && ${w} !== true && ${g} === ${t} && !${S}`}}function d(){let m=u.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){u.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${f}"`}}function y(S){let C=S instanceof RegExp?(0,ut.regexpCode)(S):l.code.formats?(0,ut._)`${l.code.formats}${(0,ut.getProperty)(s)}`:void 0,q=n.scopeValue("formats",{key:s,ref:S,code:C});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,ut._)`${q}.validate`]:["string",S,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,ut._)`await ${w}(${r})`}return typeof g=="function"?(0,ut._)`${w}(${r})`:(0,ut._)`${w}.test(${r})`}}}};Lw.default=JH});var GA=I(Ww=>{"use strict";Object.defineProperty(Ww,"__esModule",{value:!0});var GH=JA(),YH=[GH.default];Ww.default=YH});var YA=I(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.contentVocabulary=zo.metadataVocabulary=void 0;zo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];zo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var QA=I(Mw=>{"use strict";Object.defineProperty(Mw,"__esModule",{value:!0});var XH=oA(),QH=vA(),ZH=zA(),eB=GA(),XA=YA(),tB=[XH.default,QH.default,(0,ZH.default)(),eB.default,XA.metadataVocabulary,XA.contentVocabulary];Mw.default=tB});var eI=I(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});hf.DiscrError=void 0;var ZA;(function(e){e.Tag="tag",e.Mapping="mapping"})(ZA||(hf.DiscrError=ZA={}))});var nI=I(Hw=>{"use strict";Object.defineProperty(Hw,"__esModule",{value:!0});var Jo=ge(),Fw=eI(),tI=zd(),nB=jc(),rB=xe(),iB={message:({params:{discrError:e,tagName:t}})=>e===Fw.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Jo._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},sB={keyword:"discriminator",type:"object",schemaType:"object",error:iB,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,Jo._)`${n}${(0,Jo.getProperty)(c)}`);t.if((0,Jo._)`typeof ${f} == "string"`,()=>a(),()=>e.error(!1,{discrError:Fw.DiscrError.Tag,tag:f,tagName:c})),e.ok(l);function a(){let d=p();t.if(!1);for(let m in d)t.elseIf((0,Jo._)`${f} === ${m}`),t.assign(l,u(d[m]));t.else(),e.error(!1,{discrError:Fw.DiscrError.Mapping,tag:f,tagName:c}),t.endIf()}function u(d){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:d},m);return e.mergeEvaluated(h,Jo.Name),m}function p(){var d;let m={},h=w(i),g=!0;for(let R=0;R<o.length;R++){let S=o[R];if(S?.$ref&&!(0,rB.schemaHasRulesButRef)(S,s.self.RULES)){let q=S.$ref;if(S=tI.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,q),S instanceof tI.SchemaEnv&&(S=S.schema),S===void 0)throw new nB.default(s.opts.uriResolver,s.baseId,q)}let C=(d=S?.properties)===null||d===void 0?void 0:d[c];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);g=g&&(h||w(S)),k(C,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,S){if(R.const)y(R.const,S);else if(R.enum)for(let C of R.enum)y(C,S);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function y(R,S){if(typeof R!="string"||R in m)throw new Error(`discriminator: "${c}" values must be unique strings`);m[R]=S}}}};Hw.default=sB});var rI=I((L8,oB)=>{oB.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 sI=I((Ve,Bw)=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.MissingRefError=Ve.ValidationError=Ve.CodeGen=Ve.Name=Ve.nil=Ve.stringify=Ve.str=Ve._=Ve.KeywordCxt=Ve.Ajv=void 0;var aB=eA(),cB=QA(),lB=nI(),iI=rI(),uB=["/properties"],gf="http://json-schema.org/draft-07/schema",Go=class extends aB.default{_addVocabularies(){super._addVocabularies(),cB.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(lB.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(iI,uB):iI;this.addMetaSchema(t,gf,!1),this.refs["http://json-schema.org/schema"]=gf}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(gf)?gf:void 0)}};Ve.Ajv=Go;Bw.exports=Ve=Go;Bw.exports.Ajv=Go;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.default=Go;var dB=$c();Object.defineProperty(Ve,"KeywordCxt",{enumerable:!0,get:function(){return dB.KeywordCxt}});var Yo=ge();Object.defineProperty(Ve,"_",{enumerable:!0,get:function(){return Yo._}});Object.defineProperty(Ve,"str",{enumerable:!0,get:function(){return Yo.str}});Object.defineProperty(Ve,"stringify",{enumerable:!0,get:function(){return Yo.stringify}});Object.defineProperty(Ve,"nil",{enumerable:!0,get:function(){return Yo.nil}});Object.defineProperty(Ve,"Name",{enumerable:!0,get:function(){return Yo.Name}});Object.defineProperty(Ve,"CodeGen",{enumerable:!0,get:function(){return Yo.CodeGen}});var fB=Ud();Object.defineProperty(Ve,"ValidationError",{enumerable:!0,get:function(){return fB.default}});var pB=jc();Object.defineProperty(Ve,"MissingRefError",{enumerable:!0,get:function(){return pB.default}})});import{createRequire as NB}from"node:module";function Qo(e,t){if(!vf){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{vf=$B("node:sqlite").DatabaseSync}finally{process.emitWarning=n}}return t===void 0?new vf(e):new vf(e,t)}var $B,vf,kf=re(()=>{"use strict";$B=NB(import.meta.url??__filename)});import{AsyncLocalStorage as jB}from"node:async_hooks";function hI(e){return Math.max(0,Math.min(e,(mI.getStore()?.deadline??1/0)-performance.now()))}function gI(){let e=mI.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new Zw}var mI,Zw,wI=re(()=>{"use strict";mI=new jB,Zw=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}}});import{randomUUID as DB}from"node:crypto";import{promises as Di}from"node:fs";import Zc from"node:path";import{performance as yI}from"node:perf_hooks";async function vI(e){let t,n;try{let r=await Di.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 Di.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 qB(e){let t=e+".sqlite";try{let r=await Di.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=Qo(Zc.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 kI(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function LB(e,t={}){e=Zc.resolve(e),await Di.mkdir(Zc.dirname(e),{recursive:!0});let n=await Di.lstat(Zc.dirname(e));if(!n.isDirectory()||n.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+Zc.dirname(e));let r=yI.now()+hI(t.timeoutMs??3e4),i;for(;gI(),i=await qB(e),!i;){if(yI.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:DB(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let c=await vI(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 Di.unlink(e),await Di.writeFile(e,JSON.stringify(s),{mode:384,flag:"wx"})}catch(c){throw kI(i),c}let o=!1;return{owner:s,async release(){if(o)return!0;o=!0;let c=!0;try{let l=await vI(e);l?.token===s.nonce?l.owner?.createdAt===s.createdAt&&l.owner.operation===s.operation?await Di.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{kI(i)}return c}}}async function bI(e,t,n={}){let r=await LB(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 RI=re(()=>{"use strict";kf();wI()});import{execFileSync as TI}from"node:child_process";function NI(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=wr(()=>TI("git",["diff-tree","--stdin","--always","--no-renames","--name-status","-r","-z"],{cwd:e,input:t.join(`
|
|
161
|
+
`)+`
|
|
162
|
+
`,encoding:"utf8",timeout:QB,maxBuffer:ZB,windowsHide:!0}))}catch(o){if(!["ENOBUFS","ETIMEDOUT"].includes(o.code??""))throw o;return new Map(t.map(c=>[c,wr(()=>TI("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 QB,ZB,$I=re(()=>{"use strict";ds();qh();gd();QB=3e4,ZB=8*1024*1024});var dP=St(_t(),1);ic();import Rt from"path";Ot();ds();var Sh=St(_t(),1);Jn();import{execFileSync as Rh}from"child_process";import{promises as bD}from"fs";import RD from"path";Ot();Jn();un();Re();nt();fi();Re();var ac=St(_t(),1);cn();Re();Tt();Tt();Vu();import{randomUUID as pD}from"node:crypto";import yr from"path";import{AsyncLocalStorage as mD}from"node:async_hooks";var wS=new mD,sc=".comet-state-transaction.json";async function Nt(e,t){let n=await Pe(e);return wS.getStore()===n?t():wS.run(n,async()=>(await vS(e),t()))}async function oc(e,t){let n=t===sc?await Pe(e):e;try{return(await ue(n,t,Number.MAX_SAFE_INTEGER,{label:"Classic state transaction"})).bytes.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}function hD(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=os({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 vS(e){let t=await oc(e,sc);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 le(e),i=n.stateFile??Nu;if(typeof i!="string"||!$u(i)||yr.basename(r)!==i)throw new Error("Classic state transaction belongs to a different state filename; preserve files for recovery");let s=await oc(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=hD(s===n.afterYaml?n.afterRun:n.beforeRun);if(await le(e)!==r)throw new Error("Classic state filename changed during transaction recovery");o?await as(await Pe(e),o):await Za(await Pe(e));let c=await Pe(e);await pr(yr.join(c,sc),{containedRoot:c})}function kS(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 fs(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 yS(e,t,n){e.get(t)!==n&&e.set(t,n)}function bS(e,t){if(t.classic)for(let[n,r]of Object.entries(Ku(t.classic)))n==="auto_transition"&&r===null&&!e.has(n)||yS(e,n,r);else for(let n of mr)e.delete(n);uh(e.toJS(),t.run),t.run?yS(e,"run_id",t.run.runId):e.delete("run_id")}function gD(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 RS(e){let t=!1;for(let n of["build_command","verify_command"])e.has(n)&&(e.delete(n),t=!0);return t}async function bh(e){let t;try{t=(await ue(yr.dirname(e),yr.basename(e),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new ac.Document({})}let n=(0,ac.parseDocument)(t);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return fs(n),n}var wD=Et("classicStateProjection",e=>yD(e));async function Wt(e,t={}){return t.migrate===!1?wD(e):Nt(e,()=>vD(e,t))}async function yD(e){let t=await vh(e);if(t===null)return ln({});if((await V(t,sc,{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 bh(await le(e));RS(n);let r=fs(n),i=await Qa(t);return!i&&r.run_id&&r.skill&&(i=os(r)),kS(r,i),ln(r,i)}async function vD(e,t){let n=t.migrate!==!1,r=await le(e),i=await bh(r),s=fs(i),o=RS(i);o&&(s=fs(i));let c=await Qa(await Pe(e));if(kS(s,c),!c&&s.run_id&&s.skill){let{runStateFromDocument:l}=await Promise.resolve().then(()=>(Vu(),GR));c=l(s),c&&n&&(await as(await Pe(e),c),gD(i),o=!0)}return o&&n&&await We(r,i.toString(),{containedRoot:e}),ln(fs(i),c)}async function xo(e,t,n={}){let r=await le(e,{defaultFileName:Nu});if(await oc(e,yr.basename(r))===null){let i=new ac.Document({change_id:pD()});bS(i,{...t,unknownKeys:t.unknownKeys??[]}),ln(fs(i),t.run??null);let s=await ct(e),o=await hr(s),c=await Pt(o,`classic-changes/${i.get("change_id")}`,{label:"Classic initial Run"});t.run&&await as(c,t.run),await We(r,i.toString(),{containedRoot:e,exclusive:!0,beforeCommit:n.beforeCommit});return}return Nt(e,()=>kD(e,t,n))}async function kD(e,t,n){let r=await le(e),i=await oc(e,yr.basename(r));if(i!==null&&Lt(i))throw new Error("Classic managed Run state is owned by the SDK; compat writes are not allowed");let s=await bh(r);s.has("change_id")||s.set("change_id",yr.basename(await Pe(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");bS(s,{...t,unknownKeys:t.unknownKeys??[]}),ln(fs(s),t.run??null);let c=await oc(e,yr.basename(r)),l=s.toString();if(c===l){await n.beforeCommit?.(),t.run?await as(await Pe(e),t.run):await Za(await Pe(e));return}let f=await Pe(e),a=yr.join(f,sc);await We(a,JSON.stringify({schema:"comet.classic.state-transaction.v1",stateFile:yr.basename(r),beforeYaml:c,afterYaml:l,beforeRun:await Qa(await Pe(e)),afterRun:t.run}),{containedRoot:f});try{t.run?await as(await Pe(e),t.run):await Za(await Pe(e)),await We(r,l,{containedRoot:e,beforeCommit:n.beforeCommit})}catch(u){throw await vS(e).catch(()=>{}),u}await pr(a,{containedRoot:f}).catch(()=>{})}Ze();cn();Re();function rt(e){let t={cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0};try{let n=wr(()=>Rh("git",["rev-parse","--abbrev-ref","HEAD"],t).trim());if(n&&n!=="HEAD")return n}catch{}try{return wr(()=>Rh("git",["symbolic-ref","--quiet","--short","HEAD"],t).trim())||null}catch{return null}}var SD=fr("liveGitBranch",e=>rt(e));function Qt(e){try{return wr(()=>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 CD=fr("isGitWorkTree",e=>Qt(e)),ED=["current","branch","worktree"];function ps(e){return ED.includes(e)}function dn(e){return ps(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"}}async function CS(e,t){return t.heal?Nt(e,()=>SS(e,t)):SS(e,t)}async function SS(e,t){let n=await le(e),r=(0,Sh.parseDocument)(await bD.readFile(n,"utf8"),{uniqueKeys:!1});if(r.errors.length>0)throw new Error(`Invalid .comet.yaml: ${r.errors[0].message}`);let i=r.toJS()??{},s=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,c=ps(s),l=SD(t.cwd),f=c&&o===null&&l===null?CD(t.cwd):!0,a=dn({isolation:s,boundBranch:o,currentBranch:l,gitWorkTree:f});return a.status==="needs-heal"&&t.heal?(await xD(e,a.branch),{status:"healed",branch:a.branch,bindingRequired:c,currentBranch:l}):{...a,bindingRequired:c,currentBranch:l}}async function xD(e,t){return Nt(e,()=>AD(e,t))}async function AD(e,t){let n=await le(e),r=(await ue(e,RD.basename(n),rc,{label:"Classic branch binding"})).bytes.toString("utf8"),i=(0,Sh.parseDocument)(r,{uniqueKeys:!1});if(i.errors.length)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);i.set("bound_branch",t),await We(n,i.toString(),{containedRoot:e})}function ID(e){return e??"detached HEAD"}function ES(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${ID(n)}'.
|
|
163
|
+
Next: ask the user to confirm — switch back to '${t}', or run \`comet state rebind ${e}\` after explicit confirmation.`}function xS(e){return`change '${e}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}Hu();import ed from"path";var ms={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 mi(e,t){if(ed.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let n=ed.resolve(e),r=ed.resolve(n,t);if(r!==n&&!r.startsWith(n+ed.sep))throw new Error("Run path must stay inside the change directory")}async function AS(e,t,n,r={}){mi(e,t),await Mu(e,t,`${JSON.stringify(n)}
|
|
164
|
+
`,ms.trajectory,"Run trajectory",r)}async function IS(e,t,n={}){mi(e,t);let r=await is(e,t,ms.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 _S(e,t,n={}){mi(e,t);let r=await is(e,t,ms.artifacts,"Run artifacts",n);return r===null?{}:JSON.parse(r)}async function PS(e,t,n,r={}){mi(e,t),await ss(e,t,JSON.stringify(n,null,2)+`
|
|
165
|
+
`,ms.artifacts,"Run artifacts",r)}async function OS(e,t,n,r={}){mi(e,t),await ss(e,t,n,ms.context,"Run context",r)}async function TS(e,t,n={}){mi(e,t);let r=await is(e,t,ms.pendingAction,"Run pending action",n);return r===null?null:JSON.parse(r)}async function NS(e,t,n={}){mi(e,t),await Fu(e,t,"Run pending action",n)}async function $S(e,t,n,r={}){mi(e,t),await ss(e,t,JSON.stringify(n,null,2)+`
|
|
166
|
+
`,ms.checkpoint,"Run checkpoint",r)}fi();un();nt();import hi from"node:path";async function Ch(e,t){let n=hi.resolve(e,t),r=hi.relative(hi.resolve(e),n);if(hi.isAbsolute(t)||hi.isAbsolute(r)||r===".."||r.startsWith(`..${hi.sep}`))throw new Error("Run path must stay inside the change directory");let i=await ct(e),s=await bo(i,n,{readOnly:!0}),o=s?.root??e,c=s?.target??n,l=o===hi.parse(c).root?mt(i):o;return{root:l,ref:hi.relative(l,c).replaceAll("\\","/"),inspectionRoot:o,target:c}}async function gi(...e){return e[0]=await Pe(e[0]),AS(...e)}async function Ao(...e){let t=await Ch(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,IS(...e)}async function jS(...e){let t=await Ch(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,_S(...e)}async function td(...e){return e[0]=await Pe(e[0]),PS(...e)}async function nd(...e){return e[0]=await Pe(e[0]),OS(...e)}async function DS(...e){let t=await Ch(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,TS(...e)}async function qS(...e){return e[0]=await Pe(e[0]),NS(...e)}async function LS(...e){return e[0]=await Pe(e[0]),$S(...e)}import id from"path";import{createHash as PD}from"node:crypto";import{types as OD}from"node:util";var WS=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(WS,n)?WS[n]:"manual-review"}code;recovery};var Eh=new WeakMap,MS=new WeakMap;function On(e){return Eh.has(e)}function rd(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(OD.isProxy(c))throw new b("INVALID_JSON","仅接受无执行行为的 JSON 数据");let f=Eh.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?je(a.value):n?a.value:c}i.add(c);let u=0,p=m=>m&&typeof m=="object"?s.get(m)?.height??0:0,d=m=>(s.set(c,{value:m,height:u}),r&&(Object.freeze(c),Eh.set(c,u)),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);u=Math.max(u,1+p(y.value)),(t||n)&&w.push(R)}return d(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),S=String(Number(y))===y&&Number.isInteger(Number(y))&&Number(y)>=0&&Number(y)<4294967295,C=String(Number(R))===R&&Number.isInteger(Number(R))&&Number(R)>=0&&Number(R)<4294967295;return S||C?S&&C?Number(y)-Number(R):S?-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);u=Math.max(u,1+p(k.value)),(t||n)&&h.push([w,y])}return d(n?`{${h.map(([w,k])=>`${JSON.stringify(w)}:${k}`).join(",")}}`:t?Object.fromEntries(h):c)}finally{i.delete(c)}}return o(e,0)}function jr(e){return rd(e,!1,!0)}function et(e){return rd(e)}function je(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(je(e[r]));return n}let t={};for(let n of Object.keys(e)){let r=je(e[n]);n==="__proto__"?Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0}):t[n]=r}return t}function Tn(e){rd(e,!1)}function D(e){let t=e!==null&&typeof e=="object"&&On(e),n=t?MS.get(e):void 0;if(n!==void 0)return n;let r=PD("sha256").update(jr(e)).digest("hex");return t&&MS.set(e,r),r}function hs(e){return rd(e,!1,!1,!0),e}function TD(e){if(e!=="build"&&e!=="verify")throw new Error(`Invalid command check scope: '${String(e)}'`)}function ND(e,t="."){if(t.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=id.resolve(e),r=id.resolve(n,t);if(r!==n&&!r.startsWith(n+id.sep))throw new Error(`Command check cwd must resolve within the project root: '${t}'`);return id.relative(n,r).replaceAll("\\","/")||"."}async function $D(e,t,n,r){return Nt(e,async()=>{let s={sequence:(await HS(e,t.trajectoryRef)).maximumSequence+1,timestamp:new Date().toISOString(),runId:t.runId,type:n,data:r};return await gi(e,t.trajectoryRef,s),s})}async function FS(e,t,n,r,i){if(!r.verificationReport||i.exitCode!==0)throw new Error("接受 Verify 需要真实检查和报告");await $D(t,n,"checkpoint",{kind:"classic-accepted-verify-check",scope:"verify",sequence:i.sequence,...i.action?{actionId:i.action.id}:{},reportRef:r.verificationReport,checkEpoch:r.checkEpoch??0,verifiedAt:r.verifiedAt})}async function HS(e,t){let n=await Ao(e,t);return{events:n,maximumSequence:n.reduce((r,i)=>Math.max(r,i.sequence),0)}}async function xh(e,t,n,r){TD(r);let{events:i}=await HS(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=ND(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 Ah(e,t,n,r){let i=await xh(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 Wt(t,{migrate:!1})).classic;return s?.phase!=="archive"&&(i.checkEpoch??0)!==(s?.checkEpoch??0)?{record:null,reason:"报告属于较早阶段,请由 Agent 核对当前工作后提交结果"}:{record:i}}vo();Re();import wi from"path";Re();bn();nt();_n();import cc from"path";function jD(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function BS(e,t,n,r){let i=ot(n,"Classic handoff artifact pointer");if((await V(e,i,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await Gt(e),c=`${at(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 u=a[0];Co(u);let p=a.slice(2),d=cc.resolve(t);if(cc.dirname(d)!==cc.resolve(o.archiveDir))return null;let m=cc.basename(d),h=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(m);if(m!==u&&h?.[1]!==u)return null;await V(e,at(e,d),{label:"Classic archived change directory",expected:"directory"});let g=cc.join(d,".comet",...p),w=at(e,g);try{return await ue(e,w,r,{label:"Historical Classic archived handoff artifact"}),w}catch(k){if(jD(k))return null;throw k}}nt();_n();import gs from"node:path";function vr(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 VS(e){let t=vr(e);return t.missingFields.length===0&&t.invalidFields.length===0}function lc(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)}nt();Ze();async function sd(e,t,n,r={}){if(n.workflow!=="full"||n.buildMode!=="autonomous")return[];let i=[];if(r.requirePlan!==!1){let s=vr(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 Yn(e,n.designDoc,"Classic autonomous design"))&&i.push("design_doc must reference a nonempty technical design for autonomous full build"),r.requirePlan!==!1&&(await ws(e,n.plan,{requireNonempty:!0})).status!=="ready"&&i.push("plan must reference a nonempty implementation plan in the configured plans directory"),i}async function ws(e,t,n={}){if(!t||t==="null")return{status:"missing",recordedPath:null};let r=await Gt(e),i=gs.resolve(e,t),s=gs.relative(r.superpowersPlansDir,i);return gs.isAbsolute(t)||!s||s.startsWith(`..${gs.sep}`)||gs.isAbsolute(s)||s.includes(gs.sep)||gs.extname(s).toLowerCase()!==".md"?{status:"broken",recordedPath:t}:await lt(e,t,{label:`Classic build plan ${t}`,expected:"file"})&&(!n.requireNonempty||(await oe(e,t,{label:`Classic build plan ${t}`})).trim().length>0)?{status:"ready",recordedPath:t}:{status:"broken",recordedPath:t}}Ze();var DD=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,qD=/\s*<!-- comet-task:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->\s*$/u;function Mt(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=DD.exec(s);if(!c)continue;let l=qD.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 od(e,t){let n=Mt(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 US(e,t,n){let r=[...e.matchAll(/^<!-- comet-task-authority: (.+) -->$/gmu)];if(!r.length)return"legacy";if(r.length!==1||r[0][1]!==t)throw new Error("Plan task authority must point to this change tasks.md");if(Mt(e).length)throw new Error("Canonical plan must reference tasks, not maintain a second checkbox ledger");if(!n.length||n.some(o=>!o.id))throw new Error("Canonical plan requires stable task IDs");let i=new Set([...e.matchAll(/<!-- comet-task-ref:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->/gu)].map(o=>o[1])),s=new Set(n.map(o=>o.id));if([...i].some(o=>!s.has(o)))throw new Error("Plan references a missing task ID; update the plan mapping");if(n.some(o=>!i.has(o.id)))throw new Error("Plan must reference each task ID; update the plan mapping");return"canonical"}function ad(e,t){return wi.relative(e,t).split(wi.sep).join("/")}async function uc(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=at(e,Pu(e,c).openSpecRoot);if((s===l||s.startsWith(`${l}/`))&&(await V(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 Bm(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 LD(e,t,n,r){try{r??=await Gt(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 uc(e,"design.handoff",n,r);if(!n||i.satisfied||i.detail)return i;try{let s=await BS(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 Ih(e,t,n){return uc(e,t,ad(e,n))}async function WD(e,t){let n=wi.join(t,"specs"),r;try{r=await So(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]?ad(e,r[0]):void 0,detail:`${r.length} delta spec${r.length===1?"":"s"}`}}async function MD(e,t){let n,r=ad(e,t);try{n=(await ue(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=Mt(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 yi(e,t){return e.some(n=>n.code===t&&n.satisfied)}async function vi(e,t){let n=await ct(e),r=t.classic,i=wi.join(e,"proposal.md"),s=wi.join(e,"design.md"),o=wi.join(e,"tasks.md"),c=t.run?wi.resolve(e,t.run.checkpointRef):wi.join(e,".comet","checkpoint.json"),l,f;try{l=await Gt(n)}catch(u){f=u}let a=await Promise.all([Ih(n,"openspec.proposal",i),Ih(n,"openspec.design",s),Ih(n,"openspec.tasks",o),WD(n,e),uc(n,"design.document",r?.designDoc??null,l,f),(async()=>{let u=await uc(n,"build.plan",r?.plan??null,l,f);if(!u.satisfied)return u;try{let p=await ws(n,r?.plan??null,{requireNonempty:r?.buildMode==="autonomous"});return p.status==="ready"?u:{code:u.code,source:u.source,satisfied:!1,detail:`Implementation plan is ${p.status}`}}catch(p){return{code:u.code,source:u.source,satisfied:!1,detail:p instanceof Error?p.message:String(p)}}})(),MD(n,o),uc(n,"verification.report",r?.verificationReport??null,l,f),LD(n,e,r?.handoffContext??null,l),(async()=>{try{return{code:"run.checkpoint",source:ad(n,c),satisfied:await Yn(n,c,"Classic Run checkpoint")}}catch(u){return{code:"run.checkpoint",satisfied:!1,detail:u instanceof Error?u.message:String(u)}}})()]);return a.push({code:"archive.confirmed",satisfied:r?.archiveConfirmation==="confirmed"}),a}fi();import{promises as hC}from"fs";import Sn from"path";import{fileURLToPath as gC}from"url";Ot();fi();import{createHash as hq,randomUUID as gq}from"crypto";import{promises as Nh}from"fs";import Dr from"path";function FD(e){return e.classicProfile??e.workflow}function HD(e){return e.isolation!==null&&VS(e)}function BD(e){return(e.buildMode==="direct"||e.buildMode==="autonomous")&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function VD(e,t,n){if(e!=="full"&&t.verifyResult==="fail")return`${e}.build.execute`;if(e==="full"){if(yi(n,"build.plan")&&t.buildPause==="plan-ready")return"full.build.plan-ready";if(!HD(t))return"full.build.configure";if(!yi(n,"build.plan"))return"full.build.plan";if(t.verifyResult==="fail")return"full.build.fix"}else if(!BD(t))throw new Error(`${e} build configuration is incomplete`);return yi(n,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function UD(e,t,n){return t.verifyResult!=="pass"||!yi(n,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function KD(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 Io(e,t){let n=FD(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 yi(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return VD(n,e,t);case"verify":return UD(n,e,t);case"archive":return KD(n,e)}}Tt();function KS(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 oC,randomUUID as uq}from"crypto";import{promises as kt}from"fs";import ht from"path";var GS=St(_t(),1);import{promises as _h}from"fs";import Nn from"path";var zD=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],JD=["deterministic","adaptive"],GD=["function","mcp","script","agent"],YD=["none","read","write","external"],XD=["progress","step","completion"],QD=["artifact_exists","state_equals"];function ys(e,t,n){return new Error(`${e}: ${t} ${n}`)}function fn(e,t,n="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw ys(t,n,"must be an object")}function ki(e,t,n){if(!Array.isArray(e))throw ys(t,n,"must be an array")}function Zt(e,t,n){if(typeof e!="string")throw ys(t,n,"must be a string")}function Zn(e,t,n,r){t in e&&Zt(e[t],n,`${r}.${t}`)}function YS(e,t,n,r){if(t in e&&typeof e[t]!="boolean")throw ys(n,`${r}.${t}`,"must be a boolean")}function bi(e,t,n,r){if(typeof e!="string"||!t.includes(e))throw ys(n,r,`must be one of ${t.join(", ")}`)}function cd(e,t,n){ki(e,t,n),e.forEach((r,i)=>{Zt(r,t,`${n}[${i}]`)})}function zS(e,t,n){fn(e,t,n),Zt(e.name,t,`${n}.name`),Zt(e.description,t,`${n}.description`),YS(e,"required",t,n)}function ZD(e,t,n){fn(e,t,n),Zt(e.id,t,`${n}.id`),Zn(e,"source",t,n),Zn(e,"version",t,n)}function eq(e,t,n){fn(e,t,n),Zt(e.id,t,`${n}.id`),Zt(e.role,t,`${n}.role`),Zn(e,"instructions",t,n)}function tq(e,t,n){fn(e,t,n),Zt(e.id,t,`${n}.id`),bi(e.kind,GD,t,`${n}.kind`),Zt(e.source,t,`${n}.source`),bi(e.sideEffect,YD,t,`${n}.sideEffect`),YS(e,"requiresConfirmation",t,n)}function nq(e,t,n){fn(e,t,n),bi(e.type,zD,t,`${n}.type`),Zn(e,"ref",t,n),Zn(e,"prompt",t,n),Zn(e,"question",t,n),"options"in e&&cd(e.options,t,`${n}.options`)}function rq(e,t,n){fn(e,t,n),Zt(e.id,t,`${n}.id`),nq(e.action,t,`${n}.action`),Zn(e,"next",t,n),"completionEvals"in e&&cd(e.completionEvals,t,`${n}.completionEvals`)}function iq(e,t){let n="goal";fn(e,t,n),Zt(e.statement,t,`${n}.statement`),ki(e.inputs,t,`${n}.inputs`),e.inputs.forEach((r,i)=>{zS(r,t,`${n}.inputs[${i}]`)}),ki(e.outputs,t,`${n}.outputs`),e.outputs.forEach((r,i)=>{zS(r,t,`${n}.outputs[${i}]`)}),cd(e.success,t,`${n}.success`)}function sq(e,t){let n="orchestration";fn(e,t,n),bi(e.mode,JD,t,`${n}.mode`),Zn(e,"entry",t,n),"steps"in e&&(ki(e.steps,t,`${n}.steps`),e.steps.forEach((r,i)=>{rq(r,t,`${n}.steps[${i}]`)}))}function XS(e,t){return fn(e,t),bi(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),bi(e.kind,["Skill"],t,"kind"),fn(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"),iq(e.goal,t),sq(e.orchestration,t),ki(e.skills,t,"skills"),e.skills.forEach((n,r)=>{ZD(n,t,`skills[${r}]`)}),ki(e.agents,t,"agents"),e.agents.forEach((n,r)=>{eq(n,t,`agents[${r}]`)}),ki(e.tools,t,"tools"),e.tools.forEach((n,r)=>{tq(n,t,`tools[${r}]`)}),e}function QS(e,t){fn(e,t);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in e&&cd(e[n],t,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in e&&(typeof e[n]!="number"||!Number.isFinite(e[n])))throw ys(t,n,"must be a finite number");return e}function oq(e,t){return fn(e,t),"runtime"in e&&ZS(e.runtime,t,"runtime"),e}function ZS(e,t,n){return ki(e,t,n),e.forEach((r,i)=>{let s=`${n}[${i}]`;fn(r,t,s),Zt(r.id,t,`${s}.id`),bi(r.scope,XD,t,`${s}.scope`),bi(r.type,QD,t,`${s}.type`),Zn(r,"artifact",t,s),Zn(r,"field",t,s),Zn(r,"equals",t,s)}),e}async function Ph(e){let t=await _h.readFile(e,"utf8");try{return(0,GS.parse)(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw ys(e,"document",r)}}async function aq(e){try{return await Ph(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function JS(e){try{return await _h.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function cq(e){let t=Nn.join(e,"checks.yaml"),n=Nn.join(e,"evals.yaml"),[r,i]=await Promise.all([JS(t),JS(n)]);if(i)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return r?{document:oq(await Ph(t),t)}:{document:null}}async function eC(e){let t=Nn.resolve(e.root),n=Nn.resolve(e.controlRoot);e.requireSkillMarkdown&&await _h.access(Nn.join(t,"SKILL.md"));let r=Nn.join(n,"skill.yaml"),i=Nn.join(n,"guardrails.yaml"),s=XS(await Ph(r),r),o=await aq(i),c=o===null?null:QS(o,i),l=await cq(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 tC(e){let t=Nn.resolve(e);return eC({root:t,controlRoot:Nn.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function nC(e){let t=Nn.resolve(e);return eC({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function rC(e,t,n=Nn.join(t,"package.json")){fn(e,n);let r=e.packageKind==="runtime"?"runtime":void 0,i=XS(e.definition,n),s=QS(e.guardrails,n),o=ZS(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:Nn.resolve(t),packageKind:r,definition:i,guardrails:{...c,...s},evals:o}}import iC from"path";function lq(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 sC(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),lq(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=iC.posix.normalize(o.source.replaceAll("\\","/"));(iC.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 ld(e){return Array.isArray(e)?e.map(ld):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,ld(n)])):e}function dq(e){return ld({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function fq(e){return ht.posix.normalize(e.replaceAll("\\","/"))}function _o(e,t,n){let r=ht.relative(e,t);if(!(r===""||!ht.isAbsolute(r)&&!r.startsWith(`..${ht.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function aC(e,t,n){let r=fq(t);if(ht.posix.isAbsolute(r)||r===".."||r.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let i=ht.resolve(e,...r.split("/"));_o(e,i,n);let s;try{s=await kt.realpath(i)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${t}`,{cause:o}):o}if(_o(e,s,n),!(await kt.stat(s)).isFile())throw new Error(`${n} is not a file: ${t}`);return{path:r,content:await kt.readFile(s)}}async function pq(e){let t=await kt.realpath(e.root),n=e.packageKind==="runtime"?[]:[await aC(t,"SKILL.md","SKILL.md")];for(let r of e.definition.tools)r.kind==="script"&&n.push(await aC(t,r.source,`Script tool ${r.id}`));return n.sort((r,i)=>r.path.localeCompare(i.path))}function mq(e,t){let n=t.map(r=>({path:r.path,sha256:oC("sha256").update(r.content).digest("hex")}));return oC("sha256").update(JSON.stringify(ld({package:e,files:n}))).digest("hex")}function uC(e){return JSON.stringify(e,null,2)+`
|
|
167
|
+
`}async function dC(e){let t=dq(e),n=await pq(e);return{document:t,files:n,hash:mq(t,n)}}async function ud(e){return(await dC(e)).hash}async function cC(e){try{return await kt.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function lC(e,t){try{if((await kt.readFile(ht.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await kt.readFile(ht.join(e,"package.json"),"utf8")!==uC(t.document))throw new Error("package mismatch");for(let i of t.files)if(!(await kt.readFile(ht.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 Oh(e,t){let n=await dC(e),r=ht.resolve(t,".comet","skill-snapshots"),i=ht.join(r,n.hash);if(await kt.mkdir(r,{recursive:!0}),await cC(i))return await lC(i,n),{hash:n.hash,snapshotDir:i};let s=ht.join(r,`.tmp-${uq()}`);_o(r,s,"Temporary snapshot"),_o(r,i,"Published snapshot");try{await kt.mkdir(s);for(let o of n.files){let c=ht.join(s,...o.path.split("/"));_o(s,c,`Snapshot file ${o.path}`),await kt.mkdir(ht.dirname(c),{recursive:!0}),await kt.writeFile(c,o.content)}await kt.writeFile(ht.join(s,"package.json"),uC(n.document)),await kt.writeFile(ht.join(s,"sha256"),n.hash+`
|
|
168
|
+
`),await kt.rename(s,i)}catch(o){if(await cC(i)){try{await lC(i,n)}finally{await kt.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:i}}throw await kt.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:i}}async function Th(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let n=ht.resolve(e,".comet","skill-snapshots"),r=ht.join(n,t);_o(n,r,"Skill snapshot");try{let i=(await kt.readFile(ht.join(r,"sha256"),"utf8")).trim();if(i!==t)throw new Error(`stored hash is ${i||"(empty)"}`);let s=ht.join(r,"package.json"),o=JSON.parse(await kt.readFile(s,"utf8")),c=rC(o,r,s),l=sC(c);if(l.length>0)throw new Error(l.map(a=>` - ${a}`).join(`
|
|
169
|
+
`));let f=await ud(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})}}nt();Ze();Tt();async function fC(e){try{return await Nh.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function pC(e){return hq("sha256").update(e).digest("hex")}function wq(e){return pC(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function yq(e){return e.replaceAll(".","_").replaceAll("-","_")}async function vq(e,t){let n=await ct(e),r=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[yq(o.code),o.source])),i=Dr.join(e,"subagent-progress.md");await fC(i)&&(r.subagent_progress=Dr.relative(n,i).split(Dr.sep).join("/"));let s=t.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(r.handoff_context=s.source),r}function kq(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:cs,profile:t,source:"pre-migration"}}]}async function bq(e){await Promise.all(e.map(t=>Nh.rm(t,{recursive:!0,force:!0})))}async function mC(e,t){return Nt(e,()=>Rq(e,t))}async function Rq(e,t){let n=await ct(e),r=await oe(n,await le(e),{label:"Classic migration state"});if(Lt(r))throw new Error("Classic managed Run is owned by the SDK and cannot be migrated to compat");let i=await Wt(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!==cs)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 ud(t.skillPackage)!==i.run.skillHash)return await Th(await Pe(e),i.run.skillHash),{classic:s,run:i.run,evidence:await vi(e,i),migrated:!1,snapshotDir:Dr.join(await Pe(e),".comet","skill-snapshots",i.run.skillHash)};let m=await Oh(t.skillPackage,await Pe(e));return{classic:s,run:i.run,evidence:await vi(e,i),migrated:!1,snapshotDir:m.snapshotDir}}let c=await vi(e,i),l=Io(s,c);if(!t.skillPackage.definition.orchestration.steps?.some(d=>d.id===l))throw new Error(`Classic Skill package does not define resolved step: ${l}`);let f=await ud(t.skillPackage),a=Dr.join(await Pe(e),".comet","skill-snapshots",f),u=await fC(a),p=[];try{let d=await Oh(t.skillPackage,await Pe(e)),m=KS(t.skillPackage,t.runId?.()??gq(),d.hash);m.currentStep=l,l==="completed"&&(m.status="completed");let h={...s,classicProfile:o,classicMigration:cs},g=await vq(e,c),w=await ct(e),k=c.find(C=>C.code==="design.handoff"&&C.satisfied),y=null;k?.source&&(y=await oe(w,k.resolvedSource??k.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await nd(e,m.contextRef,y),p.push(Dr.resolve(await Pe(e),m.contextRef))),await td(e,m.artifactsRef,g),p.push(Dr.resolve(await Pe(e),m.artifactsRef));let R=(t.now?.()??new Date).toISOString(),S={runId:m.runId,stateVersion:1,trajectoryOffset:2,contextHash:y===null?null:pC(y),artifactsHash:wq(g),createdAt:R};await LS(e,m.checkpointRef,S),p.push(Dr.resolve(await Pe(e),m.checkpointRef)),p.push(Dr.resolve(await Pe(e),m.trajectoryRef));for(let C of kq(m,o,R))await gi(e,m.trajectoryRef,C);return await xo(e,{classic:h,run:m,unknownKeys:i.unknownKeys}),{classic:h,run:m,evidence:c,migrated:!0,snapshotDir:d.snapshotDir}}catch(d){throw await bq(p),u||await Nh.rm(a,{recursive:!0,force:!0}),d}}Tt();async function Sq(e){try{return(await hC.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dd(e){try{return(await hC.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Cq(e){return await Sq(e)?await dd(Sn.join(e,"skill.yaml"))?!0:await dd(Sn.join(e,"SKILL.md"))&&await dd(Sn.join(e,"comet","skill.yaml")):!1}function Eq(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 xq(){let e=Sn.dirname(gC(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Sn.resolve(e,"..","runtime","classic"),Sn.resolve(e,"..","..","comet","runtime","classic"),Sn.resolve(e,"..","..","assets","skills","comet","runtime","classic"),Sn.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Sn.resolve(e,"..","..","comet-classic"),Sn.resolve(e,"..","..","assets","skills","comet-classic"),Sn.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of t)if(await Cq(n))return n;return null}async function Aq(e){return await dd(Sn.join(e,"skill.yaml"))?nC(e):tC(e)}async function Po(e){let t=await xq();return mC(e,{skillPackage:t?await Aq(t):Eq(Sn.dirname(gC(import.meta.url)))})}async function wC(e){let t=await Wt(e),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return Po(e)}async function fd(e,t,n,r){return Nt(e,()=>Iq(e,t,n,r))}async function Iq(e,t,n,r){let i=await Wt(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 vi(e,{classic:t,run:n,unknownKeys:i.unknownKeys}),o=Io(t,s),c={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await xo(e,{classic:t,run:c,unknownKeys:i.unknownKeys});let l=await Ao(e,c.trajectoryRef);return await gi(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}Tt();var yC={"full.open":["openspec.proposal","openspec.tasks"],"full.design.handoff":["openspec.proposal","openspec.design","openspec.tasks"],"full.design.document":["design.handoff"],"full.build.plan":["openspec.tasks"],"full.build.plan-ready":["build.plan"],"full.build.configure":["build.plan"],"full.build.execute":["build.plan"],"full.build.complete":["build.tasks-complete"],"full.verify.run":["build.tasks-complete"],"full.verify.branch":["verification.report"],"full.archive.confirm":["verification.report"],"full.archive.execute":["archive.confirmed"]};function _q(e){return yC[e]?yC[e]:e.endsWith(".open")?["openspec.proposal","openspec.tasks"]:e.endsWith(".build.execute")?[]:e.endsWith(".build.complete")?["build.tasks-complete"]:e.endsWith(".verify.run")?["build.tasks-complete"]:e.endsWith(".verify.branch")?["verification.report"]:e.endsWith(".archive.confirm")?["verification.report"]:e.endsWith(".archive.execute")?["archive.confirmed"]:[]}function vC(e,t){let n=_q(e),r=n.filter(i=>!yi(t,i));return{stepId:e,passed:r.length===0,requiredEvidence:n,missingEvidence:r}}function Pq(e){switch(e){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}async function kC(e,t){try{let n=await wC(e),r=await vi(e,{classic:n.classic,run:n.run,unknownKeys:[]}),i=Io(n.classic,r);return{name:t,valid:!0,workflow:n.classic.workflow,phase:n.classic.phase,currentStep:i,nextCommand:Pq(n.classic.phase),runtimeMode:"engine-projection",runtimeEval:vC(i,r),evidence:r}}catch(n){return{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:n instanceof Error?n.message:String(n)}}}ic();vo();nt();import{randomUUID as Oq}from"node:crypto";function md(e){return e==="zh-CN"?"zh-CN":"en"}function dc(e,t,n){return e==="zh-CN"?n:t}var $h={open:{en:"open (clarifying the request)",zh:"open(需求澄清)"},design:{en:"design",zh:"design(方案设计)"},build:{en:"build",zh:"build(实现)"},verify:{en:"verify",zh:"verify(验证)"},archive:{en:"archive",zh:"archive(归档)"}};function pd(e,t){return $h[e]?dc(t,$h[e].en,$h[e].zh):e}function bC(e){let{name:t,phase:n,failed:r,total:i,locale:s}=e;return r===0?{summary:dc(s,`Change ${t} passed every check for leaving the ${pd(n,s)} stage (${i} total) and is ready to proceed.`,`需求 ${t} 通过了离开 ${pd(n,s)}阶段的全部 ${i} 项检查,可以继续推进。`)}:{summary:dc(s,`Change ${t} is not ready to leave the ${pd(n,s)} stage yet: ${r} of ${i} checks failed. The failing items below are the Agent's checklist, not user actions.`,`需求 ${t} 暂时还不能离开 ${pd(n,s)}阶段:${r}/${i} 项检查未通过。下方的失败项是给 Agent 的检查清单,不需要用户处理。`),user_message:dc(s,"A few preparation items are still missing before this change can move to the next stage; the Agent is filling them in and will continue afterwards.","这条需求要进入下一阶段还差几项准备工作;Agent 正在补齐,之后会自动继续。")}}function RC(e){let{name:t,locale:n}=e;return{summary:dc(n,`Handoff context for ${t} was written and recorded; the Build phase can resume from it.`,`需求 ${t} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}_n();Ze();function Tq(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(`
|
|
170
|
+
`)}async function jh(e){let{projectRoot:t,changeDir:n,change:r}=e,i=at(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 oe(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 Oo(e){let t=at(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 jh(e)).handoffContext===t+"/proposal.md":!1}async function Nq(e){let{projectRoot:t,changeDir:n,change:r}=e,i=[],s=[...["proposal.md","design.md","tasks.md"].map(c=>n+"/"+c),...await So(t,n+"/specs")];for(let c of s)await lt(t,c,{label:"Classic handoff source",expected:"file"})&&i.push({reference:at(t,c),content:await oe(t,c,{label:"Classic handoff source"})});await Yu(t,n+"/.comet/handoff","Classic handoff view directory");let o=n+"/.comet/handoff/design-context.md";return await Rn(t,o,Tq(r,"full","",i),{label:"Classic handoff view"}),at(t,o)}var sY=yo(async e=>{let[t,n,r,i]=e;if(n==="--hash-only")return{exitCode:64,stderr:`handoff --hash-only 已移除。由 Agent 读取实际文档并判断上下文是否需要更新。
|
|
171
|
+
`};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]
|
|
172
|
+
`};let s=us(t);if(s)return{exitCode:1,stderr:s};let o=De(),c=await Tr(o),l=await cS(t,c.projectRoot);return!l.exists||!l.stateExists?{exitCode:1,stderr:"Classic change directory or state is missing"}:Nt(l.directory,async()=>{let f=await Wt(l.directory);if(!f.classic||!["design","build"].includes(f.classic.phase))throw new Error("Design handoff requires phase: design or build");let a=await pi(o,l.directory);if(a.problems.length)throw new Error(a.problems.join(`
|
|
173
|
+
`));let u=await Po(l.directory),p=await DS(l.directory,u.run.pendingRef);if(u.run.pending&&p?.type!=="handoff")throw new Error("Another Classic action is pending");if(p&&u.run.pending!==p.id)throw new Error("Classic handoff pending identity does not match the original Run");let d=await jh({projectRoot:o,changeDir:l.directory,change:t,contextCompression:u.classic.contextCompression}),m=d.handoffContext.replace(/\.json$/u,".md"),h=await oe(o,m,{label:"Classic handoff"}),g=i==="--full"?await Nq({projectRoot:o,changeDir:l.directory,change:t}):null;await nd(l.directory,u.run.contextRef,h),await td(l.directory,u.run.artifactsRef,{...await jS(l.directory,u.run.artifactsRef),handoff_context:d.handoffContext,handoff_markdown:m});let w={...u.classic,...d},k={...u.run,pending:null};if(k.currentStep==="full.design.handoff"&&(k=await fd(l.directory,w,k,{actionId:p?.id??Oq(),kind:"classic-handoff"})),await xo(l.directory,{...f,classic:w,run:k}),p){let R=await Ao(l.directory,k.trajectoryRef);R.some(S=>S.type==="recovery_reconciled"&&S.data?.actionId===p.id)||await gi(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 qS(l.directory,u.run.pendingRef)}let y=RC({name:t,locale:md(w.language)});return{exitCode:0,envelope:y,stderr:y.summary+`
|
|
174
|
+
[HANDOFF] source `+d.handoffContext+(g?`
|
|
175
|
+
[HANDOFF] view `+g:"")+`
|
|
176
|
+
`}})});import{stripVTControlCharacters as $q}from"node:util";function kr(e,t={}){return{code:"CLASSIC_COMMAND_FAILED",message:$q(e instanceof Error?e.message:String(e)),...t}}nt();_n();Ze();import Dn from"node:path";import jq from"node:path";Ze();async function hd(e,t,n){let r=[];if(n.designDoc)try{(await oe(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(kr(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 Yn(e,jq.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}}nt();import{createHash as kd,randomUUID as xY}from"node:crypto";var OC=St(_t(),1);gd();qh();Jn();Re();un();Ze();fi();Ot();import $n from"node:path";var AC=["implementing","task-review","checkoff","done","blocked"];function Si(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic progress requires a JSON object");return e}function bd(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 jn(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 Lh(e,t){if(!Array.isArray(e)||e.length>200)throw new Error(`Invalid Classic progress ${t}`);return e.map(n=>jn(n,t))}function Fq(e){let t=Si(e);if(bd(t,["schemaVersion","taskIds","revision","stage","sessionId","evidence","unresolved","reviewRounds"]),t.schemaVersion!==1)throw new Error("Unsupported Classic checkpoint schemaVersion");let n=Lh(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(!AC.includes(t.stage))throw new Error(`Invalid Classic checkpoint stage '${String(t.stage)}'; stages: ${AC.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:jn(t.sessionId,"sessionId"),evidence:Lh(t.evidence,"evidence"),unresolved:Lh(t.unresolved,"unresolved"),reviewRounds:t.reviewRounds}}async function TC(e,t,n){let r=$n.join(t,".comet",n);if(await lt(e,r,{label:"Classic progress",expected:"file"}))return JSON.parse(await oe(e,r,{label:"Classic progress"}))}function Hq(e,t){let n=kd("sha256").update(t).digest("hex");return $n.join(mt(e),"classic-delivery",`${n}.json`)}async function Bq(e,t){let n=Hq(e,t);if(!await lt(e,n,{label:"Classic delivery reauthorization",expected:"file"}))return null;let r=Si(JSON.parse(await oe(e,n,{label:"Classic delivery reauthorization"})));if(bd(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=Mh({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:jn(r.previousAuthorizationId,"previousAuthorizationId"),authorizationId:jn(r.authorizationId,"authorizationId"),...i,targetBranch:i.targetBranch,...r.authorizedRemoteUrl===void 0?{}:{authorizedRemoteUrl:jn(r.authorizedRemoteUrl,"authorizedRemoteUrl")}}}async function NC(e,t,n){let r=await TC(e,t,"coordination.json");if(r===void 0)return{checkpoint:null,stale:!1};let i=Fq(r),s=new Set(Mt(n).map(o=>o.id));return{checkpoint:i,stale:i.taskIds.some(o=>!s.has(o))}}function Mh(e,t=!1){let n=Si(e);if(bd(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=jn(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=jn(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=jn(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=jn(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 $C(e){let t=(0,OC.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length)throw new Error("Invalid Classic delivery change state");return Si(t.toJS())}function Vq(e,t,n){return typeof e.run_id=="string"&&e.run_id?`run:${e.run_id}`:jC(e,t,n)}function jC(e,t,n){let r=e.archived===!0||$n.basename($n.dirname(t))==="archive"?$n.basename(t).replace(/^\d{4}-\d{2}-\d{2}-/u,""):$n.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:${kd("sha256").update(JSON.stringify([r,e.created_at,e.base_ref??$n.resolve(n)])).digest("hex")}`}function DC(e,t,n,r){let i=Vq(t,n,r);if(e===i)return i;if(typeof e=="string"&&e.startsWith("legacy:")&&e===jC(t,n,r))return e;throw new Error("Classic delivery change identity mismatch")}var Uq=Et("classicCurrentState",async(e,t)=>Kq(e,t));async function Kq(e,t){return $C(await oe(e,await le(t),{label:"Classic delivery state"}))}async function zq(e,t){return Uq(e,t)}var vd=class extends Error{constructor(t,n){super(`Classic delivery git command timed out: ${[t,...n].join(" ")}`)}};function Wh(e,t,n,r){return CC(t,n,{cwd:e,timeoutMs:5e3,env:xC({authentication:r})}).trim()}function pc(e,t,n,r=!1){try{return Wh(e,t,n,r)}catch{return null}}function Jq(e,t,n,r=!1){try{return Wh(e,t,n,r)}catch(i){if(!(i instanceof Ri)||!i.timedOut)return null;try{return Wh(e,t,n,r)}catch(s){if(s instanceof Ri&&s.timedOut)throw new vd(t,n);return null}}}function fc(e,t){return pc(e,"git",["-C",e,...t])}function wd(e,t){return Jq(e,"git",["-C",e,...t])}function IC(e,t,n=!1){return pc(e,"git",["-C",e,"remote","get-url",...n?["--push"]:[],t],!0)}function Gq(e,t){let n=$n.relative(e,t).replaceAll("\\","/");return[`:(literal)${n}`,...[".comet-state.lock",".comet-state-transaction.json",...[...yh].map(r=>`.comet/${r}`)].map(r=>`:(exclude,literal)${n}/${r}`)]}function _C(e,t,n,r){let i=$n.relative(e,t).replaceAll("\\","/"),s=Gq(e,t),o=wo.map(l=>wd(e,["show",`${n}:${i}/${l}`])).filter(l=>l!==null);if(o.length!==1)return!1;let c=o[0];try{let l=$C(c);return l.archived===!0&&DC(r,l,t,e)===r&&wd(e,["merge-base","--is-ancestor",n,"HEAD"])!==null&&wd(e,["diff","--quiet","--no-ext-diff","--no-textconv",n,"--",...s])!==null&&wd(e,["ls-files","--others","--exclude-standard","--",...s])===""}catch(l){if(l instanceof vd)throw l;return!1}}function Yq(e){return kd("sha256").update(e).digest("hex")+".json"}async function Xq(e,t){let n=Yq(t);return[{root:$n.dirname(mt(e)),file:$n.join(mt(e),"classic-delivery-receipts",n)}]}function Qq(e,t){let n=Si(e);if(bd(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=Mh({action:"local",targetBranch:"main",...n.commit!==void 0?{commit:n.commit}:{},...n.prUrl!==void 0?{prUrl:n.prUrl}:{}});return{schemaVersion:1,changeIdentity:t,authorizationId:jn(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:e1(n.archiveFiles)}}}async function Zq(e,t){let n=null;for(let r of await Xq(e,t)){if(!await lt(r.root,r.file,{label:"Classic delivery receipt",expected:"file"}))continue;let i=Qq(JSON.parse(await oe(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 e1(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 t1(e){return e.authorizationId===void 0?`legacy:${kd("sha256").update(JSON.stringify(e)).digest("hex")}`:jn(e.authorizationId,"authorizationId")}function PC(e,t,n){return t===n||fc(e,["merge-base","--is-ancestor",t,n])!==null}function n1(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 yd(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 qC(e,t,n={}){let r=n.evidence!==!1,i=await TC(e,t,"delivery.json");if(i===void 0)return{delivery:null,verification:{status:"needsAuthorization"}};let s=Si(i);if(s.schemaVersion!==1)throw new Error("Unsupported Classic delivery schemaVersion");let o=Mh(s,!0),c=await zq(e,t),l=DC(s.changeIdentity,c,t,e),f=t1(s),a=await Bq(e,l);if(a&&a.previousAuthorizationId!==f)throw new Error("Classic delivery reauthorization is stale for the sealed authorization");let u=a?{action:a.action,targetBranch:a.targetBranch,...a.remote===void 0?{}:{remote:a.remote}}:o,p=a?.authorizationId??f,d=await Zq(e,l),m=d?.authorizationId===p?d:null;if(m?.invalidated)return{delivery:null,verification:{status:"needsAuthorization",invalidated:!0}};for(let G of["commit","prUrl"]){if(G==="commit"&&m?.[G]&&u[G]&&m[G]!==u[G])throw new Error("Classic delivery receipt conflicts with authorization evidence");m?.[G]&&(u[G]=m[G])}let h=s.authorizedRemoteUrl===void 0?void 0:jn(s.authorizedRemoteUrl,"authorizedRemoteUrl"),g=a?.authorizedRemoteUrl??h,w={...u,schemaVersion:1,changeIdentity:l,authorizationId:p,...g?{authorizedRemoteUrl:g}:{}};if(u.action==="archive-only"){let G=c.archived===!0&&!!(m?.archiveCompleted||m?.archiveFiles);return{delivery:w,verification:{status:G?"complete":"needsVerification",archiveVerified:G}}}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=fc(e,["symbolic-ref","--quiet","--short","HEAD"]),y=$n.relative(e,t).replaceAll("\\","/"),R=null;!u.commit&&c.archived===!0&&(R=fc(e,["log","-20","--format=%H","HEAD","--",...wo.map(ie=>`:(literal)${y}/${ie}`)])?.split(/\r?\n/u).find(ie=>/^[a-f0-9]{40,64}$/u.test(ie)&&_C(e,t,ie,l))??null);let S=u.commit??R,C=!!S&&fc(e,["cat-file","-t",S])==="commit",q=c.archived===!0&&C&&_C(e,t,S,l),T=k===u.targetBranch&&(!c.bound_branch||a!==null||c.bound_branch===k)&&q,F=!1,B=!1,X=null,Y=n.verifyRemote&&u.action!=="local"?"unavailable":"notChecked",de="notChecked";if(n.verifyRemote&&T&&u.action!=="local"&&u.remote&&g&&IC(e,u.remote)===g&&IC(e,u.remote,!0)===g){let G=`refs/heads/${u.targetBranch}`,ie=pc(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",u.remote,G],!0),Ye=ie?.split(/\r?\n/u)??[],O=Ye.length===1?/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(Ye[0]):null,U=O?.[2]===G?O[1]:null;F=!!S&&!!U&&PC(e,S,U),Y=F?"verified":ie===""?"missing":ie===null||!U||fc(e,["cat-file","-t",U])!=="commit"?"unavailable":"missing";let ne=n1(g),Ke=ne&&u.prUrl?yd(u.prUrl,ne):null,x=F||ie==="",j=N=>N.headRefName===u.targetBranch&&typeof N.headRefOid=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(N.headRefOid)&&(F?N.headRefOid===U&&["OPEN","MERGED"].includes(N.state):ie===""&&N.state==="MERGED"&&!!S&&PC(e,S,N.headRefOid));if(x&&u.action==="pr"&&(de="unavailable"),x&&u.action==="pr"&&Ke&&ne){let N=pc(e,"gh",["pr","view",Ke,"--repo",ne,"--json","url,headRefName,headRefOid,state"],!0);try{let W=N?Si(JSON.parse(N)):null;B=!!W&&typeof W.url=="string"&&yd(W.url,ne)===Ke&&j(W),de=B?"verified":W?"missing":"unavailable"}catch{B=!1,de="unavailable"}}else if(x&&u.action==="pr"&&!u.prUrl&&ne){let N=pc(e,"gh",["pr","list","--repo",ne,"--head",u.targetBranch,"--state","all","--json","url,headRefName,headRefOid,state","--limit","100"],!0);try{let W=N===null?null:JSON.parse(N);if(!Array.isArray(W)||W.length>=100)throw new Error("Incomplete PR discovery");let K=W.map(Si).filter(se=>typeof se.url=="string"&&yd(se.url,ne)&&j(se));K.length===1?(X=yd(K[0].url,ne),B=!0,de="verified"):de=K.length===0?"missing":"unavailable"}catch{de="unavailable"}}}return{delivery:w,verification:{status:T&&(u.action==="local"||(u.action==="push"?F:B))?"complete":"needsVerification",currentBranch:k,commitExists:C,archiveCommitted:q,observedCommit:R,observedPrUrl:X,remoteVerified:F,prVerified:B,remoteStatus:Y,prStatus:de}}}Ze();fi();function LC(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 mc(e,t,n,r){return LC({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 Rd(e,t,n,r=!1,i,s={}){let o=await Gt(e),c=i===void 0?await Wt(t,{migrate:!1}):{classic:n,run:i??null},l=Dn.join(t,"tasks.md"),f=await lt(e,l,{label:"Classic task authority",expected:"file"}),a=f?await oe(e,l,{label:"Classic recovery task authority"}):"",u;try{u=Mt(a)}catch{u=[]}let p=u.find(q=>!q.completed)??null,m=!!(n.plan&&await lt(e,n.plan,{label:"Classic plan",expected:"file"}))?await oe(e,n.plan,{label:"Classic recovery plan mapping"}):"",h=od(m,u),g=n.workflow==="full"?await ws(e,n.plan):null,w=vr(n),k=w.missingFields.length>0||w.invalidFields.length>0,y=await NC(e,t,a),R=n.phase==="archive"?await qC(e,t):null,S={kind:"continue-phase",reason:"Continue the current phase using confirmed artifacts."},C=n.phase==="design"?await hd(e,t,n):null;if(C)S={kind:C.design==="invalid"?"repair-design":C.design==="missing"?"design":"complete-design",reason:C.design==="invalid"?"Repair only the reported Design Doc metadata or reference; preserve existing confirmed work.":C.design==="missing"?"Continue the existing design and obtain explicit confirmation before registering it.":`Retain the registered Design Doc. Handoff is ${C.handoff}; after confirming recorded user authorization, complete only the remaining Design steps.`,...C.design==="ready"?{cwd:e,argv:["comet","state","complete-design",Dn.basename(t),"--design-doc",n.designDoc,"--json"]}:{}};else if(n.phase==="build"){if(n.workflow==="full"&&!n.isolation?S={kind:"workspace",reason:"Resume /comet-open to restore the missing isolation decision without regenerating valid artifacts."}:n.workflow==="full"&&k?S={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:T})=>`${q} (${T})`).join("; ")}`]:[]].join("; ")}); retain confirmed settings and any valid plan.`}:n.workflow==="full"&&g?.status!=="ready"?S={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?S={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?S={kind:"paused",reason:"Keep the valid plan and confirmed configuration. Clear the explicit plan-ready pause only after the user asks to continue."}:u.length?p?S={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."}:S={kind:"check",reason:"All tasks done in the authoritative tasks.md. Revalidate or execute Build checks, then run guard --apply."}:S={kind:"reconcile-task",reason:"Restore the task authority and match existing work before proceeding."},S.kind==="reconcile-task"&&y.checkpoint&&!y.stale){let q=u.find(T=>y.checkpoint.taskIds.includes(T.id??"")&&!T.completed);q&&(S={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"?S={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"&&(S={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:Dn.relative(e,t).replaceAll("\\","/"),tasks:Dn.relative(e,l).replaceAll("\\","/"),designDoc:n.designDoc??Dn.relative(e,Dn.join(t,"design.md")).replaceAll("\\","/"),plan:n.plan,plansRoot:Dn.relative(e,Dn.join(o.superpowersRoot,"plans")).replaceAll("\\","/"),handoffContext:n.handoffContext},...C?{designReadiness:C,issues:C.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:S,continuation:{...S,cwd:e,...n.archived?{}:{contextRequest:mc(n,e,void 0,Dn.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:u.length,completed:u.filter(q=>q.completed).length,needsIds:u.some(q=>!q.id),next:p,...r?{tasks:u}:{}},planMapping:{status:h.unmapped.length?"reconciliation-required":"ready",unmappedCount:h.unmapped.length,...r?{unmapped:h.unmapped}:{}},coordination:{path:y.checkpoint?(await bo(e,Dn.join(t,".comet","coordination.json"),{readOnly:!0}))?.target??Dn.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?[Dn.resolve(e,n.plan)]:[]]}}Ot();un();import{promises as NV}from"node:fs";var Cy=St(_t(),1);import y_ from"node:path";un();Jn();cn();Qi();Re();un();import{promises as r1}from"node:fs";import{AsyncLocalStorage as i1}from"node:async_hooks";import er from"node:path";var ks="comet.change-owner.v1",MC=["native","classic-full","classic-hotfix","classic-tweak"],s1=Et("changeOwnerRuntimeRoots",e=>wh(e)),FC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function tr(e,t,n="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!FC.test(t))throw new Error(`Invalid change name: ${t}`);return`${n==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function Hh(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===ks&&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)&&!MC.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 Sd(e,t,n,r){let i;try{({bytes:i}=await ue(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 Hh(s,n,r)}function HC(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function BC(e,t){return tr(e,t),`change-owner-records/${e}/${t}.json`}async function Bh(e,t,n){let r;try{r=await ue(e,BC(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:Hh(i,t,n),identity:HC(r.stat)}}async function VC(e,t,n){let r=await Ua(e,"change owner bindings"),i=async c=>{try{let{stat:l}=await r.stat(tr(t,n,c));return HC(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 o1(e,t,n=!1){let r=await VC(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 Bh(e,t.workflow,t.change);if(i?.identity&&i.identity===(r.active??r.history))return;let s=BC(t.workflow,t.change);await Pt(e,er.posix.dirname(s),{label:"canonical change runtime owners"});let o=tr(t.workflow,t.change,r.active?"active":"history");try{await CR(er.join(e,o),er.join(e,s),{containedRoot:e})}catch(c){if(!["ENOTSUP","EOPNOTSUPP"].includes(c.code??""))throw c}}async function a1(e,t,n){let r;try{r=await Bh(e,t,n)}catch(s){if(s instanceof Ct&&s.reason==="changed")return null;throw s}if(!r?.identity)return null;let i=await VC(e,t,n);return i.active===r.identity&&i.history===null||i.history===r.identity&&i.active===null?r:null}var vs=new i1,UC=fr("verifiedOwnerBatchResults",()=>new Map),KC=(e,t,n)=>`${JSON.stringify([e,t])}\0${n}`;async function zC(e){let t=vs.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??s1(e)}async function JC(e,t,n=!1){let r=vs.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 vs.run(i,()=>di(()=>n?fR(t):t())),o=UC();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 Fh(e,t,n){let r=await a1(e,t,n);return r?r.owner:JC([e],async()=>{let i=await Sd(e,tr(t,n),t,n),s=await Sd(e,tr(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 Ci(e,t,n,r={}){if(tr(t,n),!r.readOnly)return vs.run(null,()=>di(async()=>Fh(await Nr(e),t,n)));let[i,s]=await zC(e),o=er.parse(i).root,l=(await V(o,er.relative(o,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await Fh(i,t,n):null,f=s?await Fh(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 WC(e,t,n,r={}){let i=await Ci(e,t,n,r),s=i?.format==="sdk"?i:null,o=vs.getStore();return r.readOnly&&o?.active&&o.owners.set(KC(e,t,n),s),s}async function Ei(e,t,n,r={}){if(!r.readOnly||vs.getStore()?.active)return WC(e,t,n,r);let i=UC(),s=KC(e,t,n);if(i.has(s))return i.get(s);let o=WC(e,t,n,r).catch(c=>{throw i.get(s)===o&&i.delete(s),c});return i.set(s,o),o}async function c1(e,t,n,r=!1){tr(t,"validate");let i=n.readOnly?await zC(e):[await Nr(e)],s=async()=>{let o={active:new Set,history:new Set};for(let c of i)for(let l of["active","history"]){let f=er.parse(c).root,a=er.posix.dirname(tr(t,"validate",l)),u=await V(f,er.relative(f,er.join(c,a)).replaceAll("\\","/"),{label:`${t} ${l} change runtime owners`,expected:"directory"});if(!u.exists)continue;let p=await r1.readdir(u.target,{withFileTypes:!0});for(let d of p){if(d.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(d.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(d.isFile()&&h.test(d.name)||d.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(d.name))continue}if(!d.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${d.name}`);let m=d.name.slice(0,-5);if(!d.isFile()||!FC.test(m))throw new Error(`Invalid ${t} change runtime owner entry: ${d.name}`);o[l].add(m)}}return o};return r?s():JC(i,s)}var c5=Et("changeOwnerPartitions",c1);async function l1(e,t,n){return dR(),vs.run(null,()=>di(async()=>{let r=await hr(e);return tr(t.workflow,t.change),n(r)}))}async function GC(e,t,n={}){let r=tr(t.workflow,t.change),i=Hh(t,t.workflow,t.change);return l1(e,i,async s=>{if(await Sd(s,tr(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 Pt(s,er.posix.dirname(r),{label:"change runtime owner directory"});try{await We(er.join(s,...r.split("/")),`${JSON.stringify(i)}
|
|
177
|
+
`,{containedRoot:s,exclusive:!0,requireAtomicPublication:!0})}catch(c){if(c.code!=="EEXIST")throw c;let l=await Sd(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 Bh(s,t.workflow,t.change))&&await o1(s,i),i})}function hc(e,t,n={}){return GC(e,t,n)}function YC(e,t){return GC(e,t)}Re();_n();import TV from"node:path";import{randomUUID as v1}from"node:crypto";import{types as u1}from"node:util";import{createHash as d1}from"node:crypto";var XC=new WeakMap,QC=new WeakMap;function ZC(e,t){let n=e!==null&&typeof e=="object"&&t?.(e);if(n){let i=QC.get(e);if(i!==void 0)return i}let r=JSON.stringify(e);return n&&r.length<=64*1024&&QC.set(e,r),r}function f1(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,u=new WeakMap,p=new Map,d=new Map,m=new Map,h=w=>{let k=w&&typeof w=="object"?u.get(w):void 0;if(k!==void 0)return k;let y=ZC(w,n);return k=f.get(y),k===void 0&&(k=o.length,o.push(w),f.set(y,k)),w&&typeof w=="object"&&u.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(([S,C])=>[S,h(C)]),removed:[...w.removed]}),m.set(w,R),R};for(let w of t){let k=s,y=e;for(let F of w.path.slice(0,-1)){y=y[F];let B=i(y);Object.defineProperty(k,F,{value:B,enumerable:!0,writable:!0,configurable:!0}),k=B}let R=w.path.at(-1),S=k[R];if(!S||typeof S!="object"||Array.isArray(S))continue;if(n?.(S)){let F=XC.get(S);if(!F){let B=S,X=d.get(w.group),Y=Object.entries(B),de=X?Y.filter(([Ye,O])=>!Object.hasOwn(X.source,Ye)||h(X.source[Ye])!==h(O)):Y,G=X?Object.keys(X.source).filter(Ye=>!Object.hasOwn(B,Ye)):[],ie=X&&de.length+G.length<Y.length;F={...ie?{base:X.node}:{},entries:ie?de:Y,removed:ie?G:[]},XC.set(S,F)}d.set(w.group,{source:S,node:F}),l.push({path:w.path,map:g(F)}),Object.defineProperty(k,R,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let C=new Map;for(let[F,B]of Object.entries(S)){let X=B&&typeof B=="object"?u.get(B):void 0;if(X===void 0){let Y=ZC(B,n);X=f.get(Y),X===void 0&&(X=o.length,o.push(B),f.set(Y,X)),B&&typeof B=="object"&&u.set(B,X)}C.set(F,X)}let q=JSON.stringify([...C]),T=a.get(q);if(T===void 0){let F=p.get(w.group),B=[...C].filter(([de,G])=>F?.entries.get(de)!==G),X=F?[...F.entries.keys()].filter(de=>!C.has(de)):[],Y=F&&B.length+X.length<C.size;T=c.length,c.push({...Y?{base:F.id}:{},entries:Y?B:[...C],removed:Y?X:[]}),a.set(q,T)}p.set(w.group,{id:T,entries:C}),l.push({path:w.path,map:T}),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 p1(){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 tE(e){let{nodes:t,set:n}=p1(),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,u]of l.entries)f=n(f,a,u);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],u=o(a.left),p=o(a.right),d=i.length;return i.push({...a,left:u,right:p}),s.set(l,d),d},c=r.map(o);return{version:3,values:e.values,nodes:i,maps:c,bindings:e.bindings}}function nE(e,t,n){let r=f1(e,t,n);return{record:r.record,...r.pool?{pool:tE(r.pool)}:{}}}var qr=new WeakMap,gc=new WeakMap;function*Cd(e,t=e.root){if(t===null)return;let n=e.pool.nodes[t];yield*Cd(e,n.left),yield[n.key,e.pool.values[n.value]],yield*Cd(e,n.right)}function m1(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:()=>[...Cd(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 qr.set(n,e),n}var it=e=>{throw new Error(e)},To=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;function rE(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return it("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(s=>!["version","values","maps","bindings"].includes(s))&&it("JSON 引用池字段无效"),i.maps.forEach((s,o)=>{(!s||!Array.isArray(s.entries)||!Array.isArray(s.removed)||s.base!==void 0&&!To(s.base,o)||Object.keys(s).some(l=>!["base","entries","removed"].includes(l)))&&it("JSON 映射引用无效");let c=new Set;for(let l of s.removed)(typeof l!="string"||c.has(l))&&it("JSON 删除键无效"),c.add(l);for(let l of s.entries)(!Array.isArray(l)||l.length!==2||typeof l[0]!="string"||!To(l[1],i.values.length)||c.has(l[0]))&&it("JSON 值引用无效"),c.add(l[0])}),rE(tE(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 it("JSON 引用池版本或字段无效");let r=[];return n.nodes.forEach((i,s)=>{(!i||typeof i.key!="string"||!To(i.value,n.values.length)||![i.left,i.right].every(l=>l===null||To(l,s))||Object.keys(i).some(l=>!["key","value","left","right","height"].includes(l)))&&it("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)&&it("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&&!To(i,n.nodes.length))&&it("JSON 映射根无效"),n}function h1(e,t){let n=(m,h=0,g=new Set)=>{if(h>64&&it("JSON 数据嵌套过深"),!(m===null||typeof m=="string"||typeof m=="boolean"||typeof m=="number"&&Number.isFinite(m))){if(typeof m!="object"||m===null||u1.isProxy(m)||g.has(m))return it("JSON 数据无效");Object.getPrototypeOf(m)!==Object.prototype&&Object.getPrototypeOf(m)!==null&&!Array.isArray(m)&&it("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))&&it("JSON 数据不能包含访问器"),n(k.value,h+1,g)}Array.isArray(m)&&Object.keys(m).length!==m.length&&it("JSON 数组不能稀疏"),g.delete(m)}};n(e),n(t);let r=rE(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))||!To(m.map,r.maps.length)||Object.keys(m).some(k=>!["path","map"].includes(k)))&&it("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)))))&&it("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))&&it("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)&&it("JSON 池绑定必须替换空对象"),Object.defineProperty(g,w,{value:m1({pool:r,root:r.maps[m.map],stats:s,checked:l,origins:f}),enumerable:!0,writable:!0,configurable:!0})}let a=new WeakMap,u=new Map,p=m=>{if(!m||typeof m!="object")return 0;let h=a.get(m);if(h!==void 0)return h;let g=qr.get(m),w=y=>{if(y===null)return 0;let R=u.get(y);if(R!==void 0)return R;let S=r.nodes[y],C=Math.max(1+p(r.values[S.value]),w(S.left),w(S.right));return u.set(y,C),C},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&&it("JSON 逻辑数据嵌套超过 64 层"),wc(r),wc(i);let d=m=>{if(!(!m||typeof m!="object"||qr.has(m)||gc.has(m))){gc.set(m,s);for(let h of Object.values(m))d(h)}};return d(i),{value:i,stats:s,materialize:(m=[])=>pn(m.reduce((h,g)=>h?.[g],i)),hash:()=>Ft(i)}}function wc(e){let t=new WeakSet,n=r=>{if(!(!r||typeof r!="object"||qr.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 pn(e){if(e===null||typeof e!="object")return e;let t=qr.get(e);if(t){t.stats.materializedMaps++;let n=[...Cd(t)];return t.stats.materializedEntries+=n.length,Object.fromEntries(n.map(([r,i])=>[r,pn(i)]))}return Array.isArray(e)?e.map(pn):Object.fromEntries(Object.entries(e).map(([n,r])=>[n,pn(r)]))}function Ed(e,t){let n=qr.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 xd(e,t,n){let r=qr.get(e),i=(c,l)=>{let f=l.sequence;return t.get(f)!==c&&it("WorkflowRun 结果来源不一致"),f};if(!r){for(let[c,l]of Object.entries(e))i(c,l)>=n&&it("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&&it("WorkflowRun 结果序号无效")}function g1(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 eE=new WeakMap;function Ft(e,t={}){let n=d1("sha256"),r=e&&typeof e=="object"?gc.get(e):void 0,i=f=>{if(!f||typeof f!="object")return;let a=qr.get(f)?.stats??gc.get(f);if(a)return a;for(let u of Object.values(f)){let p=i(u);if(p)return p}};r??=i(e);let s=r&&t.cachePrefixes!==!1?eE.get(r):void 0;r&&!s&&t.cachePrefixes!==!1&&(s={root:{hash:n.copy(),next:new Map},size:0},eE.set(r,s));let o=s?.root,c=f=>{let a=Buffer.byteLength(f);r&&(r.logicalHashBytes+=a);let u=o?.next.get(f);if(u){n=u.hash.copy(),o=u;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,u)=>{u&&c(","),l(a)}),c("]");return}c("{"),g1(f).forEach((a,u)=>{u&&c(","),c(JSON.stringify(a)+":"),l(f[a])}),c("}")};return l(e),n.digest("hex")}function yc(e){return gc.get(e)??qr.get(e)?.stats}function Ad(e,t,n=!0){let r=h1(e,t);return n?r.materialize():r.value}function bt(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new b("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function br(e){return On(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function Vh(e,t,n){if(t!==e.attempt||n!==e.inputHash)throw new b("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function Uh(e){return["succeeded","failed","cancelled"].includes(e.status)}function iE(e){return sE(e,e.input)}function sE(e,t,n){for(let o of["id","runId","stepId","type"])bt(e[o],o);e.ref!==void 0&&bt(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)bt(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??D(t),status:"pending",retry:i,requiredCapabilities:[...new Set(s)],receipts:[],reconciliations:[]}}function oE(e,t){Vh(e,t.attempt,t.inputHash),bt(t.executorId,"executorId"),bt(t.token,"token"),t.sessionId!==void 0&&bt(t.sessionId,"sessionId");let n={executorId:t.executorId,token:t.token,...t.sessionId===void 0?{}:{sessionId:t.sessionId}};if(e.claim){if(D(e.claim)===D(n)&&e.status==="running")return br(e);throw new b("ACTION_ALREADY_CLAIMED","Action 已由执行者领取,不能替换其归属")}if(e.status!=="pending")throw new b("ACTION_NOT_PENDING","只有待执行 Action 可以被领取");return{...br(e),claim:n,status:"running",...t.executionOrigin?{executionOrigin:structuredClone(t.executionOrigin)}:{}}}function Kh(e,t){if(t=Id(t),bt(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new b("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&bt(t.event,"event");let n=D(t),r=e.rejectedOutcomes?.find(s=>s.outcome.outcomeId===t.outcomeId);if(r)throw D(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:br(e),duplicate:!0}}if(Vh(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new b("STALE_ACTION","结果不属于当前 Action");if(Uh(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(bt(s.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(s.sha256))throw new b("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...br(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:n}]},duplicate:!1}}function aE(e,t){if(bt(t,"reason"),!["running","unknown"].includes(e.status))throw new b("ACTION_NOT_RUNNING","只有已派发 Action 才存在执行结果不明的情况");return{...br(e),status:"unknown",reason:t}}function cE(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=br(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:et(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 zh(e,t){return bt(t,"reason"),Uh(e)?br(e):{...br(e),status:"cancelled",reason:t}}function lE(e,t){nr(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let n of["actionId","inputHash","claimToken","evidence"])bt(t[n],n);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new b("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(Vh(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new b("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function Jh(e,t){if(lE(e,t),e.status!=="cancelled")throw new b("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&D(e.cancellation)!==D(t))throw new b("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...br(e),cancellation:structuredClone(t)}}function Gh(e,t){if(lE(e,t),!Uh(e))throw new b("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&D(e.executionStop)!==D(t))throw new b("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...br(e),executionStop:structuredClone(t)}}function nr(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 Id(e){let t=et(e),n=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(nr(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(nr(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 _d(e,t){if(nr(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=sE(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&&bt(n.reason,"reason"),n.claim!==void 0&&(nr(n.claim,["executorId","sessionId","token"]),bt(n.claim.executorId,"executorId"),bt(n.claim.token,"token"),n.claim.sessionId!==void 0&&bt(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&&(nr(n.executionOrigin,["workflow"]),nr(n.executionOrigin.workflow,["id","version","hash"]),bt(n.executionOrigin.workflow.id,"executionOrigin.workflow.id"),bt(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&&Jh({...n,input:null},n.cancellation),n.executionStop!==void 0&&Gh({...n,input:null},n.executionStop);let i=new Set;for(let o of n.receipts){if(nr(o,["outcomeId","hash"]),bt(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(nr(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=Id(c.outcome),f=n.receipts.find(a=>a.outcomeId===l.outcomeId);if(o.has(l.outcomeId)||!f||f.hash!==D(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(nr(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(nr(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!==D(n.outcome))throw new b("INVALID_ACTION","终态结果与已接受摘要不一致");Kh({...n,input:null,status:"running",receipts:[]},n.outcome)}else if(n.outcome!==void 0)throw new b("INVALID_ACTION","非执行终态不能保存当前执行结果");return n}function Yh(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}var pE=new WeakSet,mE=new WeakSet,Xh=new WeakSet,uE=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"];function Z(e){throw new b("INVALID_RUN",e)}function gt(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Z(`${t} 必须是 JSON 对象`),e}function qn(e,t,n){for(let r of Object.keys(e))t.includes(r)||Z(`${n} 包含不支持的字段:${r}`)}function qe(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&Z(`${t} 必须是非空字符串且不超过 4096 字符`),e}function No(e,t,n=0){return(!Number.isSafeInteger(e)||e<n)&&Z(`${t} 必须是大于等于 ${n} 的安全整数`),e}function xi(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&Z(`${t} 必须是 SHA-256 摘要`),e}function dE(e,t,n=!1){let r=gt(e,t);qn(r,n?["id","version","hash"]:["id","version"],t);let i={id:qe(r.id,`${t}.id`),version:qe(r.version,`${t}.version`)};return n&&(i.hash=xi(r.hash,`${t}.hash`)),i}function vc(e,t,n){let r=gt(e,t);if(!n&&On(r)&&mE.has(r))return r;let i=(s,o)=>{qe(s,`${t} step id`);let c=gt(o,`${t}.${s}`);qn(c,["sequence","value"],`${t}.${s}`),(!Object.hasOwn(c,"sequence")||!Object.hasOwn(c,"value"))&&Z(`${t}.${s} 缺少 sequence 或 value`),No(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 fE(e,t,n){let r=gt(e,t);return qn(r,["from","to","results","activation"],t),(!Object.hasOwn(r,"from")||!Object.hasOwn(r,"to")||!Object.hasOwn(r,"results"))&&Z(`${t} 缺少 from、to 或 results`),{from:r.from===null?null:qe(r.from,`${t}.from`),to:qe(r.to,`${t}.to`),results:vc(r.results,`${t}.results`,n),...Object.hasOwn(r,"activation")?{activation:r.activation}:{}}}function Pd(e,t,n,r){let i=`${t}:`;e.startsWith(i)||Z(`${n} 不属于当前 Run`);let s=e.slice(i.length);/^[1-9][0-9]*$/.test(s)||Z(`${n} 的步骤序号无效`);let o=Number(s);return(!Number.isSafeInteger(o)||o>r)&&Z(`${n} 的步骤序号超出 Run 范围`),o}function w1(e,t,n,r){let i=gt(e,"Wait");qn(i,["id","stepId","sequence","status","proposal","proposalHash","choices","results","decision"],"Wait");for(let u of["id","stepId","sequence","status","proposal","proposalHash","choices","results"])Object.hasOwn(i,u)||Z(`Wait 缺少 ${u}`);let s=qe(i.id,"Wait.id"),o=qe(i.stepId,"Wait.stepId"),c=No(i.sequence,"Wait.sequence",1);(c>n||Pd(s,t,"Wait.id",n)!==c)&&Z("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||Z("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&Z("Wait.choices 必须是非空数组");let l=i.choices.map(u=>qe(u,"Wait.choices"));new Set(l).size!==l.length&&Z("Wait.choices 不能重复");let f=xi(i.proposalHash,"Wait.proposalHash");D(i.proposal)!==f&&Z("Wait.proposal 与 proposalHash 不一致");let a={id:s,stepId:o,sequence:c,status:i.status,proposal:i.proposal,proposalHash:f,choices:l,results:vc(i.results,"Wait.results",r)};if(i.decision!==void 0){let u=gt(i.decision,"Wait.decision");qn(u,["id","choice","proposalHash","reason"],"Wait.decision"),u.reason!==void 0&&!Yh(u.reason)&&Z("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let p={id:qe(u.id,"Wait.decision.id"),choice:qe(u.choice,"Wait.decision.choice"),proposalHash:xi(u.proposalHash,"Wait.decision.proposalHash"),...u.reason===void 0?{}:{reason:u.reason}};(i.status!=="resolved"||!l.includes(p.choice)||p.proposalHash!==f)&&Z("Wait.decision 与 Wait 状态、选择或提案不一致"),a.decision=p}else i.status==="resolved"&&Z("已解决的 Wait 必须保存对应 decision");return a}function y1(e,t,n,r){let i=gt(e,"EvidenceWait");qn(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let s=qe(i.id,"EvidenceWait.id"),o=No(i.sequence,"EvidenceWait.sequence",1);(o>n||Pd(s,t,"EvidenceWait.id",n)!==o)&&Z("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||Z("EvidenceWait.status 无效");let c={id:s,stepId:qe(i.stepId,"EvidenceWait.stepId"),sequence:o,kind:qe(i.kind,"EvidenceWait.kind"),status:i.status,results:vc(i.results,"EvidenceWait.results",r)};if(i.receipt!==void 0){let l=gt(i.receipt,"EvidenceWait.receipt");qn(l,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),c.receipt={ref:qe(l.ref,"EvidenceWait.receipt.ref"),contentHash:xi(l.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:qe(l.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let l=gt(i.invalidation,"EvidenceWait.invalidation");qn(l,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),c.invalidation={ref:qe(l.ref,"EvidenceWait.invalidation.ref"),contentHash:xi(l.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:qe(l.submissionId,"EvidenceWait.invalidation.submissionId"),reason:qe(l.reason,"EvidenceWait.invalidation.reason")}}return(c.status==="resolved"!=!!c.receipt||c.status==="invalidated"!=!!c.invalidation)&&Z("EvidenceWait.receipt 与状态不一致"),c}function $o(e,t){let n=gt(et(e),"WorkflowRun");return Td(n,t)}function hE(e,t){if(e&&typeof e=="object"&&Xh.has(e)&&On(e)){let n=e;return t!==void 0&&n.runId!==t&&Z("WorkflowRun.runId 与存储键不一致"),n}return Tn(e),gE(Td(gt(structuredClone(e),"WorkflowRun"),t))}function kc(e,t,n){return Td(gt(e,"WorkflowRun"),t,void 0,n)}function Od(e,t){return Tn(e),Td(gt(e,"WorkflowRun"),e.runId,t&&Xh.has(t)&&On(t)?t:void 0),gE(e)}function gE(e){hs(e),Xh.add(e);for(let n of e.actions)pE.add(n);let t=n=>mE.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 Td(e,t,n,r){qn(e,uE,"WorkflowRun");for(let O of uE.filter(U=>U!=="reason"&&U!=="state"&&U!=="evidenceWaits"&&U!=="initialStateHash"&&U!=="commands"))Object.hasOwn(e,O)||Z(`WorkflowRun 缺少 ${O}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new b("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=qe(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&Z("WorkflowRun.runId 与存储键不一致");let s=No(e.revision,"WorkflowRun.revision",1),o=No(e.sequence,"WorkflowRun.sequence"),c=dE(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||Z("WorkflowRun.status 无效"),e.reason!==void 0&&qe(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||Z("WorkflowRun 缺少 input");let l=gt(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(l).length===0&&Z("WorkflowRun.definitionHashes 不能为空");for(let[O,U]of Object.entries(l)){let ne;try{ne=JSON.parse(O)}catch{Z("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(ne)||ne.length!==2||typeof ne[0]!="string"||typeof ne[1]!="string"||JSON.stringify(ne)!==O)&&Z("WorkflowRun.definitionHashes 包含非规范的工作流引用"),xi(U,`WorkflowRun.definitionHashes.${O}`)}let f=JSON.stringify([c.id,c.version]);l[f]!==c.hash&&Z("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&Z("WorkflowRun.lineage 必须是最多 32 层的数组");let a=e.lineage.map(O=>qe(O,"WorkflowRun.lineage"));(new Set(a).size!==a.length||a.includes(i))&&Z("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&Z("WorkflowRun.actions 和 waits 必须是数组");let u=e.actions.map(O=>{let U;try{U=O&&typeof O=="object"&&pE.has(O)&&On(O)?O:_d(O,r?.hash(O.input))}catch(ne){if(ne instanceof b&&ne.code==="UNSUPPORTED_PROTOCOL")throw ne;Z(`WorkflowRun.actions 包含无效 Action:${ne.message}`)}return U.executionOrigin&&U.executionOrigin.workflow.id!==c.id&&Z("Action 执行来源不属于当前工作流"),U.runId!==i&&Z(`Action ${U.id} 不属于当前 Run`),new Set(U.requiredCapabilities).size!==U.requiredCapabilities.length&&Z(`Action ${U.id} 的 requiredCapabilities 不能重复`),U}),p=new Map(u.map(O=>[O.id,O]));e.commands!==void 0&&!Array.isArray(e.commands)&&Z("WorkflowRun.commands 必须是数组");let d=e.commands?.map(O=>{let U=gt(O,"WorkflowRun.commands item");qn(U,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let ne={id:qe(U.id,"WorkflowRun.commands.id"),name:qe(U.name,"WorkflowRun.commands.name"),inputHash:xi(U.inputHash,"WorkflowRun.commands.inputHash"),actionId:qe(U.actionId,"WorkflowRun.commands.actionId")};return p.has(ne.actionId)||Z("WorkflowRun.commands 指向不存在的 Action"),ne});d&&new Set(d.map(O=>O.id)).size!==d.length&&Z("WorkflowRun.commands 标识不能重复");let m=e.waits.map(O=>w1(O,i,o,r));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&Z("WorkflowRun.evidenceWaits 必须是数组");let h=e.evidenceWaits?.map(O=>y1(O,i,o,r))??[],g=new Map;for(let O of u){let U=Pd(O.id,i,"Action.id",o);g.has(U)&&Z("WorkflowRun 的步骤序号不能重复"),g.set(U,O.stepId)}for(let O of m)g.has(O.sequence)&&Z("WorkflowRun 的步骤序号不能重复"),g.set(O.sequence,O.stepId);for(let O of h)g.has(O.sequence)&&Z("WorkflowRun 的步骤序号不能重复"),g.set(O.sequence,O.stepId);g.size!==o&&Z("WorkflowRun.sequence 与已激活步骤数量不一致");let w=gt(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(w).length!==u.length&&Z("WorkflowRun.actionContexts 必须与 actions 一一对应");let k=new Map,y=n?new Map([...n.actions.map(O=>[n.actionContexts[O.id].sequence,O.stepId]),...n.waits.map(O=>[O.sequence,O.stepId]),...(n.evidenceWaits??[]).map(O=>[O.sequence,O.stepId])]):void 0;if(n&&y&&n.runId===i&&[...y].every(([O,U])=>g.get(O)===U)){let O=(U,ne)=>k.set(U,Math.min(k.get(U)??1/0,ne));for(let U of Object.values(n.actionContexts))O(U.results,U.sequence);for(let U of n.waits)O(U.results,U.sequence);for(let U of n.evidenceWaits??[])O(U.results,U.sequence);for(let U of n.ready)O(U.results,n.sequence+1);for(let U of Object.values(n.joins))for(let ne of Object.values(U))for(let Ke of ne)O(Ke.results,n.sequence+1);O(n.outputs,n.sequence+1)}let R=new Map;function S(O,U){let ne=U??o+1;if(r){r.validateOrigins(O,g,ne);return}let Ke=k.get(O);if(!(Ke!==void 0&&ne>=Ke&&On(O))&&!((R.get(O)??1/0)<=ne)){R.set(O,ne);for(let[x,j]of Object.entries(O))(j.sequence>=(U??o+1)||g.get(j.sequence)!==x)&&Z(`WorkflowRun 结果 ${x} 的序号或来源不一致`)}}for(let O of u){Object.hasOwn(w,O.id)||Z(`Action ${O.id} 缺少上下文`);let U=gt(w[O.id],`actionContexts.${O.id}`);qn(U,["sequence","results"],`actionContexts.${O.id}`);let ne=No(U.sequence,`actionContexts.${O.id}.sequence`,1);ne!==Pd(O.id,i,"Action.id",o)&&Z(`Action ${O.id} 的上下文序号不一致`);let Ke=vc(U.results,`actionContexts.${O.id}.results`,r);S(Ke,ne)}for(let O of m)S(O.results,O.sequence);for(let O of h)S(O.results,O.sequence);Array.isArray(e.ready)||Z("WorkflowRun.ready 必须是数组");let C=e.ready.map(O=>fE(O,"WorkflowRun.ready token",r));for(let O of C)S(O.results);let q=gt(e.joins,"WorkflowRun.joins"),T=Object.fromEntries(Object.entries(q).map(([O,U])=>{qe(O,"WorkflowRun.joins step id");let ne=gt(U,`WorkflowRun.joins.${O}`),Ke=Object.fromEntries(Object.entries(ne).map(([x,j])=>{qe(x,"WorkflowRun.joins parent id"),Array.isArray(j)||Z(`WorkflowRun.joins.${O}.${x} 必须是数组`);let N=j.map(W=>{let K=fE(W,`WorkflowRun.joins.${O}.${x}`,r);return(K.to!==O||K.from!==x)&&Z(`WorkflowRun.joins.${O}.${x} 包含错误来源的 token`),S(K.results),K});return[x,N]}));return[O,Ke]})),F=vc(e.outputs,"WorkflowRun.outputs",r);S(F),Array.isArray(e.children)||Z("WorkflowRun.children 必须是数组");let B=e.children.map(O=>{let U=gt(O,"WorkflowRun.children item");qn(U,["actionId","runId","workflow"],"WorkflowRun.children item");let ne=dE(U.workflow,"WorkflowRun.children.workflow"),Ke=qe(U.actionId,"WorkflowRun.children.actionId"),x=qe(U.runId,"WorkflowRun.children.runId"),j=p.get(Ke);return(!j||j.type!=="child_workflow"||j.ref!==`${ne.id}@${ne.version}`||x!==`child-${D(Ke)}`||!Object.hasOwn(l,JSON.stringify([ne.id,ne.version])))&&Z("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:Ke,runId:x,workflow:ne}});(new Set(B.map(O=>O.actionId)).size!==B.length||u.filter(O=>O.type==="child_workflow").length!==B.length)&&Z("每个子工作流 Action 必须恰好对应一个 Child Run");let Y=u.some(O=>["pending","running","unknown"].includes(O.status)),de=m.some(O=>O.status==="pending"),G=h.some(O=>O.status==="pending"),ie=Object.values(T).some(O=>Object.values(O).some(U=>U.length>0));return e.status==="running"&&!Y&&C.length===0&&Z("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(Y||!de&&!G&&!ie||C.length>0)&&Z("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(Y||de||G||ie||C.length>0)&&Z("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&Z(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:s,workflow:c,definitionHashes:l,...e.initialStateHash===void 0?{}:{initialStateHash:xi(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:o,actions:u,...d===void 0?{}:{commands:d},actionContexts:w,waits:m,...e.evidenceWaits===void 0?{}:{evidenceWaits:h},ready:C,joins:T,outputs:F,children:B,lineage:a,...e.reason===void 0?{}:{reason:e.reason}}}var wE=new WeakMap;async function jo(e,t){let n=await(e.readProjection?e.readProjection(t):e.read(t));if(!n)throw new b("RUN_NOT_FOUND",`找不到工作流实例:${t}`);yc(n)||(Tn(n),n=structuredClone(n),wc(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=kc(r,t,{hash:Ft,visitResults:Ed,validateOrigins:xd})}catch(c){throw c instanceof b?c:new b("INVALID_RUN",c instanceof Error?c.message:String(c))}wc(i);let s=yc(n);s&&(s.validationActions=i.actions.length,s.validationMaterializedEntries=s.materializedEntries);let o=e.queryScope??wE.get(e);return o||(o=v1(),wE.set(e,o)),Object.freeze({record:n,run:i,scope:o,stats:s,materialize:(c=[])=>pn(c.reduce((l,f)=>l?.[f],i)),hash:()=>Ft(i)})}var Ai=e=>{throw new b("INVALID_REQUEST",e)};function Qh(e,t){let{run:n,scope:r}=e;["current","summary","history","action","artifact"].includes(t.view)||Ai("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 pn({...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 pn({...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||Ai("query.actionId 不属于当前 Run"),t.view==="action")return pn({...i,action:p,context:n.actionContexts[p.id]});let d=(p.outcome?.artifacts??[]).map(h=>({...h,artifactId:D({actionId:p.id,...h})})),m=t.artifactId===void 0?d:d.filter(h=>h.artifactId===t.artifactId);return t.artifactId!==void 0&&!m.length&&Ai("query.artifactId 不属于所选 Action"),pn({...i,actionId:p.id,artifacts:m})}let c=t.limit??25;(!Number.isSafeInteger(c)||c<1||c>100)&&Ai("query.limit 必须在 1–100 之间");let l=t.filter??"all";["all","actions","waits","evidenceWaits"].includes(l)||Ai("query.filter 无效");let f=D({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(d=>!["binding","offset"].includes(d)))&&Ai("query.cursor 与当前存储、版本或筛选不匹配"),a=p.offset}catch{Ai("query.cursor 无效或已经过期")}let u=[...l==="all"||l==="actions"?n.actions.map((p,d)=>({kind:"action",sequence:n.actionContexts[p.id].sequence,path:["actions",String(d)]})):[],...l==="all"||l==="waits"?n.waits.map((p,d)=>({kind:"wait",sequence:p.sequence,path:["waits",String(d)]})):[],...l==="all"||l==="evidenceWaits"?(n.evidenceWaits??[]).map((p,d)=>({kind:"evidenceWait",sequence:p.sequence,path:["evidenceWaits",String(d)]})):[]].sort((p,d)=>d.sequence-p.sequence);return a>u.length&&Ai("query.cursor 超出历史范围"),{...pn(i),records:u.slice(a,a+c).map(p=>({kind:p.kind,sequence:p.sequence,value:e.materialize(p.path)})),total:u.length,...a+c<u.length?{nextCursor:Buffer.from(JSON.stringify({binding:f,offset:a+c})).toString("base64url")}:{}}}import{randomUUID as Jw}from"node:crypto";import{types as Xw}from"node:util";var Uw=St(sI(),1);var dt=St(sw(),1),mB=(()=>{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=dt.default.default??dt.default;function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,u=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),u++}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),u++}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),u++}for(let p in s)if(!(p==="action"||p==="commit"||p==="prUrl"||p==="remote"||p==="targetBranch")){let d={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[d]:a.push(d),u++}if(s.action!==void 0){let p=s.action;if(!(p==="local"||p==="push"||p==="pr")){let d={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=[d]:a.push(d),u++}}if(s.commit!==void 0){let p=s.commit;if(typeof p=="string"){if(!n.test(p)){let d={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=[d]:a.push(d),u++}}else{let d={instancePath:o+"/commit",schemaPath:"#/properties/commit/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}if(s.prUrl!==void 0){let p=s.prUrl;if(typeof p=="string"){if(r(p)<1){let d={instancePath:o+"/prUrl",schemaPath:"#/properties/prUrl/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[d]:a.push(d),u++}}else{let d={instancePath:o+"/prUrl",schemaPath:"#/properties/prUrl/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}if(s.remote!==void 0){let p=s.remote;if(typeof p=="string"){if(r(p)<1){let d={instancePath:o+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[d]:a.push(d),u++}}else{let d={instancePath:o+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}if(s.targetBranch!==void 0){let p=s.targetBranch;if(typeof p=="string"){if(r(p)<1){let d={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[d]:a.push(d),u++}}else{let d={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}}else{let p={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),u++}return i.errors=a,u===0}return e.exports})(),hB=(()=>{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,u=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[d]:a.push(d),u++}if(s.language===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[d]:a.push(d),u++}if(s.phase===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[d]:a.push(d),u++}if(s.contextCompression===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[d]:a.push(d),u++}if(s.buildMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[d]:a.push(d),u++}if(s.buildPause===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[d]:a.push(d),u++}if(s.subagentDispatch===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[d]:a.push(d),u++}if(s.tddMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[d]:a.push(d),u++}if(s.reviewMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[d]:a.push(d),u++}if(s.isolation===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[d]:a.push(d),u++}if(s.boundBranch===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[d]:a.push(d),u++}if(s.verifyMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[d]:a.push(d),u++}if(s.autoTransition===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[d]:a.push(d),u++}if(s.baseRef===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[d]:a.push(d),u++}if(s.designDoc===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[d]:a.push(d),u++}if(s.plan===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[d]:a.push(d),u++}if(s.verifyResult===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[d]:a.push(d),u++}if(s.verifyFailures===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[d]:a.push(d),u++}if(s.verificationReport===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[d]:a.push(d),u++}if(s.branchStatus===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[d]:a.push(d),u++}if(s.createdAt===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[d]:a.push(d),u++}if(s.verifiedAt===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[d]:a.push(d),u++}if(s.archiveConfirmation===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[d]:a.push(d),u++}if(s.archived===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[d]:a.push(d),u++}if(s.directOverride===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[d]:a.push(d),u++}if(s.handoffContext===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[d]:a.push(d),u++}if(s.handoffHash===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[d]:a.push(d),u++}if(s.classicProfile===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[d]:a.push(d),u++}if(s.classicMigration===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[d]:a.push(d),u++}for(let d in s)if(!n.call(t.properties,d)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),u++}if(s.archiveConfirmation!==void 0){let d=s.archiveConfirmation;if(!(d===null||d==="pending"||d==="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),u++}}if(s.archived!==void 0&&typeof s.archived!="boolean"){let d={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[d]:a.push(d),u++}if(s.autoTransition!==void 0){let d=s.autoTransition;if(typeof d!="boolean"&&d!==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),u++}}if(s.baseRef!==void 0){let d=s.baseRef;if(typeof d!="string"&&d!==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),u++}}if(s.boundBranch!==void 0){let d=s.boundBranch;if(typeof d!="string"&&d!==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),u++}}if(s.branchStatus!==void 0){let d=s.branchStatus;if(!(d===null||d==="pending"||d==="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),u++}}if(s.buildMode!==void 0){let d=s.buildMode;if(!(d===null||d==="subagent-driven-development"||d==="executing-plans"||d==="direct"||d==="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),u++}}if(s.buildPause!==void 0){let d=s.buildPause;if(!(d===null||d==="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),u++}}if(s.checkEpoch!==void 0){let d=s.checkEpoch;if(!(typeof d=="number"&&!(d%1)&&!isNaN(d)&&isFinite(d))){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),u++}if(typeof d=="number"&&isFinite(d)&&(d<0||isNaN(d))){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),u++}}if(s.classicMigration!==void 0){let d=s.classicMigration;if(!(d===null||d===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),u++}}if(s.classicProfile!==void 0){let d=s.classicProfile;if(!(d===null||d==="full"||d==="hotfix"||d==="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),u++}}if(s.contextCompression!==void 0){let d=s.contextCompression;if(!(d===null||d==="off"||d==="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),u++}}if(s.createdAt!==void 0){let d=s.createdAt;if(typeof d!="string"&&d!==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),u++}}if(s.designDoc!==void 0){let d=s.designDoc;if(typeof d!="string"&&d!==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),u++}}if(s.directOverride!==void 0){let d=s.directOverride;if(typeof d!="boolean"&&d!==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),u++}}if(s.handoffContext!==void 0){let d=s.handoffContext;if(typeof d!="string"&&d!==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),u++}}if(s.handoffHash!==void 0){let d=s.handoffHash,m=u,h=!1,g=u;if(d!==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),u++}var p=g===u;if(h=h||p,!h){let w=u;if(typeof d=="string"){if(!r.test(d)){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),u++}}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),u++}var p=w===u;h=h||p}if(h)u=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),u++}}if(s.isolation!==void 0){let d=s.isolation;if(!(d===null||d==="current"||d==="branch"||d==="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),u++}}if(s.language!==void 0){let d=s.language;if(!(d===null||d==="en"||d==="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),u++}}if(s.phase!==void 0){let d=s.phase;if(!(d==="open"||d==="design"||d==="build"||d==="verify"||d==="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),u++}}if(s.plan!==void 0){let d=s.plan;if(typeof d!="string"&&d!==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),u++}}if(s.reviewMode!==void 0){let d=s.reviewMode;if(!(d===null||d==="off"||d==="standard"||d==="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),u++}}if(s.subagentDispatch!==void 0){let d=s.subagentDispatch;if(!(d===null||d==="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),u++}}if(s.tddMode!==void 0){let d=s.tddMode;if(!(d===null||d==="tdd"||d==="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),u++}}if(s.verificationReport!==void 0){let d=s.verificationReport;if(typeof d!="string"&&d!==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),u++}}if(s.verifiedAt!==void 0){let d=s.verifiedAt;if(typeof d!="string"&&d!==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),u++}}if(s.verifyFailures!==void 0){let d=s.verifyFailures;if(!(typeof d=="number"&&!(d%1)&&!isNaN(d)&&isFinite(d))){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),u++}if(typeof d=="number"&&isFinite(d)&&(d<0||isNaN(d))){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),u++}}if(s.verifyMode!==void 0){let d=s.verifyMode;if(!(d===null||d==="light"||d==="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),u++}}if(s.verifyResult!==void 0){let d=s.verifyResult;if(!(d==="pending"||d==="pass"||d==="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),u++}}if(s.workflow!==void 0&&s.workflow!=="full"){let d={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=[d]:a.push(d),u++}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[d]:a.push(d),u++}return i.errors=a,u===0}return e.exports})(),gB=(()=>{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,u=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[d]:a.push(d),u++}if(s.language===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[d]:a.push(d),u++}if(s.phase===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[d]:a.push(d),u++}if(s.contextCompression===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[d]:a.push(d),u++}if(s.buildMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[d]:a.push(d),u++}if(s.buildPause===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[d]:a.push(d),u++}if(s.subagentDispatch===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[d]:a.push(d),u++}if(s.tddMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[d]:a.push(d),u++}if(s.reviewMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[d]:a.push(d),u++}if(s.isolation===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[d]:a.push(d),u++}if(s.boundBranch===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[d]:a.push(d),u++}if(s.verifyMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[d]:a.push(d),u++}if(s.autoTransition===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[d]:a.push(d),u++}if(s.baseRef===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[d]:a.push(d),u++}if(s.designDoc===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[d]:a.push(d),u++}if(s.plan===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[d]:a.push(d),u++}if(s.verifyResult===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[d]:a.push(d),u++}if(s.verifyFailures===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[d]:a.push(d),u++}if(s.verificationReport===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[d]:a.push(d),u++}if(s.branchStatus===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[d]:a.push(d),u++}if(s.createdAt===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[d]:a.push(d),u++}if(s.verifiedAt===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[d]:a.push(d),u++}if(s.archiveConfirmation===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[d]:a.push(d),u++}if(s.archived===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[d]:a.push(d),u++}if(s.directOverride===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[d]:a.push(d),u++}if(s.handoffContext===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[d]:a.push(d),u++}if(s.handoffHash===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[d]:a.push(d),u++}if(s.classicProfile===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[d]:a.push(d),u++}if(s.classicMigration===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[d]:a.push(d),u++}for(let d in s)if(!n.call(t.properties,d)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),u++}if(s.archiveConfirmation!==void 0){let d=s.archiveConfirmation;if(!(d===null||d==="pending"||d==="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),u++}}if(s.archived!==void 0&&typeof s.archived!="boolean"){let d={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[d]:a.push(d),u++}if(s.autoTransition!==void 0){let d=s.autoTransition;if(typeof d!="boolean"&&d!==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),u++}}if(s.baseRef!==void 0){let d=s.baseRef;if(typeof d!="string"&&d!==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),u++}}if(s.boundBranch!==void 0){let d=s.boundBranch;if(typeof d!="string"&&d!==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),u++}}if(s.branchStatus!==void 0){let d=s.branchStatus;if(!(d===null||d==="pending"||d==="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),u++}}if(s.buildMode!==void 0){let d=s.buildMode;if(!(d===null||d==="subagent-driven-development"||d==="executing-plans"||d==="direct"||d==="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),u++}}if(s.buildPause!==void 0){let d=s.buildPause;if(!(d===null||d==="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),u++}}if(s.checkEpoch!==void 0){let d=s.checkEpoch;if(!(typeof d=="number"&&!(d%1)&&!isNaN(d)&&isFinite(d))){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),u++}if(typeof d=="number"&&isFinite(d)&&(d<0||isNaN(d))){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),u++}}if(s.classicMigration!==void 0){let d=s.classicMigration;if(!(d===null||d===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),u++}}if(s.classicProfile!==void 0){let d=s.classicProfile;if(!(d===null||d==="full"||d==="hotfix"||d==="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),u++}}if(s.contextCompression!==void 0){let d=s.contextCompression;if(!(d===null||d==="off"||d==="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),u++}}if(s.createdAt!==void 0){let d=s.createdAt;if(typeof d!="string"&&d!==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),u++}}if(s.designDoc!==void 0){let d=s.designDoc;if(typeof d!="string"&&d!==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),u++}}if(s.directOverride!==void 0){let d=s.directOverride;if(typeof d!="boolean"&&d!==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),u++}}if(s.handoffContext!==void 0){let d=s.handoffContext;if(typeof d!="string"&&d!==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),u++}}if(s.handoffHash!==void 0){let d=s.handoffHash,m=u,h=!1,g=u;if(d!==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),u++}var p=g===u;if(h=h||p,!h){let w=u;if(typeof d=="string"){if(!r.test(d)){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),u++}}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),u++}var p=w===u;h=h||p}if(h)u=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),u++}}if(s.isolation!==void 0){let d=s.isolation;if(!(d===null||d==="current"||d==="branch"||d==="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),u++}}if(s.language!==void 0){let d=s.language;if(!(d===null||d==="en"||d==="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),u++}}if(s.phase!==void 0){let d=s.phase;if(!(d==="open"||d==="design"||d==="build"||d==="verify"||d==="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),u++}}if(s.plan!==void 0){let d=s.plan;if(typeof d!="string"&&d!==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),u++}}if(s.reviewMode!==void 0){let d=s.reviewMode;if(!(d===null||d==="off"||d==="standard"||d==="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),u++}}if(s.subagentDispatch!==void 0){let d=s.subagentDispatch;if(!(d===null||d==="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),u++}}if(s.tddMode!==void 0){let d=s.tddMode;if(!(d===null||d==="tdd"||d==="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),u++}}if(s.verificationReport!==void 0){let d=s.verificationReport;if(typeof d!="string"&&d!==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),u++}}if(s.verifiedAt!==void 0){let d=s.verifiedAt;if(typeof d!="string"&&d!==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),u++}}if(s.verifyFailures!==void 0){let d=s.verifyFailures;if(!(typeof d=="number"&&!(d%1)&&!isNaN(d)&&isFinite(d))){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),u++}if(typeof d=="number"&&isFinite(d)&&(d<0||isNaN(d))){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),u++}}if(s.verifyMode!==void 0){let d=s.verifyMode;if(!(d===null||d==="light"||d==="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),u++}}if(s.verifyResult!==void 0){let d=s.verifyResult;if(!(d==="pending"||d==="pass"||d==="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),u++}}if(s.workflow!==void 0){let d=s.workflow;if(!(d==="hotfix"||d==="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),u++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[d]:a.push(d),u++}return i.errors=a,u===0}return e.exports})(),wB=(()=>{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,u=0;if(s&&typeof s=="object"&&!Array.isArray(s)){if(s.workflow===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};a===null?a=[d]:a.push(d),u++}if(s.language===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};a===null?a=[d]:a.push(d),u++}if(s.phase===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};a===null?a=[d]:a.push(d),u++}if(s.contextCompression===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};a===null?a=[d]:a.push(d),u++}if(s.buildMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};a===null?a=[d]:a.push(d),u++}if(s.buildPause===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};a===null?a=[d]:a.push(d),u++}if(s.subagentDispatch===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};a===null?a=[d]:a.push(d),u++}if(s.tddMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};a===null?a=[d]:a.push(d),u++}if(s.reviewMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};a===null?a=[d]:a.push(d),u++}if(s.isolation===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};a===null?a=[d]:a.push(d),u++}if(s.boundBranch===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};a===null?a=[d]:a.push(d),u++}if(s.verifyMode===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};a===null?a=[d]:a.push(d),u++}if(s.autoTransition===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};a===null?a=[d]:a.push(d),u++}if(s.baseRef===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};a===null?a=[d]:a.push(d),u++}if(s.designDoc===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};a===null?a=[d]:a.push(d),u++}if(s.plan===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};a===null?a=[d]:a.push(d),u++}if(s.verifyResult===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};a===null?a=[d]:a.push(d),u++}if(s.verifyFailures===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};a===null?a=[d]:a.push(d),u++}if(s.verificationReport===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};a===null?a=[d]:a.push(d),u++}if(s.branchStatus===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};a===null?a=[d]:a.push(d),u++}if(s.createdAt===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};a===null?a=[d]:a.push(d),u++}if(s.verifiedAt===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};a===null?a=[d]:a.push(d),u++}if(s.archiveConfirmation===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};a===null?a=[d]:a.push(d),u++}if(s.archived===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};a===null?a=[d]:a.push(d),u++}if(s.directOverride===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};a===null?a=[d]:a.push(d),u++}if(s.handoffContext===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};a===null?a=[d]:a.push(d),u++}if(s.handoffHash===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};a===null?a=[d]:a.push(d),u++}if(s.classicProfile===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};a===null?a=[d]:a.push(d),u++}if(s.classicMigration===void 0){let d={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};a===null?a=[d]:a.push(d),u++}for(let d in s)if(!n.call(t.properties,d)){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),u++}if(s.archiveConfirmation!==void 0){let d=s.archiveConfirmation;if(!(d===null||d==="pending"||d==="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),u++}}if(s.archived!==void 0&&typeof s.archived!="boolean"){let d={instancePath:o+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};a===null?a=[d]:a.push(d),u++}if(s.autoTransition!==void 0){let d=s.autoTransition;if(typeof d!="boolean"&&d!==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),u++}}if(s.baseRef!==void 0){let d=s.baseRef;if(typeof d!="string"&&d!==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),u++}}if(s.boundBranch!==void 0){let d=s.boundBranch;if(typeof d!="string"&&d!==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),u++}}if(s.branchStatus!==void 0){let d=s.branchStatus;if(!(d===null||d==="pending"||d==="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),u++}}if(s.buildMode!==void 0){let d=s.buildMode;if(!(d===null||d==="subagent-driven-development"||d==="executing-plans"||d==="direct"||d==="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),u++}}if(s.buildPause!==void 0){let d=s.buildPause;if(!(d===null||d==="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),u++}}if(s.checkEpoch!==void 0){let d=s.checkEpoch;if(!(typeof d=="number"&&!(d%1)&&!isNaN(d)&&isFinite(d))){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),u++}if(typeof d=="number"&&isFinite(d)&&(d<0||isNaN(d))){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),u++}}if(s.classicMigration!==void 0){let d=s.classicMigration;if(!(d===null||d===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),u++}}if(s.classicProfile!==void 0){let d=s.classicProfile;if(!(d===null||d==="full"||d==="hotfix"||d==="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),u++}}if(s.contextCompression!==void 0){let d=s.contextCompression;if(!(d===null||d==="off"||d==="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),u++}}if(s.createdAt!==void 0){let d=s.createdAt;if(typeof d!="string"&&d!==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),u++}}if(s.designDoc!==void 0){let d=s.designDoc;if(typeof d!="string"&&d!==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),u++}}if(s.directOverride!==void 0){let d=s.directOverride;if(typeof d!="boolean"&&d!==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),u++}}if(s.handoffContext!==void 0){let d=s.handoffContext;if(typeof d!="string"&&d!==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),u++}}if(s.handoffHash!==void 0){let d=s.handoffHash,m=u,h=!1,g=u;if(d!==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),u++}var p=g===u;if(h=h||p,!h){let w=u;if(typeof d=="string"){if(!r.test(d)){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),u++}}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),u++}var p=w===u;h=h||p}if(h)u=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),u++}}if(s.isolation!==void 0){let d=s.isolation;if(!(d===null||d==="current"||d==="branch"||d==="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),u++}}if(s.language!==void 0){let d=s.language;if(!(d===null||d==="en"||d==="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),u++}}if(s.phase!==void 0){let d=s.phase;if(!(d==="open"||d==="design"||d==="build"||d==="verify"||d==="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),u++}}if(s.plan!==void 0){let d=s.plan;if(typeof d!="string"&&d!==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),u++}}if(s.reviewMode!==void 0){let d=s.reviewMode;if(!(d===null||d==="off"||d==="standard"||d==="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),u++}}if(s.subagentDispatch!==void 0){let d=s.subagentDispatch;if(!(d===null||d==="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),u++}}if(s.tddMode!==void 0){let d=s.tddMode;if(!(d===null||d==="tdd"||d==="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),u++}}if(s.verificationReport!==void 0){let d=s.verificationReport;if(typeof d!="string"&&d!==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),u++}}if(s.verifiedAt!==void 0){let d=s.verifiedAt;if(typeof d!="string"&&d!==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),u++}}if(s.verifyFailures!==void 0){let d=s.verifyFailures;if(!(typeof d=="number"&&!(d%1)&&!isNaN(d)&&isFinite(d))){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),u++}if(typeof d=="number"&&isFinite(d)&&(d<0||isNaN(d))){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),u++}}if(s.verifyMode!==void 0){let d=s.verifyMode;if(!(d===null||d==="light"||d==="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),u++}}if(s.verifyResult!==void 0){let d=s.verifyResult;if(!(d==="pending"||d==="pass"||d==="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),u++}}if(s.workflow!==void 0){let d=s.workflow;if(!(d==="tweak"||d==="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),u++}}}else{let d={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[d]:a.push(d),u++}return i.errors=a,u===0}return e.exports})(),yB=(()=>{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=dt.default.default??dt.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 u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveDirectory"},message:"must have required property 'archiveDirectory'"};f===null?f=[u]:f.push(u),a++}for(let u in i)if(u!=="archiveDirectory"){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.archiveDirectory!==void 0){let u=i.archiveDirectory;if(typeof u=="string"){if(n(u)<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 u={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[u]:f.push(u),a++}return r.errors=f,a===0}return e.exports})(),vB=(()=>{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=dt.default.default??dt.default;function s(o,{instancePath:c="",parentData:l,parentDataProperty:f,rootData:a=o}={}){let u=null,p=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.deliveryAction===void 0){let d={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"deliveryAction"},message:"must have required property 'deliveryAction'"};u===null?u=[d]:u.push(d),p++}if(o.targetBranch===void 0){let d={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};u===null?u=[d]:u.push(d),p++}if(o.verifiedBranch===void 0){let d={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedBranch"},message:"must have required property 'verifiedBranch'"};u===null?u=[d]:u.push(d),p++}if(o.baseCommit===void 0){let d={instancePath:c,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseCommit"},message:"must have required property 'baseCommit'"};u===null?u=[d]:u.push(d),p++}for(let d in o)if(!(d==="baseCommit"||d==="deliveryAction"||d==="deliveryPaths"||d==="prBaseBranch"||d==="remote"||d==="remoteIdentity"||d==="targetBranch"||d==="verifiedBranch")){let m={instancePath:c,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};u===null?u=[m]:u.push(m),p++}if(o.baseCommit!==void 0){let d=o.baseCommit;if(typeof d=="string"){if(!n.test(d)){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})?$"'};u===null?u=[m]:u.push(m),p++}}else{let m={instancePath:c+"/baseCommit",schemaPath:"#/properties/baseCommit/type",keyword:"type",params:{type:"string"},message:"must be string"};u===null?u=[m]:u.push(m),p++}}if(o.deliveryAction!==void 0){let d=o.deliveryAction;if(!(d==="local"||d==="push"||d==="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"};u===null?u=[m]:u.push(m),p++}}if(o.deliveryPaths!==void 0){let d=o.deliveryPaths;if(Array.isArray(d)){let m=d.length;for(let h=0;h<m;h++){let g=d[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"};u===null?u=[w]:u.push(w),p++}}else{let w={instancePath:c+"/deliveryPaths/"+h,schemaPath:"#/properties/deliveryPaths/items/type",keyword:"type",params:{type:"string"},message:"must be string"};u===null?u=[w]:u.push(w),p++}}}else{let m={instancePath:c+"/deliveryPaths",schemaPath:"#/properties/deliveryPaths/type",keyword:"type",params:{type:"array"},message:"must be array"};u===null?u=[m]:u.push(m),p++}}if(o.prBaseBranch!==void 0){let d=o.prBaseBranch;if(typeof d=="string"){if(i(d)<1){let m={instancePath:c+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};u===null?u=[m]:u.push(m),p++}}else{let m={instancePath:c+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};u===null?u=[m]:u.push(m),p++}}if(o.remote!==void 0){let d=o.remote;if(typeof d=="string"){if(i(d)<1){let m={instancePath:c+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};u===null?u=[m]:u.push(m),p++}}else{let m={instancePath:c+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};u===null?u=[m]:u.push(m),p++}}if(o.remoteIdentity!==void 0){let d=o.remoteIdentity;if(typeof d=="string"){if(!r.test(d)){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}$"'};u===null?u=[m]:u.push(m),p++}}else{let m={instancePath:c+"/remoteIdentity",schemaPath:"#/properties/remoteIdentity/type",keyword:"type",params:{type:"string"},message:"must be string"};u===null?u=[m]:u.push(m),p++}}if(o.targetBranch!==void 0){let d=o.targetBranch;if(typeof d=="string"){if(i(d)<1){let m={instancePath:c+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};u===null?u=[m]:u.push(m),p++}}else{let m={instancePath:c+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};u===null?u=[m]:u.push(m),p++}}if(o.verifiedBranch!==void 0){let d=o.verifiedBranch;if(typeof d=="string"){if(i(d)<1){let m={instancePath:c+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};u===null?u=[m]:u.push(m),p++}}else{let m={instancePath:c+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};u===null?u=[m]:u.push(m),p++}}}else{let d={instancePath:c,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};u===null?u=[d]:u.push(d),p++}return s.errors=u,p===0}return e.exports})(),kB=(()=>{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 u={instancePath:i,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:a},message:"must NOT have additional properties"};l===null?l=[u]:l.push(u),f++}if(r.boundBranch!==void 0){let a=r.boundBranch;if(typeof a!="string"&&a!==null){let u={instancePath:i+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};l===null?l=[u]:l.push(u),f++}}if(r.buildMode!==void 0){let a=r.buildMode;if(!(a==="subagent-driven-development"||a==="executing-plans"||a==="direct"||a==="autonomous")){let u={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=[u]:l.push(u),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 u={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=[u]:l.push(u),f++}}if(r.reviewMode!==void 0){let a=r.reviewMode;if(!(a==="off"||a==="standard"||a==="thorough")){let u={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=[u]:l.push(u),f++}}if(r.subagentDispatch!==void 0){let a=r.subagentDispatch;if(!(a==="confirmed"||a===null)){let u={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=[u]:l.push(u),f++}}if(r.tddMode!==void 0){let a=r.tddMode;if(!(a==="tdd"||a==="direct")){let u={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=[u]:l.push(u),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})(),bB=(()=>{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=dt.default.default??dt.default,r=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,u=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),u++}for(let p in s)if(!(p==="checks"||p==="checksReason"||p==="event"||p==="proposal"||p==="requirementsEvidence")){let d={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};a===null?a=[d]:a.push(d),u++}if(s.checks!==void 0){let p=s.checks;if(Array.isArray(p)){let d=p.length;for(let m=0;m<d;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),u++}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),u++}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),u++}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),u++}}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),u++}}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),u++}}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),u++}}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),u++}}}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),u++}}}else{let d={instancePath:o+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};a===null?a=[d]:a.push(d),u++}}if(s.checksReason!==void 0){let p=s.checksReason;if(typeof p=="string"){if(n(p)<1){let d={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[d]:a.push(d),u++}}else{let d={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}if(s.event!==void 0){let p=s.event;if(!(p==="build-complete"||p==="escalation-requested")){let d={instancePath:o+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};a===null?a=[d]:a.push(d),u++}}if(s.proposal!==void 0){let p=s.proposal;if(typeof p=="string"){if(n(p)<1){let d={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[d]:a.push(d),u++}}else{let d={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}if(s.requirementsEvidence!==void 0){let p=s.requirementsEvidence;if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.ref===void 0){let d={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"ref"},message:"must have required property 'ref'"};a===null?a=[d]:a.push(d),u++}if(p.contentHash===void 0){let d={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};a===null?a=[d]:a.push(d),u++}for(let d in p)if(!(d==="contentHash"||d==="ref")){let m={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};a===null?a=[m]:a.push(m),u++}if(p.contentHash!==void 0){let d=p.contentHash;if(typeof d=="string"){if(!r.test(d)){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),u++}}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),u++}}if(p.ref!==void 0){let d=p.ref;if(typeof d=="string"){if(n(d)<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),u++}}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),u++}}}else{let d={instancePath:o+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[d]:a.push(d),u++}}}else{let p={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),u++}return i.errors=a,u===0}return e.exports})(),RB=(()=>{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=dt.default.default??dt.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 u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};f===null?f=[u]:f.push(u),a++}for(let u in i)if(!(u==="checks"||u==="checksReason"||u==="event"||u==="reason"||u==="verificationReport")){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.checks!==void 0){let u=i.checks;if(Array.isArray(u)){let p=u.length;for(let d=0;d<p;d++){let m=u[d];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:s+"/checks/"+d,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/"+d,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/"+d,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/"+d+"/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/"+d+"/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/"+d+"/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/"+d+"/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/"+d+"/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/"+d,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 u=i.checksReason;if(typeof u=="string"){if(n(u)<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 u=i.event;if(!(u==="verification-ready"||u==="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 u=i.reason;if(typeof u=="string"){if(n(u)<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 u=i.verificationReport;if(typeof u=="string"){if(n(u)<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 u={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[u]:f.push(u),a++}return r.errors=f,a===0}return e.exports})(),SB=(()=>{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 u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};f===null?f=[u]:f.push(u),a++}for(let u in i)if(u!=="contentHash"){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.contentHash!==void 0){let u=i.contentHash;if(typeof u=="string"){if(!n.test(u)){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 u={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[u]:f.push(u),a++}return r.errors=f,a===0}return e.exports})(),CB=(()=>{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=dt.default.default??dt.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 u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};f===null?f=[u]:f.push(u),a++}if(i.summary===void 0){let u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"summary"},message:"must have required property 'summary'"};f===null?f=[u]:f.push(u),a++}for(let u in i)if(!(u==="deliveryPaths"||u==="prBaseBranch"||u==="remote"||u==="summary"||u==="targetBranch")){let p={instancePath:s,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:u},message:"must NOT have additional properties"};f===null?f=[p]:f.push(p),a++}if(i.deliveryPaths!==void 0){let u=i.deliveryPaths;if(Array.isArray(u)){let p=u.length;for(let d=0;d<p;d++){let m=u[d];if(typeof m=="string"){if(n(m)<1){let h={instancePath:s+"/deliveryPaths/"+d,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/"+d,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 u=i.prBaseBranch;if(typeof u=="string"){if(n(u)<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 u=i.remote;if(typeof u=="string"){if(n(u)<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 u=i.summary;if(typeof u=="string"){if(n(u)<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 u=i.targetBranch;if(typeof u=="string"){if(n(u)<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 u={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[u]:f.push(u),a++}return r.errors=f,a===0}return e.exports})(),EB=(()=>{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=dt.default.default??dt.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 u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};f===null?f=[u]:f.push(u),a++}if(i.buildPause!==void 0&&i.buildPause!=="plan-ready"){let u={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=[u]:f.push(u),a++}if(i.plan!==void 0){let u=i.plan;if(typeof u=="string"){if(n(u)<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 u={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[u]:f.push(u),a++}return r.errors=f,a===0}return e.exports})(),xB=(()=>{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=dt.default.default??dt.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 u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};f===null?f=[u]:f.push(u),a++}if(i.checks!==void 0){let u=i.checks;if(Array.isArray(u)){let p=u.length;for(let d=0;d<p;d++){let m=u[d];if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.name===void 0){let h={instancePath:s+"/checks/"+d,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/"+d,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/"+d,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/"+d+"/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/"+d+"/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/"+d+"/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/"+d+"/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/"+d+"/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/"+d,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 u=i.checksReason;if(typeof u=="string"){if(n(u)<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 u={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=[u]:f.push(u),a++}}else{let u={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[u]:f.push(u),a++}return r.errors=f,a===0}return e.exports})(),AB=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={properties:{designDoc:{minLength:1,type:"string"}},required:["designDoc"],type:"object"},n=dt.default.default??dt.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 u={instancePath:s,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};f===null?f=[u]:f.push(u),a++}if(i.designDoc!==void 0){let u=i.designDoc;if(typeof u=="string"){if(n(u)<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 u={instancePath:s,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[u]:f.push(u),a++}return r.errors=f,a===0}return e.exports})(),IB=(()=>{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=dt.default.default??dt.default,r=new RegExp("^[a-f0-9]{64}$","u");function i(s,{instancePath:o="",parentData:c,parentDataProperty:l,rootData:f=s}={}){let a=null,u=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),u++}if(s.handoffContext!==void 0){let p=s.handoffContext;if(typeof p=="string"){if(n(p)<1){let d={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[d]:a.push(d),u++}}else{let d={instancePath:o+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}if(s.handoffHash!==void 0){let p=s.handoffHash;if(typeof p=="string"){if(!r.test(p)){let d={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=[d]:a.push(d),u++}}else{let d={instancePath:o+"/handoffHash",schemaPath:"#/properties/handoffHash/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}if(s.proposal!==void 0){let p=s.proposal;if(typeof p=="string"){if(n(p)<1){let d={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};a===null?a=[d]:a.push(d),u++}}else{let d={instancePath:o+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};a===null?a=[d]:a.push(d),u++}}}else{let p={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};a===null?a=[p]:a.push(p),u++}return i.errors=a,u===0}return e.exports})(),oI=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"}',mB],['{"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"}',hB],['{"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"}',gB],['{"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"}',wB],['{"additionalProperties":false,"properties":{"archiveDirectory":{"minLength":1,"type":"string"}},"required":["archiveDirectory"],"type":"object"}',yB],['{"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"}',vB],['{"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"}',kB],['{"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"}',bB],['{"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"}',RB],['{"additionalProperties":false,"properties":{"contentHash":{"pattern":"^[a-f0-9]{64}$","type":"string"}},"required":["contentHash"],"type":"object"}',SB],['{"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"}',CB],['{"properties":{"buildPause":{"enum":["plan-ready"]},"plan":{"minLength":1,"type":"string"}},"required":["plan"],"type":"object"}',EB],['{"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"}',xB],['{"properties":{"designDoc":{"minLength":1,"type":"string"}},"required":["designDoc"],"type":"object"}',AB],['{"properties":{"handoffContext":{"minLength":1,"type":"string"},"handoffHash":{"pattern":"^[a-f0-9]{64}$","type":"string"},"proposal":{"minLength":1,"type":"string"}},"required":["proposal"],"type":"object"}',IB]]);var _B=128,aI=1024*1024,Ns=new Map,Vw=0;function wf(e){let t=jr(e),n=Ns.get(t);if(n)return Ns.delete(t),Ns.set(t,n),n;let i=oI.get(t)??new Uw.Ajv({strict:!0,allErrors:!0}).compile(JSON.parse(t)),s={validate:i,errorsText:()=>Uw.Ajv.prototype.errorsText(i.errors)};if(t.length<=aI){for(;Ns.size>=_B||Vw+t.length>aI;){let o=Ns.keys().next().value;Ns.delete(o),Vw-=o.length}Ns.set(t,s),Vw+=t.length}return s}var PB=["type","ref","input","outputSchema","validator","requiredCapabilities","retry","join"];function wt(e){throw new b("INVALID_WORKFLOW",e)}function ji(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&wt(`${t} 必须是 JSON 对象`),e}function Yc(e,t,n){for(let r of Object.keys(e))t.includes(r)||wt(`${n} 包含不支持的字段:${r}`)}function Kt(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&wt(`${t} 必须是非空字符串且不超过 4096 字符`),e}function Kw(e,t,n=!1){(!Array.isArray(e)||!n&&e.length===0)&&wt(`${t} 必须是${n?"":"非空"}字符串数组`);let r=e.map(i=>Kt(i,t));return new Set(r).size!==r.length&&wt(`${t} 不能包含重复值`),r}function zw(e,t){return Kw(typeof e=="string"?[e]:e,t)}function Xc(e,t){let n=ji(e,t);return Yc(n,["id","version"],t),{id:Kt(n.id,`${t}.id`),version:Kt(n.version,`${t}.version`)}}function lI(e){if(e!==null&&typeof e=="object"){for(let t of Object.values(e))lI(t);Object.freeze(e)}return e}function uI(e,t){try{let n=typeof e=="boolean"?e:ji(e,t);typeof n!="boolean"&&n.$async===!0&&wt(`${t} 仅支持同步校验;异步检查请注册 RuntimeValidator`),wf(n)}catch(n){wt(`${t} 不是受支持的 JSON Schema:${n.message}`)}}function OB(e){let t=ji(e,"step"),n=Kt(t.type,"step.type");["invoke_skill","call_tool","handoff","ask_user","child_workflow","await_evidence"].includes(n)||wt(`不支持的步骤类型:${n}`);let r=n==="ask_user"?["proposalFrom","choices"]:n==="child_workflow"?["workflow"]:n==="await_evidence"?["kind"]:[];Yc(t,[...PB,...r],"step");let i=t.retry===void 0?"manual":t.retry;i!=="manual"&&i!=="idempotent"&&i!=="reconcile"&&wt("step.retry 必须是 manual、idempotent 或 reconcile");let s={...t.ref===void 0?{}:{ref:Kt(t.ref,"step.ref")},...t.input===void 0?{}:{input:t.input},...t.outputSchema===void 0?{}:{outputSchema:t.outputSchema},...t.validator===void 0?{}:{validator:Xc(t.validator,"step.validator")},...t.requiredCapabilities===void 0?{}:{requiredCapabilities:Kw(t.requiredCapabilities,"step.requiredCapabilities",!0)},...t.join===void 0?{}:{join:Kw(t.join,"step.join")},retry:i};return t.outputSchema!==void 0&&uI(t.outputSchema,"outputSchema"),n==="ask_user"?{...s,type:n,proposalFrom:zw(t.proposalFrom,"step.proposalFrom"),choices:zw(t.choices===void 0?["approved","rejected"]:t.choices,"step.choices")}:n==="child_workflow"?{...s,type:n,workflow:Xc(t.workflow,"step.workflow")}:n==="await_evidence"?(s.validator||wt("await_evidence 必须声明验证器"),{...s,type:n,kind:Kt(t.kind,"step.kind"),validator:s.validator}):{...s,type:n,ref:Kt(t.ref,"step.ref")}}var cI=new WeakSet;function ar(e){if(cI.has(e))return e;let t=ji(et(e),"workflow");Yc(t,["id","version","entry","steps","commands","transitions","maxTransitions","initialState","stateSchema","stateValidator","transitionHandler"],"workflow");let n=Kt(t.id,"workflow.id"),r=Kt(t.version,"workflow.version");t.initialState!==void 0&&t.stateSchema===void 0&&wt("workflow.initialState 必须声明 stateSchema"),t.stateValidator!==void 0&&t.stateSchema===void 0&&wt("workflow.stateValidator 必须声明 stateSchema"),t.stateSchema!==void 0&&uI(t.stateSchema,"stateSchema");let i=ji(t.steps,"workflow.steps");Object.keys(i).length===0&&wt("workflow.steps 必须至少包含一个步骤");let s=Object.fromEntries(Object.entries(i).map(([h,g])=>(Kt(h,"step id"),[h,OB(g)])));function o(h,g){Object.hasOwn(s,h)||wt(`${g} 引用了不存在的步骤:${h}`)}let c=zw(t.entry,"workflow.entry");for(let h of c)o(h,"workflow.entry");let l=t.commands===void 0?{}:ji(t.commands,"workflow.commands"),f={};for(let[h,g]of Object.entries(l)){Kt(h,"workflow command name");let w=typeof g=="string"?{stepId:Kt(g,`workflow.commands.${h}`)}:ji(g,`workflow.commands.${h}`);Yc(w,["stepId","validator"],`workflow.commands.${h}`);let k=Kt(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))&&wt(`workflow.commands.${h} 必须指向不带 join 的执行步骤`),Object.defineProperty(f,h,{value:{stepId:k,...w.validator===void 0?{}:{validator:Xc(w.validator,`workflow.commands.${h}.validator`)}},enumerable:!0,configurable:!0,writable:!0})}let a=t.transitions===void 0?[]:t.transitions;Array.isArray(a)||wt("workflow.transitions 必须是数组");let u=new Set,p=a.map(h=>{let g=ji(h,"transition");Yc(g,["from","to","on"],"transition");let w=Kt(g.from,"transition.from"),k=Kt(g.to,"transition.to"),y=Kt(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 u.has(R)&&wt(`重复的状态转移:${w} -> ${k} (${y})`),u.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)||wt(`${h}.join 依赖缺少对应的进入边:${k}`);w.size!==g.join.length&&wt(`${h}.join 必须包含全部进入边的父节点`)}if(g.type==="ask_user")for(let w of g.proposalFrom)o(w,`${h}.proposalFrom`)}let d=t.maxTransitions===void 0?1e3:t.maxTransitions;(typeof d!="number"||!Number.isSafeInteger(d)||d<1)&&wt("workflow.maxTransitions 必须是正安全整数");let m=lI({id:n,version:r,entry:c,steps:s,...t.commands===void 0?{}:{commands:f},transitions:p,maxTransitions:d,...t.initialState===void 0?{}:{initialState:t.initialState},...t.stateSchema===void 0?{}:{stateSchema:t.stateSchema},...t.stateValidator===void 0?{}:{stateValidator:Xc(t.stateValidator,"workflow.stateValidator")},...t.transitionHandler===void 0?{}:{transitionHandler:Xc(t.transitionHandler,"workflow.transitionHandler")}});return cI.add(m),m}function Qc(e,t,n){Object.defineProperty(e,t,{value:n,configurable:!0,enumerable:!0,writable:!0})}function yf(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.value]))}function TB(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)&&Qc(t,r,i);return t}function Hr(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)||Qc(e.joins,s.to,Object.fromEntries(o.join.map(p=>[p,[]])));let u=e.joins[s.to];if(u[s.from].push(s),o.join.some(p=>u[p].length===0))continue;c=TB(o.join.map(p=>u[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:yf(c),...s.activation===void 0?{}:{activation:s.activation}};if(o.type==="ask_user"){let u=Object.fromEntries(o.proposalFrom.map(d=>{if(!Object.hasOwn(c,d))throw new b("PROPOSAL_INPUT_MISSING",`确认步骤缺少上游产物:${d}`);return[d,c[d].value]})),p={input:a.input,outputs:u,...s.activation===void 0?{}:{activation:s.activation}};e.waits.push({id:f,stepId:s.to,sequence:l,status:"pending",proposal:p,proposalHash:D(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 u=o.type==="child_workflow"?`${o.workflow.id}@${o.workflow.version}`:o.ref,p=iE({id:f,runId:e.runId,stepId:s.to,type:o.type,ref:u,input:a,retry:o.retry,requiredCapabilities:o.requiredCapabilities});e.actions.push(p),Qc(e.actionContexts,f,{sequence:l,results:c}),o.type==="child_workflow"&&e.children.push({actionId:f,runId:`child-${D(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 Xo(e,t,n,r,i,s,o,c){let l={sequence:r,value:s},f={...i};Qc(f,n,l),(!Object.hasOwn(e.outputs,n)||e.outputs[n].sequence<=r)&&Qc(e.outputs,n,l);let a=t.transitions.filter(d=>d.from===n),u=a.filter(d=>d.on===o),p=c??u.map(d=>d.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 d of p){let m=typeof d=="string"?d:d.stepId;if(!u.some(h=>h.to===m))throw new b("TRANSITION_TARGET_INVALID","后续步骤必须由工作流声明");e.ready.push({from:n,to:m,results:f,...typeof d=="string"?{}:{activation:d.input}})}}function dI(e){return je({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 Ge(e){return JSON.stringify([e.id,e.version])}function Cn(e){if(e===void 0)return;if(!e||typeof e!="object"||Xw.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=et(t);if(n!==void 0){if(!(n instanceof AbortSignal))throw new b("INVALID_JSON","signal 必须是 AbortSignal");r.signal=n}return r}function Qw(e,t=new Set){if(e===null||typeof e!="object")return e;if(Xw.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:Qw(s.value,t)})}return t.delete(e),r}function Gw(e){if(e===null||typeof e!="object")return e;if(Xw.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"?Cn(r.value):Qw(r.value)})}return t}function $s(e){let t=Qw(e),n=et(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 Yw(e,t){let n=e.supports(je(t));if(typeof n!="boolean")throw new b("INVALID_VALIDATION","执行器 supports 必须返回布尔值");return n}function Er(e){if(e?.signal?.aborted)throw new b("REQUEST_ABORTED","请求已取消,请查询已提交状态后再决定是否重试")}function js(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)&&js(e[r],t[r]))}function fI(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 pI=new WeakMap;function Ds(e){let t=new Map,n=new Map;for(let v of e.workflows){let E=ar(v),_=Ge(E);if(t.has(_))throw new b("DUPLICATE_WORKFLOW","不能重复注册同一工作流版本");t.set(_,E);let A=pI.get(E);A===void 0&&(A=D(E),pI.set(E,A)),n.set(E,A)}let r=new Map;for(let v of e.validators??[]){let E=Ge(v);if(r.has(E))throw new b("DUPLICATE_VALIDATOR","不能重复注册同一验证器版本");r.set(E,v)}let i=new Map;for(let v of e.stateValidators??[]){let E=Ge(v);if(i.has(E))throw new b("DUPLICATE_STATE_VALIDATOR","不能重复注册同一状态验证器版本");i.set(E,v)}let s=new Map;function o(v){let E=s.get(v);return E||(E=wf(v),s.set(v,E)),E}let c=new Map,l=new Map;for(let v of e.transitionHandlers??[]){let E=Ge(v);if(l.has(E))throw new b("DUPLICATE_TRANSITION_HANDLER","不能重复注册同一转移处理器版本");l.set(E,v)}let f=new Map;for(let v of e.evidenceValidators??[]){let E=Ge(v);if(f.has(E))throw new b("DUPLICATE_EVIDENCE_VALIDATOR","不能重复注册同一证据验证器版本");f.set(E,v)}let a=new Map;for(let v of e.commandValidators??[]){let E=Ge(v);if(a.has(E))throw new b("DUPLICATE_COMMAND_VALIDATOR","不能重复注册同一命令验证器版本");a.set(E,v)}for(let v of e.executors??[]){if(c.has(v.id))throw new b("DUPLICATE_EXECUTOR","不能重复注册同一执行器");c.set(v.id,v)}function u(v){let E=t.get(Ge(v));if(!E)throw new b("WORKFLOW_UNAVAILABLE","请提供当前 Run 固定的工作流定义版本");if(v.hash!==void 0&&v.hash!==n.get(E))throw new b("WORKFLOW_CHANGED","同一版本的工作流内容已改变;请恢复原定义或显式迁移");return E}function p(v){if(v.transitionHandler&&!l.has(Ge(v.transitionHandler)))throw new b("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本")}function d(v){if(v.stateValidator&&!i.has(Ge(v.stateValidator)))throw new b("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本")}function m(v){for(let E of Object.values(v.steps))if(E.type==="await_evidence"&&!f.has(Ge(E.validator)))throw new b("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的证据验证器版本")}function h(v){for(let E of Object.values(v.commands??{}))if(E.validator&&!a.has(Ge(E.validator)))throw new b("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本")}function g(v,E,_){if(v.stateSchema!==void 0){let A=o(v.stateSchema);if(!A.validate(E))throw new b(_,A.errorsText())}if(v.stateValidator){let A=i.get(Ge(v.stateValidator));if(!A)throw new b("STATE_VALIDATOR_UNAVAILABLE","未注册工作流所要求的状态验证器版本");try{let P=$s(A.validate({state:et(E)}));if(!P.accepted)throw new Error(P.reason??"业务状态未通过验证")}catch(P){throw new b(_,P instanceof Error?P.message:String(P))}}}function w(v,E,_,A){if(!E.transitionHandler)return;let P=l.get(Ge(E.transitionHandler));if(!P)throw new b("TRANSITION_HANDLER_UNAVAILABLE","未注册工作流所要求的转移处理器版本");let M=et(P.apply({run:je(v),event:je(_)})),H=et(M.state);g(E,H,"TRANSITION_STATE_INVALID");let z=new Set(E.transitions.filter(ee=>ee.from===_.stepId&&ee.on===A).map(ee=>ee.to));if(!Array.isArray(M.next))throw new b("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");let L=[],J=new Set;for(let ee of M.next){let $;if(typeof ee=="string")$=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","后续步骤的输入绑定无效");$={stepId:ee.stepId,input:et(ee.input)}}else throw new b("TRANSITION_TARGET_INVALID","后续步骤的输入绑定无效");let ce=typeof $=="string"?$:$.stepId,Q=D($);if(!z.has(ce)||J.has(Q))throw new b("TRANSITION_TARGET_INVALID","转移处理器选择了未声明或重复的后续步骤");J.add(Q),L.push($)}return v.state=H,L}function k(v,E=D){if(t.size>0)for(let[_,A]of Object.entries(v.definitionHashes)){let[P,M]=JSON.parse(_),H=u({id:P,version:M,hash:A});if(p(H),d(H),m(H),h(H),P===v.workflow.id&&M===v.workflow.version){let z=new Map(v.actions.map(L=>[L.id,L]));for(let L of v.commands??[]){let J=z.get(L.actionId),ee=Object.hasOwn(H.commands??{},L.name),$=J&&!ee&&!Object.hasOwn(H.steps,J.stepId)&&["succeeded","failed","cancelled"].includes(J.status);if(!J||!$&&(!ee||H.commands?.[L.name].stepId!==J.stepId)||J.input===null||typeof J.input!="object"||!Object.hasOwn(J.input,"activation")||E(J.input.activation)!==L.inputHash)throw new b("INVALID_RUN","命令记录与固定工作流 Action 不一致")}if(H.stateSchema!==void 0&&H.initialState===void 0&&v.initialStateHash===void 0)throw new b("INVALID_RUN","已保存的 Run 缺少启动时的初始状态绑定");g(H,v.state,"RUN_STATE_INVALID");for(let L of v.ready){let J=()=>{throw new b("INVALID_RUN","待调度步骤与固定工作流定义不一致")};if(Object.hasOwn(H.steps,L.to)||J(),L.from===null){(!H.entry.includes(L.to)||Object.keys(L.results).length>0||v.sequence!==0&&!(v.status==="failed"&&v.reason?.startsWith("TRANSITION_LIMIT:")))&&J();continue}let ee=L.results[L.from];ee||J();let $=v.actions.find(nn=>nn.stepId===L.from&&v.actionContexts[nn.id].sequence===ee.sequence),ce=v.waits.find(nn=>nn.stepId===L.from&&nn.sequence===ee.sequence),Q=v.evidenceWaits?.find(nn=>nn.stepId===L.from&&nn.sequence===ee.sequence),me=$?.outcome?$.outcome.status==="failed"?"failed":$.outcome.event??"succeeded":ce?.decision?.choice??(Q?.invalidation?"invalidated":Q?.receipt?"succeeded":void 0),Xe=$?v.actionContexts[$.id].results:ce?.results??Q?.results,pa=$?.outcome?$.outcome.output:ce?.decision?{choice:ce.decision.choice,proposal:ce.proposal}:Q?.invalidation?{ref:Q.invalidation.ref,contentHash:Q.invalidation.contentHash,reason:Q.invalidation.reason}:Q?.receipt?{ref:Q.receipt.ref,contentHash:Q.receipt.contentHash}:void 0;(!me||!Xe||$&&!["succeeded","failed"].includes($.status)||ce&&ce.status!=="resolved"||Q&&!["resolved","invalidated"].includes(Q.status)||pa===void 0||E(L.results)!==E({...Xe,[L.from]:{sequence:ee.sequence,value:pa}})||!H.transitions.some(nn=>nn.from===L.from&&nn.to===L.to&&nn.on===me))&&J()}for(let L of v.evidenceWaits??[]){let J=H.steps[L.stepId];if(!(!J&&L.status!=="pending")&&(!J||J.type!=="await_evidence"||J.kind!==L.kind))throw new b("INVALID_RUN","已保存的证据等待项与固定工作流定义不一致")}}}}async function y(v){let E=await e.store.read(v);if(!E)throw new b("RUN_NOT_FOUND",`找不到工作流实例:${v}`);let _=hE(E,v);return k(_),hs(_)}async function R(v,E,_){for(let A=0;A<32;A+=1){Er(v.context);let P=A===0&&_?_:await y(v.runId),M=u(P.workflow);if(v.expectedRevision!==void 0&&v.expectedRevision!==P.revision)throw new b("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let H=fI(P);if(await E(H,M),Tn(H),js(H,P))return P;if(H.revision=P.revision+1,Od(H,P),k(H),hs(H),Er(v.context),await e.store.compareAndSwap(v.runId,P.revision,H))return H}throw new b("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}function S(v,E){let _=v.actions.find(A=>A.id===E);if(!_)throw new b("ACTION_NOT_FOUND","Run 不包含此 Action");return _}function C(v){if(v.status==="cancelled")throw new b("RUN_CANCELLED","Run 已取消,不能继续推进")}function q(v,E={}){let _=Ge(v);if(Object.hasOwn(E,_))return E;E[_]=n.get(v);for(let A of Object.values(v.steps))A.type==="child_workflow"&&q(u(A.workflow),E);return E}async function T(v,E){if(Er(v.context),E.length>32)throw new b("CHILD_DEPTH_LIMIT","子工作流嵌套超过 32 层");let _=u(v.workflow);p(_),d(_),m(_),h(_);let A=Object.hasOwn(v,"initialState");if(A&&_.initialState!==void 0)throw new b("INITIAL_STATE_CONFLICT","工作流定义和启动请求不能同时指定初始状态");let P=A?et(v.initialState):_.initialState;if(_.stateSchema!==void 0&&P===void 0)throw new b("INITIAL_STATE_REQUIRED","启动请求必须提供工作流初始状态");P!==void 0&&g(_,P,"INITIAL_STATE_INVALID");let M=P===void 0?void 0:D(P),H=v.runId??Jw(),z=et(v.input),L={id:_.id,version:_.version,hash:n.get(_)},J=await e.store.read(H);if(J){if(D(J.workflow)!==D(L)||D(J.input)!==D(z)||D(J.lineage)!==D(E)||(J.initialStateHash??(_.initialState===void 0?void 0:D(_.initialState)))!==M)throw new b("RUN_CONFLICT","该 Run 标识已绑定不同工作流或输入");return y(H)}let ee={protocolVersion:1,schemaVersion:1,runId:H,revision:1,workflow:L,definitionHashes:q(_),input:z,...P===void 0?{}:{state:et(P),initialStateHash:M},status:"running",sequence:0,actions:[],actionContexts:{},waits:[],ready:_.entry.map($=>({from:null,to:$,results:{}})),joins:{},outputs:{},children:[],lineage:E};return Hr(ee,_),hs(ee),Er(v.context),Od(ee),k(ee),await e.store.compareAndSwap(H,null,ee)?je(ee):T({...v,runId:H},E)}async function F(v){return T(v,[])}async function B(v){let E=et(v.input),_=D(E);if(!v.commandId.trim()||v.commandId.length>4096||!v.name.trim()||v.name.length>4096)throw new b("INVALID_COMMAND","命令标识和名称不能为空");for(let A=0;A<32;A+=1){Er(v.context);let P=await y(v.runId),M=P.commands?.find(Q=>Q.id===v.commandId);if(M){if(M.name!==v.name||M.inputHash!==_)throw new b("COMMAND_CONFLICT","同一命令标识不能提交不同内容");return P}if(v.expectedRevision!==P.revision)throw new b("REVISION_CONFLICT","Run 已变化,请重新读取当前状态");let H=u(P.workflow),z=Object.hasOwn(H.commands??{},v.name)?H.commands?.[v.name]:void 0;if(!z)throw new b("COMMAND_NOT_FOUND","工作流未声明此命令");let L=z.stepId;if(P.status==="cancelled")throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.actions.some(Q=>["running","unknown"].includes(Q.status)))throw new b("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能中断");let J=!1,ee=!1;if(z.validator){let Q=a.get(Ge(z.validator));if(!Q)throw new b("COMMAND_VALIDATOR_UNAVAILABLE","未注册工作流所要求的命令验证器版本");let me;try{me=$s(await Q.validate({run:je(P),name:v.name,input:je(E),context:Cn(v.context)}))}catch(Xe){throw new b("COMMAND_VALIDATION_ERROR",Xe instanceof Error?Xe.message:String(Xe))}if(J=me.accepted&&me.allowCompleted===!0,ee=me.accepted&&me.allowFailed===!0,P.status==="failed"&&!ee)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="completed"&&!J)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(!me.accepted)throw new b("COMMAND_REJECTED",me.reason??"命令未通过当前工作流状态验证")}if(P.status==="completed"&&!J)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");if(P.status==="failed"&&!ee)throw new b("RUN_TERMINAL","已停止的 Run 不能接受命令");let $=je(P);P.status==="failed"&&($.status="running",delete $.reason),$.actions=$.actions.map(Q=>Q.status==="pending"?zh(Q,`命令 ${v.name} 已取代待执行 Action`):Q);for(let Q of $.waits)Q.status==="pending"&&(Q.status="cancelled");for(let Q of $.evidenceWaits??[])Q.status==="pending"&&(Q.status="cancelled");$.ready=[{from:null,to:L,results:{},activation:E}],$.joins={},Hr($,H);let ce=$.actions.at(-1);if(!ce||ce.stepId!==L||ce.status!=="pending")throw new b("COMMAND_DISPATCH_FAILED","命令未生成可执行的 Action");if($.commands=[...$.commands??[],{id:v.commandId,name:v.name,inputHash:_,actionId:ce.id}],$.revision=P.revision+1,Od($,P),k($),hs($),Er(v.context),await e.store.compareAndSwap(v.runId,P.revision,$))return je($)}throw new b("REVISION_CONFLICT","并发提交持续冲突,请重新读取当前状态")}async function X(v){for(let E of v.children)await e.store.read(E.runId)&&await N({runId:E.runId,reason:v.reason??"父工作流已取消"})}function Y(v,E,_){let A=u(v.workflow),P=Object.hasOwn(A.steps,_.stepId)?A.steps[_.stepId]:void 0;if(!P||P.type!=="child_workflow"||Ge(P.workflow)!==Ge(E.workflow)||_.type!==P.type||_.ref!==`${P.workflow.id}@${P.workflow.version}`||_.attempt!==1||_.retry!==P.retry||!js(_.requiredCapabilities,P.requiredCapabilities??[])||_.claim&&(_.claim.executorId!=="comet-child-workflow"||_.claim.sessionId!==void 0||![E.runId,`portable-${D(E.runId)}`].includes(_.claim.token)))throw new b("INVALID_RUN","子工作流 Action 与固定定义或 Runtime 领取身份不一致");let M=_.input;if(!M||typeof M!="object"||Array.isArray(M)||!js(M,{input:P.input===void 0?v.input:P.input,outputs:yf(v.actionContexts[_.id].results),...Object.hasOwn(M,"activation")?{activation:M.activation}:{}}))throw new b("INVALID_RUN","子工作流 Action 输入与父 Run 上下文不一致");let H=u({...E.workflow,hash:v.definitionHashes[Ge(E.workflow)]});if(Object.entries(q(H)).some(([z,L])=>v.definitionHashes[z]!==L))throw new b("INVALID_RUN","父 Run 缺少子工作流的固定定义绑定");return H}function de(v,E,_,A,P){let M=A.initialState===void 0?void 0:D(A.initialState);if(P.runId!==E.runId||Ge(P.workflow)!==Ge(E.workflow)||P.workflow.hash!==v.definitionHashes[Ge(E.workflow)]||!js(P.definitionHashes,q(A))||!js(P.input,_.input)||!js(P.lineage,[...v.lineage,v.runId])||(P.initialStateHash??M)!==M)throw new b("RUN_CONFLICT","已有子 Run 与父 Action 的固定定义、输入或归属不一致")}async function G(v){let E=await R(v,(_,A)=>Hr(_,A));if(E.status==="cancelled")return await X(E),E;if(E.status==="failed"||E.children.length===0)return E;for(let _ of E.children){let A=S(E,_.actionId);if(!["pending","running","unknown"].includes(A.status))continue;let P=Y(E,_,A);A.status==="pending"&&(E=await ie({runId:E.runId,actionId:A.id,attempt:A.attempt,inputHash:A.inputHash,executorId:"comet-child-workflow",claimToken:_.runId,capabilities:["child-workflow"],context:Cn(v.context)},!0),A=S(E,_.actionId));let M=A.status==="unknown"?await y(_.runId):await T({runId:_.runId,workflow:_.workflow,input:A.input,context:Cn(v.context)},[...E.lineage,E.runId]);de(E,_,A,P,M);let H=await y(E.runId);if(H.status==="cancelled")return await X(H),H;let z=await G({runId:_.runId,context:v.context});de(E,_,A,P,z),["completed","failed","cancelled"].includes(z.status)&&(E=await O({runId:E.runId,context:Cn(v.context),outcome:{actionId:A.id,attempt:A.attempt,inputHash:A.inputHash,claimToken:A.claim.token,outcomeId:`${_.runId}:${z.revision}`,status:z.status==="completed"?"succeeded":"failed",output:yf(z.outputs)}},!0))}return y(E.runId)}async function ie(v,E=!1,_){let A=v.claimToken??(v.context?.requestId?D({runId:v.runId,actionId:v.actionId,attempt:v.attempt,executorId:v.executorId,requestId:v.context.requestId}):Jw());return R(v,async P=>{if(C(P),P.status==="failed")throw new b("RUN_FAILED","Run 已因失败停止;请先完成显式恢复");let M=S(P,v.actionId);if(M.type==="child_workflow"&&!E)throw new b("CHILD_MANAGED","子工作流由 Runtime 登记与核对,不接受宿主代领");let H=oE(M,{executionOrigin:{workflow:{...P.workflow}},attempt:v.attempt,inputHash:v.inputHash,executorId:v.executorId,token:A,...v.sessionId===void 0?{}:{sessionId:v.sessionId}});if(!M.claim){let z=new Set(v.capabilities??[]);if(M.requiredCapabilities.some(J=>!z.has(J)))throw new b("CAPABILITY_REQUIRED","执行者未声明 Action 要求的全部宿主能力");let L=c.get(v.executorId);if(L&&Yw(L,M)){if(M.requiredCapabilities.some(J=>!L.capabilities.includes(J)))throw new b("CAPABILITY_REQUIRED","已配置执行端口缺少 Action 要求的宿主能力");await L.preflight?.(je(M),Cn(v.context),L.includeRun===!1?void 0:je(P)),Er(v.context)}}P.actions[P.actions.indexOf(M)]=H},_)}async function Ye(v){return ie(v)}async function O(v,E=!1,_){let A,P;try{A=Id(v.outcome)}catch(z){P=z}v={...v,outcome:A};let M,H=await R(v,async(z,L)=>{if(M=void 0,C(z),!A)throw P;let J=S(z,v.outcome.actionId);if(J.type==="child_workflow"&&!E)throw new b("CHILD_MANAGED","子工作流结果必须由 Runtime 读取其已提交状态");let ee=Kh(J,v.outcome);if(ee.duplicate)return;let $=ee.action.outcome,ce=z.actions.indexOf(J);try{if(e.validateOutcome){let me=$s(await e.validateOutcome({run:je(z),action:je(J),outcome:je($),context:Cn(v.context)}));me.accepted||(M={code:"OUTCOME_REJECTED",reason:me.reason??"应用结果契约拒绝此结果"})}let Q=L.steps[J.stepId];if(!M&&$.status==="succeeded"&&Q.outputSchema!==void 0){let me=o(Q.outputSchema);me.validate($.output)||(M={code:"OUTPUT_INVALID",reason:me.errorsText()})}if(!M&&Q.validator){let me=r.get(Ge(Q.validator));if(!me)throw new b("VALIDATOR_UNAVAILABLE","未注册工作流所要求的验证器版本");let Xe=$s(await me.validate({run:je(z),action:je(J),outcome:je($),context:Cn(v.context)}));Xe.accepted||(M={code:"OUTCOME_REJECTED",reason:Xe.reason?.trim()?Xe.reason:"结果未满足业务验收条件"})}if(!M){let me=fI(z);me.actions[ce]=ee.action;let Xe=me.actionContexts[J.id],pa=$.status==="failed"?"failed":$.event??"succeeded",nn=w(me,L,{kind:"action-outcome",stepId:J.stepId,outcome:$},pa);Xo(me,L,J.stepId,Xe.sequence,Xe.results,$.output,pa,nn),Hr(me,L),Object.assign(z,me)}}catch(Q){M={code:"OUTCOME_PROCESSING_ERROR",reason:Q instanceof Error&&Q.message.trim()?Q.message:"结果处理失败,请检查验证器或工作流定义"}}M&&(z.actions[ce]={...J,receipts:ee.action.receipts,rejectedOutcomes:[...J.rejectedOutcomes??[],{outcome:ee.action.outcome,...M}]})},_);if(M)throw new b(M.code,M.reason);return H}async function U(v){return O(v)}async function ne(v){if(v.reason!==void 0&&!Yh(v.reason))throw new b("INVALID_DECISION","reason 必须是 1 到 4096 字符的非空文本");return R(v,(E,_)=>{C(E);let A=E.waits.find(M=>M.id===v.waitId);if(!A)throw new b("WAIT_NOT_FOUND","Run 不包含此等待项");if(A.decision){if(A.decision.id!==v.decisionId||A.decision.choice!==v.choice||A.decision.proposalHash!==v.proposalHash||A.decision.reason!==v.reason)throw new b("DECISION_CONFLICT","等待项已经接受了不同的决定");return}if(A.status!=="pending"||A.proposalHash!==v.proposalHash)throw new b("STALE_PROPOSAL","提案已改变或等待项已终止,请重新审阅");if(!v.decisionId.trim()||!A.choices.includes(v.choice))throw new b("INVALID_DECISION","决定标识或选择不符合当前等待项");A.status="resolved",A.decision={id:v.decisionId,choice:v.choice,proposalHash:v.proposalHash,...v.reason===void 0?{}:{reason:v.reason}};let P=w(E,_,{kind:"wait-resolved",stepId:A.stepId,choice:v.choice,proposalHash:v.proposalHash,decisionId:v.decisionId},v.choice);Xo(E,_,A.stepId,A.sequence,A.results,{choice:v.choice,proposal:A.proposal},v.choice,P),Hr(E,_)})}async function Ke(v){return R(v,async(E,_)=>{if(C(E),E.status==="failed")throw new b("RUN_FAILED","Run 已因失败停止,不能提交证据");let A=E.evidenceWaits?.find(L=>L.id===v.evidenceId);if(!A)throw new b("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(A.status!=="pending")throw new b("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(A.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 P=_.steps[A.stepId];if(!P||P.type!=="await_evidence"||P.kind!==v.kind)throw new b("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");let M=f.get(Ge(P.validator));if(!M)throw new b("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let H=$s(await M.validate({run:je(E),kind:v.kind,ref:v.ref,contentHash:v.contentHash,context:Cn(v.context)}));if(!H.accepted||H.actualHash!==v.contentHash)throw new b("EVIDENCE_REJECTED",H.reason??"证据未通过验证或内容已改变");A.status="resolved",A.receipt={ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId};let z=w(E,_,{kind:"evidence-recorded",stepId:A.stepId,evidenceKind:v.kind,ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId},"succeeded");Xo(E,_,A.stepId,A.sequence,A.results,{ref:v.ref,contentHash:v.contentHash},"succeeded",z),Hr(E,_)})}async function x(v){return R(v,async(E,_)=>{if(C(E),E.status==="failed")throw new b("RUN_FAILED","Run 已因失败停止,不能使证据失效");let A=E.evidenceWaits?.find(J=>J.id===v.evidenceId);if(!A)throw new b("EVIDENCE_WAIT_NOT_FOUND","Run 不包含此证据等待项");if(A.status!=="pending")throw new b("EVIDENCE_WAIT_RESOLVED","证据等待项已结束");if(A.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 P=_.steps[A.stepId];if(!P||P.type!=="await_evidence"||P.kind!==v.kind)throw new b("EVIDENCE_STEP_CHANGED","证据等待项与固定工作流不一致");if(!_.transitions.some(J=>J.from===A.stepId&&J.on==="invalidated"))throw new b("EVIDENCE_INVALIDATION_UNAVAILABLE","当前工作流未声明证据失效后的恢复路径");let M=f.get(Ge(P.validator));if(!M)throw new b("EVIDENCE_VALIDATOR_UNAVAILABLE","未注册证据验证器版本");let H=$s(await M.validate({run:je(E),kind:v.kind,ref:v.ref,contentHash:v.contentHash,context:Cn(v.context)}));if(H.accepted&&H.actualHash===v.contentHash)throw new b("EVIDENCE_STILL_VALID","当前证据仍然有效,不能使其失效");let z=(H.reason?.trim()||"证据未通过验证或内容已改变").slice(0,4096);A.status="invalidated",A.invalidation={ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId,reason:z};let L=w(E,_,{kind:"evidence-invalidated",stepId:A.stepId,evidenceKind:v.kind,ref:v.ref,contentHash:v.contentHash,submissionId:v.submissionId,reason:z},"invalidated");Xo(E,_,A.stepId,A.sequence,A.results,{ref:v.ref,contentHash:v.contentHash,reason:z},"invalidated",L),Hr(E,_)})}async function j(v){return R(v,E=>{C(E);let _=E.waits.find(A=>A.id===v.waitId);if(!_||_.status!=="pending"||_.proposalHash!==v.proposalHash)throw new b("STALE_PROPOSAL","只能修改当前仍在等待决定的提案");_.proposal=et(v.proposal),_.proposalHash=D(_.proposal)})}async function N(v){let E=await R(v,_=>{if(_.status==="completed"){if(v.stoppedActions?.length)throw new b("ACTION_TERMINAL","已完成 Run 不接受取消停止确认");return}let A=_.status==="cancelled";if(A||(_.actions=_.actions.map(P=>zh(P,v.reason))),v.stoppedActions!==void 0){if(!Array.isArray(v.stoppedActions))throw new b("INVALID_ACTION","stoppedActions 必须是停止确认数组");let P=new Set;for(let M of v.stoppedActions){if(!M||typeof M!="object"||P.has(M.actionId))throw new b("INVALID_ACTION","停止确认重复或无效");P.add(M.actionId);let H=S(_,M.actionId);_.actions[_.actions.indexOf(H)]=Jh(H,M)}}if(!A){for(let P of _.waits)P.status==="pending"&&(P.status="cancelled");for(let P of _.evidenceWaits??[])P.status==="pending"&&(P.status="cancelled");_.ready=[],_.status="cancelled",_.reason=v.reason}});return E.status==="cancelled"&&await X(E),E}async function W(v){return R(v,E=>{if(!Array.isArray(v.stoppedActions)||!v.stoppedActions.length)throw new b("INVALID_ACTION","stoppedActions 必须是非空停止确认数组");let _=new Set;for(let A of v.stoppedActions){if(!A||typeof A!="object"||_.has(A.actionId))throw new b("INVALID_ACTION","停止确认重复或无效");_.add(A.actionId);let P=S(E,A.actionId);E.actions[E.actions.indexOf(P)]=Gh(P,A)}})}async function K(v){return R(v,E=>{C(E);let _=S(E,v.actionId);if(_.attempt!==v.attempt)throw new b("STALE_ACTION","Action 执行尝试已经改变");E.actions[E.actions.indexOf(_)]=aE(_,v.reason)})}async function se(v){return R(v,async(E,_)=>{C(E);let A=S(E,v.actionId);if(A.attempt!==v.attempt)throw new b("STALE_ACTION","Action 执行尝试已经改变");if(A.type==="child_workflow")throw new b("CHILD_MANAGED","子工作流由 Runtime 管理,不支持通过通用 retry 重置父 Action;保留原有子 Run 和执行记录");if(A.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(E.actions.some(L=>["running","unknown"].includes(L.status)))throw new b("ACTION_IN_FLIGHT","已有 Action 的执行结果不明,不能恢复");if(E.status!=="completed"||E.ready.length>0||E.actions.some(L=>L.status==="pending")||E.waits.some(L=>L.status==="pending")||E.evidenceWaits?.some(L=>L.status==="pending")||Object.values(E.joins).some(L=>Object.values(L).some(J=>J.length>0))||!A.outcome||A.outcome.status!=="succeeded")throw new b("RUN_TERMINAL","当前 Run 不符合已提交结果的恢复条件");let P=$s(await e.validateRecovery({run:je(E),action:je(A),outcome:je(A.outcome),context:Cn(v.context),proposalHash:v.proposalHash}));if(!P.accepted)throw new b("ACTION_TERMINAL",P.reason??"应用拒绝恢复此结果");let M=A.outcome.event??"succeeded",H=w(E,_,{kind:"action-outcome",stepId:A.stepId,outcome:A.outcome},M);if(H?.length===0||H===void 0&&!_.transitions.some(L=>L.from===A.stepId&&L.on===M))throw new b("ACTION_TERMINAL","应用未声明可恢复的后续工作");let z=E.actionContexts[A.id];Xo(E,_,A.stepId,z.sequence,z.results,A.outcome.output,M,H),Hr(E,_);return}if(A.status==="failed"){let P=E.actionContexts[A.id].sequence,M=z=>Object.hasOwn(z,A.stepId)&&z[A.stepId].sequence===P;if(Object.values(E.actionContexts).some(z=>M(z.results))||E.waits.some(z=>M(z.results))||E.evidenceWaits?.some(z=>M(z.results))||E.ready.some(z=>M(z.results))||Object.values(E.joins).some(z=>Object.values(z).some(L=>L.some(J=>M(J.results)))))throw new b("ACTION_ALREADY_ADVANCED","该失败结果已推进工作流,不能重新执行旧 Action")}E.actions[E.actions.indexOf(A)]=cE(A,v.reconciliation),E.status="running",delete E.reason})}async function pe(v,E){let _=c.get(v.executorId);if(!_)throw new b("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let A=E??await y(v.runId),P=S(A,v.actionId);if(P.status!=="pending")throw new b("ACTION_ALREADY_CLAIMED","不能重复执行已派发的 Action;请先查询和核对结果");if(!Yw(_,P))throw new b("EXECUTOR_UNSUPPORTED","执行器不支持此 Action");Er(v.context);let M=await ie({...v,attempt:P.attempt,inputHash:P.inputHash,claimToken:Jw(),capabilities:_.capabilities},!1,A),H=S(M,v.actionId),z;try{Er(v.context),z=await _.execute(je(H),Cn(v.context),_.includeRun===!1?void 0:je(M))}catch(J){let ee=await y(v.runId),$=S(ee,H.id);throw ee.status!=="cancelled"&&$.status==="running"&&$.attempt===H.attempt&&await K({runId:v.runId,actionId:H.id,attempt:H.attempt,reason:J instanceof Error?J.message:String(J)}),new b("EXECUTION_UNKNOWN","执行器未返回可提交的结果;已保留执行归属,请核对外部操作后恢复")}let L=`${H.id}:${H.attempt}:executor-result`;try{return await O({runId:v.runId,context:Cn(v.context),outcome:{...z,actionId:H.id,attempt:H.attempt,inputHash:H.inputHash,claimToken:H.claim.token,outcomeId:L}},!1,M)}catch(J){let ee=await y(v.runId),$=S(ee,H.id);if($.receipts.some(ce=>ce.outcomeId===L)){if($.rejectedOutcomes?.some(ce=>ce.outcome.outcomeId===L))throw J;if($.outcome?.outcomeId===L)return ee}throw ee.status!=="cancelled"&&$.status==="running"&&$.attempt===H.attempt&&await K({runId:v.runId,actionId:H.id,attempt:H.attempt,reason:J instanceof Error?J.message.slice(0,4096):"执行结果无法提交"}),new b("EXECUTION_UNKNOWN","执行器已返回结果但未能提交;已保留执行归属,请核对外部操作后恢复")}}async function ze(v){let E=v.maxActions??100;if(!Number.isSafeInteger(E)||E<1)throw new b("INVALID_REQUEST","maxActions 必须是正安全整数");let _=c.get(v.executorId);if(!_)throw new b("EXECUTOR_UNAVAILABLE","未注册指定的执行器");let A=0,P=await y(v.runId),M=z=>({reason:z,run:P,actionsExecuted:A}),H=z=>{if(P.status==="completed"||P.status==="failed"||P.status==="cancelled")return P.status;if(P.actions.some(L=>L.status==="unknown"&&(!z||L.type!=="child_workflow")))return"execution-unknown";if(P.actions.some(L=>L.status==="running"&&(!z||L.type!=="child_workflow")))return"action-in-flight";if(P.waits.some(L=>L.status==="pending"))return"approval-required";if(P.evidenceWaits?.some(L=>L.status==="pending"))return"evidence-required"};for(;;){Er(v.context);let z=H(!0);if(z)return M(z);(P.ready.length||P.children.length)&&(P=await G({runId:v.runId,context:v.context}));let L=H(!1);if(L)return M(L);let J=P.actions.find(ee=>ee.status==="pending");if(!J)return M("idle");if(A>=E)return M("action-limit");if(!Yw(_,J)||J.requiredCapabilities.some(ee=>!_.capabilities.includes(ee)))return M("executor-required");A++;try{P=await pe({...v,actionId:J.id},P)}catch(ee){if(!(ee instanceof b)||ee.code!=="EXECUTION_UNKNOWN"||(P=await y(v.runId),!P.actions.some($=>$.status==="unknown")))throw ee;return M("execution-unknown")}}}async function st(v){let E=await jo(e.store,v);return k(E.run,Ft),E}async function kn(v){return Qh(await st(v.runId),v)}function _e(v){return async(...E)=>{let _=E.map(A=>Gw(A));return je(await v(..._))}}return{start:_e(F),dispatchCommand:_e(B),inspect:_e(y),inspectProjection:st,query:_e(kn),inspectCurrent:async v=>await kn({runId:v,view:"current"}),executeCurrent:async v=>dI(await pe(Gw(v))),runUntilBlockedCurrent:async v=>{let E=await ze(Gw(v));return{...E,run:dI(E.run)}},next:_e(G),claim:_e(Ye),recordOutcome:_e(U),resolveWait:_e(ne),recordEvidence:_e(Ke),invalidateEvidence:_e(x),reviseWait:_e(j),cancel:_e(N),acknowledgeStopped:_e(W),markUnknown:_e(K),retry:_e(se),execute:_e(v=>pe(v)),runUntilBlocked:_e(ze)}}Va();Qi();RI();cn();Re();import{createHash as xI,randomUUID as _X}from"node:crypto";import{types as WB}from"node:util";import{promises as Hn}from"node:fs";import yt from"node:path";Jn();var SI=new WeakMap;function CI(e){return bf(e).encoded}function bf(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 u=SI.get(a)??t.get(a);if(u!==void 0)return u;let p=Object.entries(a),d=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,d),On(a)&&SI.set(a,d),d},i=r(e),s=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return s();let o=[],c=(a,u)=>{if(!a||typeof a!="object")return;let p=a;if(!(p.protocolVersion!==1||!Array.isArray(p.actions)||!p.actionContexts)){for(let[d,m]of p.actions.entries())m.input&&typeof m.input=="object"&&Object.hasOwn(m.input,"outputs")&&o.push({path:[...u,"actions",String(d),"input","outputs"],group:"outputs"});for(let[d,m]of Object.entries(p.actionContexts))m?.results&&o.push({path:[...u,"actionContexts",d,"results"],group:"results"});p.outputs&&o.push({path:[...u,"outputs"],group:"results"});for(let d of["ready","waits","evidenceWaits"])for(let[m,h]of(p[d]??[]).entries())h.results&&o.push({path:[...u,d,String(m),"results"],group:"results"})}};if(c(e,[]),c(e.run,["run"]),!o.length)return s();let l=nE(e,o,On),f=JSON.stringify(l);return f.length<i*.9?{encoded:l,json:f}:s()}function qs(e){if(typeof e!="string"||e.trim().length===0)throw new b("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function MB(e){return qs(e),xI("sha256").update(JSON.stringify(e)).digest("hex")}function Rf(e){if(!Number.isSafeInteger(e)||e<1)throw new b("STORE_INVALID_REVISION","revision 必须是正安全整数")}function FB(e,t,n,r=!0){if(qs(e),WB.isProxy(n))throw new b("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&Rf(t),Tn(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(Rf(i.revision),i.revision!==(t??0)+1)throw new b("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}var EI="comet.runtime-store-checkpoint.v1";function HB(e,t,n){let r=et(n);if(qs(e),!r||r.runId!==e)throw new b("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(Rf(r.revision),t!==null&&t!==1||r.revision<=(t??0))throw new b("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(r)}function AI(e,t,n){let r=et(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 BB(e,t,n,r=[]){return(e?.revision??null)===t&&(e===null||jr(e)===jr(AI(n,1,r)))}function vn(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new b("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(x=>{if(x!=="run.revision")throw new b("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function n(x){for(let j of t){let N=x;for(let W of j){if(!N||typeof N!="object"||Array.isArray(N)||!Object.hasOwn(N,W))throw new b("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");N=N[W]}if(N!==x.revision)throw new b("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let r=yt.resolve(e.rootDir),i=yt.parse(r).root,s=yt.relative(i,r).replaceAll("\\","/");if(!s)throw new b("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let o={label:"RuntimeStore root",expected:"directory"},c=MB,l="checkpoint.json",f="comet.runtime-store-format.v2",a=".runtime-store-v2",u=x=>`${a}/${c(x)}`,p=x=>`.runtime-store-history/${c(x)}`,d="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(x,j){let N=await ue(r,x?`${x}/${j}`:j,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let W=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(N.bytes));return Tn(W),W}catch{throw new b("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function y(x,j,N){if(!x||typeof x!="object"||Array.isArray(x)||x.runId!==j||x.revision!==N||!Number.isSafeInteger(N)||N<1)throw new b("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");n(x)}async function R(x,j=!1,N=c(x),W=!0){if(qs(x),!(await V(i,s,o)).exists)return w();let K=await V(r,N,{label:"RuntimeStore run",expected:"directory"});if(!K.exists)return w();let se=await Hn.lstat(K.target),pe=await Hn.readdir(K.target,{withFileTypes:!0}),ze=await Hn.lstat(K.target);if(await V(i,`${s}/${N}`,o),!se.isDirectory()||se.isSymbolicLink()||!ze.isDirectory()||ze.isSymbolicLink()||!In({dev:se.dev,ino:se.ino,birthtime:se.birthtimeMs},{dev:ze.dev,ino:ze.ino,birthtime:ze.birthtimeMs}))throw new b("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let st=new Set,kn=[],_e=0;for(let $ of pe){if(($.name===`${h}.contenders`||$.name==="legacy"&&N===u(x))&&$.isDirectory()&&!$.isSymbolicLink())continue;if(!$.isFile()||$.isSymbolicLink())throw new b("STORE_INVALID_ENTRY",`版本文件无效:${$.name}`);if(/^\..+\.tmp$/u.test($.name)||$.name===h||[h+".sqlite",h+".sqlite-journal",h+".sqlite-wal",h+".sqlite-shm"].includes($.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test($.name)||(st.add($.name),$.name===l))continue;if(!g.test($.name))throw new b("STORE_INVALID_ENTRY",`版本文件无效:${$.name}`);let ce=Number($.name.slice(0,-5));if(!Number.isSafeInteger(ce)||ce<1)throw new b("STORE_INVALID_ENTRY",`版本文件无效:${$.name}`);kn.push($.name),_e=Math.max(_e,ce)}let v=!1;if([u(x),p(x)].includes(N)&&kn.length>0)throw new b("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(st.has(l)){if(![u(x),p(x)].includes(N))throw new b("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let $=await k(N,l),ce=$?.record,Q=$?.legacyRevision;if(!$||![m,"comet.runtime-store-snapshot.v3"].includes(String($.schema))||!ce||Object.keys($).some(Xe=>!["schema","record","hash","legacyRevision",...$.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(Xe))||Q!==null&&(!Number.isSafeInteger(Q)||Q<1||Q>ce.revision)||$.hash!==D({record:ce,legacyRevision:Q,...$.schema==="comet.runtime-store-snapshot.v3"?{pool:$.pool}:{}}))throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let me;try{me=$.schema==="comet.runtime-store-snapshot.v3"?Ad(ce,$.pool,W):ce}catch(Xe){throw new b("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${Xe instanceof Error?Xe.message:String(Xe)}`)}return y(me,x,me.revision),{record:me,compacted:!0,legacyRevision:Q,formatPresent:v}}if(!_e)return w();let E=new Map,_=$=>`${String($).padStart(16,"0")}.json`,A=$=>st.has(_($));async function P($){if(E.has($))return E.get($);let ce=await k(N,_($));return($<=2||$===_e)&&E.set($,ce),ce}async function M($,ce=0,Q=_e){if(y($,x,Q),j)for(let me of kn){let Xe=Number(me.slice(0,-5));Xe!==ce&&y(await P(Xe),x,Xe)}return{record:$,compacted:!1,legacyRevision:$.revision,formatPresent:!1}}let H=await P(_e);if(_e===kn.length&&(H?.schema!==EI||H?.runId!==void 0))return M(H);if(!A(1))throw new b("STORE_MISSING_REVISION","版本历史缺少 revision 1");let z=null;for(let $ of[1,2]){if(!A($))break;let ce=await P($);if(ce?.schema!==EI||"runId"in ce)continue;let Q=ce.record;if(Q&&n(Q),!Q||Q.runId!==x||!Number.isSafeInteger(Q.revision)||Q.revision<$||ce.hash!==D(Q)||Object.keys(ce).some(me=>!["schema","record","hash"].includes(me))||$===2&&jr(await P(1))!==jr(AI(Q,1,t)))throw new b("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");z={slot:$,record:Q};break}let L=z?.record.revision??0,J=z?.slot??0,ee=_e===J?L:_e;if(ee<L||kn.length!==ee-L+J||kn.some($=>{let ce=Number($.slice(0,-5));return ce>J&&ce<=L})){let $=L+1;for(;A($);)$+=1;throw new b("STORE_MISSING_REVISION",`版本历史缺少 revision ${$}`)}return M(z&&_e===z.slot?z.record:H,J,z&&_e===z.slot?z.record.revision:_e)}async function S(x){let j=await V(r,c(x),{label:"RuntimeStore format",expected:"any"}),N=await V(r,`${u(x)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if(j.kind==="directory"&&N.exists&&(j=await V(r,c(x),{label:"RuntimeStore format",expected:"any"})),j.kind==="directory"&&N.exists)throw new b("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let W=null;if(j.kind==="file"){let K=await k("",c(x));if(!K||K.runId!==x||(K.schema===f?!["pending","ready"].includes(K.state)||Object.keys(K).some(se=>!["schema","runId","state","writerProtocol"].includes(se)):K.schema!==d||!["closing","closed","reopening"].includes(K.state)||!Number.isSafeInteger(K.revision)||K.revision<1||typeof K.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(K.recordHash)||Object.keys(K).some(se=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(se))))throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(K.writerProtocol!==void 0&&K.writerProtocol!=="application-holder-v1")throw new b("STORE_WRITER_FENCED","存储协议版本不受支持");W=K}return{original:j,staged:N,marker:W}}function C(x){return yc(x)?Ft(x,{cachePrefixes:!1}):D(x)}async function q(x,j){let N=await R(x,!1,u(x),!1),W=await R(x,!1,p(x),!1);if(!N.record&&!W.record||j.state==="closed"&&(N.record||!W.record))throw new b("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(N.record&&W.record){let se=await Hn.lstat(yt.join(r,u(x),l)),pe=await Hn.lstat(yt.join(r,p(x),l)),ze={dev:se.dev,ino:se.ino,birthtime:se.birthtimeMs},st={dev:pe.dev,ino:pe.ino,birthtime:pe.birthtimeMs};if(!Su(ze,st)||!In(ze,st))throw new b("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let K=W.record??N.record;if(K.revision!==j.revision||C(K)!==j.recordHash||N.record&&N.record!==K&&C(N.record)!==j.recordHash)throw new b("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:K,active:!!N.record,history:!!W.record}}async function T(x){if(qs(x),!(await V(i,s,o)).exists)return"missing";let j=await S(x),N=await V(r,`${u(x)}/${l}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),W=await V(r,`${p(x)}/${l}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(j.marker?.schema===d){if(!N.exists&&!W.exists||j.marker.state==="closed"&&(N.exists||!W.exists))throw new b("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return j.marker.state}if(W.exists)throw new b("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return j.marker||N.exists||j.original.kind==="directory"||j.staged.exists?"active":"missing"}async function F(x,j,N){await We(yt.join(r,c(x)),JSON.stringify({schema:d,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:x,state:j,revision:N.revision,recordHash:C(N)})+`
|
|
178
|
+
`,{containedRoot:r,requireAtomicPublication:!0})}async function B(x){let j=(await S(x)).marker;if(!j||!["closing","reopening"].includes(j.state))return;let N=j.state==="closing",W=(await q(x,j)).record,K=await q(x,j),se=N?u(x):p(x),pe=N?p(x):u(x);await Pt(r,pe,{label:"RuntimeStore 历史目标"});let ze=yt.join(r,se,l),st=yt.join(r,pe,l),kn=N?K.active:K.history;(N?K.history:K.active)||(await V(r,`${se}/${l}`,{label:"RuntimeStore 历史源",expected:"file"}),await V(r,pe,{label:"RuntimeStore 历史目标",expected:"directory"}),await Hn.link(ze,st),await q(x,j)),await ie(yt.dirname(st)),await ie(yt.dirname(yt.dirname(st))),await ie(r),kn&&(await q(x,j),await pr(ze,{containedRoot:r,beforeRemove:async()=>{await q(x,j)}}),await ie(yt.dirname(ze))),N?await F(x,"closed",W):await G(x,"ready",!1);let v=await Y(x,!1);if(!v||v.revision!==W.revision||C(v)!==C(W))throw new b("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function X(x,j,N){return qs(x),Rf(j),Ye(x,async()=>{await B(x);let W=(await S(x)).marker,K;if(W?.schema===d){if(N&&W.state==="reopening")throw new b("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!N&&W.state==="closing")throw new b("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(K=(await q(x,W)).record,K.revision!==j)return!1;if(N&&W.state==="closed")return!0}else{if(K=(await ne(x,!1)).record,!K||K.revision!==j)return!1;if(!N)return!0}return await F(x,N?"closing":"reopening",K),await B(x),!0})}async function Y(x,j=!0){if(qs(x),!(await V(i,s,o)).exists)return null;let N=await S(x);if(N.marker?.schema===d){let{record:se}=await q(x,N.marker);return j?pn(se):se}if((await R(x,!1,p(x),!1)).record)throw new b("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let K=await R(x,!1,u(x),j);if(K.record){if(!N.marker&&!(await S(x)).marker)throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return K.record}if(N.original.kind==="directory"){let se=(await R(x)).record;if(!se&&(await S(x)).original.kind!=="directory")throw new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return se}if(N.marker?.state==="ready")throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(N.staged.exists){let se;try{se=(await R(x,!1,`${u(x)}/legacy`)).record}catch(pe){throw(await S(x)).marker?.state==="ready"?new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):pe}if(!se){let pe=await S(x);if(!pe.staged.exists||pe.marker?.state==="ready")throw new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return se}return null}async function de(x,j=!0){for(let N=0;;N+=1)try{return await Y(x,j)}catch(W){let K=W instanceof Ct&&W.reason==="changed",se=["ENOENT","ENOTDIR"].includes(W.code??""),pe=W instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(W.message);if(!K&&!se&&!pe||N>=15)throw W}}async function G(x,j,N){await We(yt.join(r,c(x)),JSON.stringify({schema:f,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:x,state:j})+`
|
|
179
|
+
`,{containedRoot:r,exclusive:N,requireAtomicPublication:!0})}async function ie(x){let j;try{j=await Hn.open(x,"r"),await j.sync()}catch(N){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(N.code??""))throw N}finally{await j?.close()}}async function Ye(x,j){if(await Pt(i,s,o),(await V(r,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new b("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await Pt(r,u(x),{label:"RuntimeStore run"}),await ie(yt.join(r,a)),await ie(r);try{return e.singleWriter?await j():await bI(yt.join(r,u(x),h),j)}catch(W){throw["ENOTSUP","EOPNOTSUPP"].includes(W.code??"")?new b("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):W}}async function O(x,j,N,W=bf(j)){let K=yt.join(r,u(x)),se=N.legacyRevision,{encoded:pe,json:ze}=W,st=pe.pool?{record:pe.record,legacyRevision:se,pool:pe.pool}:{record:j,legacyRevision:se},kn=pe.pool?"comet.runtime-store-snapshot.v3":m,_e=`{"schema":${JSON.stringify(kn)},${ze.slice(1,-1)},"legacyRevision":${JSON.stringify(se)},"hash":${JSON.stringify(D(st))}}
|
|
180
|
+
`;await We(yt.join(K,l),_e,{containedRoot:r,exclusive:!N.compacted,requireAtomicPublication:!0}),N.formatPresent||await G(x,"ready",!1)}async function U(x,j){if(j===null)return;let N=`${u(x)}/legacy`,W=await V(r,N,{label:"RuntimeStore legacy",expected:"directory"});if(W.exists)try{for(let K of await Hn.readdir(W.target,{withFileTypes:!0}))K.isFile()&&!K.isSymbolicLink()&&g.test(K.name)&&Number(K.name.slice(0,-5))<=j&&await pr(yt.join(W.target,K.name),{containedRoot:r});await V(r,N,{label:"RuntimeStore legacy",expected:"directory"}),await Hn.rmdir(W.target).catch(K=>{if(K.code!=="ENOTEMPTY"&&K.code!=="EEXIST")throw K})}catch(K){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${K instanceof Error?K.message:String(K)}
|
|
181
|
+
`)}}async function ne(x,j=!0){let N=(await S(x)).marker;if(N?.writerProtocol&&N.writerProtocol!==e.writerProtocol)throw new b("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await B(x);let W=await S(x);if(W.marker?.schema===d)throw new b("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await R(x,!1,p(x),!1)).record)throw new b("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let se=await R(x,!1,u(x),j);if(se.record&&!W.marker)throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(W.original.kind==="directory"){await R(x,!0);let ze=await Hn.lstat(W.original.target);await V(i,`${s}/${c(x)}`,o),await V(r,u(x),o),await Hn.rename(W.original.target,W.staged.target);let st=await Hn.lstat(W.staged.target);if(!st.isDirectory()||st.isSymbolicLink()||!In({dev:ze.dev,ino:ze.ino,birthtime:ze.birthtimeMs},{dev:st.dev,ino:st.ino,birthtime:st.birthtimeMs}))throw new b("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await ie(yt.join(r,u(x))),await ie(r),W=await S(x)}if(!W.marker){try{await G(x,"pending",!0)}catch(ze){throw["EEXIST","EISDIR","ENOTDIR"].includes(ze.code??"")?new b("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):ze}W=await S(x)}let pe=se;if(!pe.record&&W.marker?.state==="ready")throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!pe.record&&W.staged.exists?(pe=await R(x,!0,`${u(x)}/legacy`),pe.record&&(await O(x,pe.record,pe),pe={...pe,compacted:!0,formatPresent:!0})):pe.record&&W.marker?.state==="pending"&&await G(x,"ready",!1),pe.record&&(pe.formatPresent=!0,await U(x,pe.legacyRevision)),pe}return{queryScope:`file:${xI("sha256").update(r).digest("hex")}`,read:de,readProjection:x=>de(x,!1),readPartitionMetadata:T,settleRun:x=>di(async()=>await T(x)==="missing"?"missing":Ye(x,async()=>{await B(x);let j=(await S(x)).marker;return j&&e.writerProtocol&&j.writerProtocol!==e.writerProtocol&&await We(yt.join(r,c(x)),JSON.stringify({...j,writerProtocol:e.writerProtocol})+`
|
|
182
|
+
`,{containedRoot:r,requireAtomicPublication:!0}),T(x)})),closeRun:(x,j)=>di(()=>X(x,j,!0)),reopenRun:(x,j)=>di(()=>X(x,j,!1)),async readDisposition(x){if(!await de(x,!1))return"missing";let N=(await S(x)).marker;return N?.schema===d?N.state:"active"},async restoreCheckpoint(x,j,N){let W=JSON.parse(HB(x,j,N));return n(W),Ye(x,async()=>{let K=await ne(x);return BB(K.record,j,W,t)?(await O(x,W,K),!0):!1})},compareAndSwap:async(x,j,N)=>Ke(x,j,N)(),prepareCompareAndSwap:Ke};function Ke(x,j,N){FB(x,j,N,!1),n(N);let{json:W}=bf(N),K=JSON.parse(W);return()=>Ye(x,async()=>{let se=await ne(x,!1);return(se.record?.revision??null)!==j?!1:(await O(x,K.record,se,{encoded:K,json:W}),!0)})}}Re();import{isDeepStrictEqual as II}from"node:util";var Dt="run_checkpoint",ey="comet.workflow-run-checkpoint.v1",VB=/^portable-[a-f0-9]{64}$/u;function Sf(e){return VB.test(e)?e:`portable-${D(e)}`}function Cf(e){let t=CI(e.run);return t.pool?{...e,schema:"comet.workflow-run-checkpoint.v2",run:t.record,pool:t.pool,storageHash:D(t)}:e}function el(e,t){return II(e,t)||II(e,Cf(t))}function _I(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=Sf(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=D(r.outcome))}}return t.status==="running"&&(r.status="unknown",r.reason="Portable recovery requires reconciliation of external execution"),r})}}var PI={hash:Ft,visitResults:Ed,validateOrigins:xd};function UB(e){let t=kc(_I(e),e.runId,PI),n=Ft(t);return{schema:ey,hash:n,run:t,sourceRevision:e.revision,sourceHash:D({hash:n,sourceRevision:e.revision})}}function Ls(e){let t=$o(_I(e),e.runId),n=D(t);return{schema:ey,hash:n,run:t,sourceRevision:e.revision,sourceHash:D({hash:n,sourceRevision:e.revision})}}function OI(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`);Tn(e);let i=e;if(![ey,"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"&&D({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"?Ad(i.run,i.pool,!r):i.run;if((r?Ft:D)(s)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=r?kc(s,t,PI):$o(s,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==D({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 Bn(e,t,n={}){return OI(e,t,n)}function Ef(e,t,n={}){return OI(e,t,n,!0)}function Ws(e,t){if(e===void 0)return!1;let n=Ef(e,t.runId,{preserveSourceRevision:!0});if(!n)return!1;let r=e,i=UB(t);return r.hash===i.hash&&r.sourceRevision===i.sourceRevision&&r.sourceHash===i.sourceHash&&n.revision===t.revision}function Ms(e){let t=structuredClone(e);for(let n of t.actions)n.claim&&!n.executionOrigin&&(n.executionOrigin={workflow:{...e.workflow}});return t}function tl(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:Sf(t.claim.token)}}Qi();var yy=St(_t(),1);$I();import{execFileSync as Li}from"node:child_process";import zt from"node:path";import{isDeepStrictEqual as wy}from"node:util";bn();Re();function ty(e){return`${e.replace(/\n+$/u,"")}
|
|
183
|
+
`}function ny(e,t,n){let r=e.replace(/\r\n/gu,`
|
|
184
|
+
`),i=r.split(`
|
|
185
|
+
`),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 ty(r);let f=i.slice(1,s).filter(a=>{let u=a.match(/^([^:\n]+):/u)?.[1]?.trim();return u===void 0?!0:u!=="archived-with"&&u!==o});return f.push(`archived-with: ${t}`),n&&f.push(n),ty(["---",...f,"---",...i.slice(s+1)].join(`
|
|
186
|
+
`))}let c=["---",`archived-with: ${t}`];return n&&c.push(n),o!=="status"&&c.push("status: final"),c.push("---"),ty([...c,r].join(`
|
|
187
|
+
`))}function xt(e,t,n){if(!e)return null;let r=e.replaceAll("\\","/");return r.startsWith(`${t}/`)?`${n}/${r.slice(t.length+1)}`:r}ic();nt();Ze();import eV from"node:path";async function xf(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=eV.posix.join(r,i);if(i==="design.md"&&!await lt(e,s,{label:"Classic Open design"}))continue;let o=await oe(e,s,{label:`Classic Open ${i}`});if(!o.trim())return i+" is empty";if(i==="tasks.md"&&Mt(o).length===0)return"tasks.md has no task"}return null}Ze();function Ue(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic delivery recovery evidence is missing");return e}function Fs(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=Ue(r.input).outputs,o=Ue(Ue(s)[`${n}.archive.preflight`]),c=Ue(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 ea(e){return Ue(Ue(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 ry(e,t){let n=Fs(e,t),r=Ue(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 Af(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 jI(e,t){if(e===void 0||t.state.archived!==!0)return!1;let n=D(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||D(i.input)!==i.inputHash)return!1;let s=Ue(Ue(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"&&D(s)===r.inputHash&&s.deliveryCheckpointHash===n&&!!(o?.status==="failed"&&cr(t,o))}return Zo(t,i)&&D(s)===r.inputHash&&Ue(s.deliveryRepair).checkpointHash===n})}function cr(e,t){let n=e.state;if(!n.archived||t.type!=="invoke_skill"||t.stepId!==`${n.workflow}.archive.deliver`)return null;let r=Ue(t.input).activation,i=r===void 0?{}:Ue(r),s=i.deliveryRepairCheckId;if(s===void 0&&i.interruptedActionId!==void 0){let p=e.actions.find(g=>g.id===i.interruptedActionId),d=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||d===void 0||(e.actionContexts[p.id]?.sequence??1/0)>=d||h?.status!=="succeeded"||h.claim?.executorId!=="comet-classic-work-continuation"||D(h.outcome?.output)!==D({interruptedActionId:p.id,resumeStepId:p.stepId})||Ue(Ue(h.input).activation).interruptedActionId!==p.id||!e.commands?.some(g=>g.name==="continue-work"&&g.actionId===h.id&&g.inputHash===D(Ue(h.input).activation)))throw new Error("Classic delivery continuation is missing its original stopped Skill");return cr(e,p)}let o=Fs(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:{...Ue(Ue(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=Ue(Ue(t.input).outputs);if(e.actionContexts[t.id]?.results[o.archive.stepId]?.sequence!==e.actionContexts[o.archive.id]?.sequence||D(p[`${n.workflow}.archive.preflight`])!==D(o.approved)||D(p[o.archive.stepId])!==D(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),u=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"||u?.status!=="resolved"||u.decision?.choice!=="approved"||D(Ue(Ue(u.proposal).outputs)[a.stepId])!==D(a.outcome.output))throw new Error("Classic delivery repair is missing its current check and explicit approval");return Fs(e,ea(a)),{...f,outputs:{...f.outputs,[a.stepId]:a.outcome.output},repairCheckId:a.id,approvalWaitIds:[...f.approvalWaitIds,u.id]}}function Hs(e,t){let n=cr(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 Hs(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 u=f.input.outputs;if(!(u?.["full.build.plan"]===void 0||u["full.design.document"]===void 0))return{recovered:!0,outputs:{"full.design.document":u["full.design.document"],"full.build.plan":u["full.build.plan"]}}}return{outputs:r,recovered:!1}}import{promises as oy}from"node:fs";import xr from"node:path";bn();Re();un();Ze();bn();Re();import{promises as tV}from"node:fs";import If from"node:path";nt();Ot();async function DI(e,t,n,r){let i=t.input.changeDir;if(ot(i,"Classic active path"),ot(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 V(e,m,{label:"Classic legacy archive path",expected:"any"});if(h.exists)if(h.kind==="directory")for(let g of await tV.readdir(h.target)){if([".comet-state.lock",".comet-state-transaction.json"].includes(g)){let w=m+"/"+g+"/.comet-runtime-migration.json";(await V(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=If.relative(e,(await Gn(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=Hs(t,n).outputs,a=f["full.design.document"]?.designDoc,u=f["full.build.plan"]?.plan;for(let m of[a,u])m&&s.push(xt(m,i,r));let p=If.relative(e,await le(If.join(e,r))).replaceAll("\\","/"),d=s.filter(m=>m.startsWith(r+"/")).map(m=>i+"/"+m.slice(r.length+1));return{paths:[...new Set([...s,...d])],sourcePaths:d,stateFiles:[p,i+"/"+If.posix.basename(p)],optionalPaths:o}}Ot();var iy=".comet/archive-manifest.json";async function sy(e,t){let n=await V(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 oy.readdir(n.target)).sort())[".comet-state.lock",".comet-state-transaction.json"].includes(i)||r.push(...await sy(e,t+"/"+i));return r}function nl(e,t){return D(tl(e,t))}async function ay(e){return vn({singleWriter:!0,rootDir:xr.join(await Nr(e),"archive-receipts/classic")})}async function qI(e){return vn({singleWriter:!0,rootDir:xr.join(await Nr(e),"archive-inputs/classic")})}function nV(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 rV(e,t,n){let r=t.input.changeDir,i=t.state,s=xr.relative(e,await le(xr.join(e,r))).replaceAll("\\","/"),o=xr.posix.dirname(r)+"/archive",c=await V(e,o,{label:"Classic Archive directory",expected:"directory"}),l=c.exists?await oy.readdir(c.target):[];return{activeRef:r,stateRef:s,specsRef:n,paths:(await sy(e,r)).filter(f=>f!==s),specPaths:await sy(e,n),documents:[i.designDoc,i.plan].filter(f=>!!f),archivePaths:l}}async function LI(e,t,n,r){let i=await qI(e),s=nl(t,n),o=await i.read(s);if(o)return nV(o.snapshot);let c=await rV(e,t,r),l={runId:s,revision:1,execution:tl(t,n),snapshot:c};if(!await i.compareAndSwap(s,null,l))throw new Error("原 Archive 已有执行准备记录,请恢复同一 Action");return c}async function WI(e,t,n){if(n.status!=="failed"||n.outcome?.status!=="failed")throw new Error("原 Archive 尚未确认失败退出;先恢复原 Action 并核对实际归档进度");let r=t.input.changeDir;if(!(await V(e,r,{label:"Classic active change",expected:"directory"})).exists)throw new Error("原 change 目录已搬迁;恢复原 Archive 进度,不能重开执行");let s=await(await qI(e)).read(nl(t,n));if(s?.snapshot.archivePaths){let o=await V(e,xr.posix.dirname(r)+"/archive",{label:"Classic Archive directory",expected:"directory"}),c=xr.posix.basename(r);if(o.exists&&(await oy.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 MI(e,t,n,r,i,s){let o=xt(i.stateRef,i.activeRef,r),c=new Set(i.paths.map(p=>xt(p,i.activeRef,r)));c.delete(o);for(let p of i.documents)c.add(xt(p,i.activeRef,r));for(let p of i.paths.filter(d=>d.startsWith(i.activeRef+"/specs/")&&d.endsWith("/spec.md")))c.add(i.specsRef+"/"+p.slice((i.activeRef+"/specs/").length));let l={schema:"comet.classic.archive-manifest.v2",execution:tl(t,n),activeRef:i.activeRef,archiveRef:r,stateRef:o,paths:[...c].sort(),sourcePaths:i.paths},f=await ay(e),a=nl(t,n),u=await f.read(a);if(u&&u.manifest.archiveRef!==r)throw new Error("原 Archive 已记录不同交付目录,不能覆盖");if(!u&&!await f.compareAndSwap(a,null,{runId:a,revision:1,manifest:l}))throw new Error("原 Archive 交付记录已存在");return await Rn(e,r+"/"+iy,JSON.stringify(u?.manifest??l,null,2)+`
|
|
188
|
+
`,{label:"Classic Archive progress"}),[]}async function iV(e,t,n,r){let i=await(await ay(e)).read(nl(t,n));if(!i||i.manifest.archiveRef!==r||i.manifest.execution.actionId!==n.id)throw new Error("原 Archive 执行收据缺失;核对原命令结果并恢复原记录,不能重复执行或用当前文件补造成功");return i}async function FI(e,t,n,r,i){return await iV(e,t,n,r),Bs(e,t,n,r)}async function Bs(e,t,n,r,i=n.outcome?.artifacts){await V(e,r+"/"+iy,{label:"Classic Archive manifest",expected:"file"});let s=await(await ay(e)).read(nl(t,n)),o=n.outcome?.output?.archiveManifest,c=s?.manifest??o;if(!c)return DI(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])ot(p,"Classic Archive path");let u=xr.relative(e,await le(xr.join(e,r))).replaceAll("\\","/");return{paths:[...new Set([...l,r+"/"+iy,...f.filter(p=>p.startsWith(c.activeRef+"/"))])],sourcePaths:f,stateFiles:[u,c.activeRef+"/"+xr.posix.basename(u)],optionalPaths:[...new Set([...a,...[".comet-state.lock",".comet-state-transaction.json"].map(p=>r+"/"+p+"/.comet-runtime-migration.json")])]}}function _f(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function qi(e,t){return Ft(e)===Ft(t)}function HI(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 ta(e,t,n={}){if(_f(t.state).archived!==!0||jI(e,t))return null;let r=(n.projection?Ef:Bn)(e,t.runId,{preserveSourceRevision:!0});if(!r)return null;let i=_f(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,u=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&&!u||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(HI(p),HI(s))||c(),_d(p,Ft(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 d=p.status==="succeeded",m=p.status==="failed";(t.status!==(d?"completed":m?"failed":"running")||t.reason!==(m?`ACTION_FAILED: ${o}`:void 0)||_f(t.state).branchStatus!==(d?"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)&&!(u&&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:{..._f(t.state),branchStatus:i.branchStatus},actions:[...t.actions.slice(0,-1),s],outputs:h};return delete g.reason,Ws(e,g)||c(),r}import{execFileSync as cV}from"node:child_process";var BI=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],sV={"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"]}},VI={open:"open-complete",design:"design-complete",build:"build-complete",verify:"verify-pass"};function oV(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 At(e,t,n={}){let r=sV[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",oV(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 Pf(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 cy(e,t,n){let r=ar(t),i=D(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=Ms(e),o=u=>Object.hasOwn(r.steps,u),c=new Set;for(let u of s.actions)!o(u.stepId)&&["pending","running","unknown"].includes(u.status)&&(c.add(u.stepId),u.status="cancelled",u.reason="旧检查调度已移交 Agent 平台;原进程结果未确认,不代表已经停止或通过。");for(let u of[...s.waits,...s.evidenceWaits??[]])!o(u.stepId)&&u.status==="pending"&&(c.add(u.stepId),u.status="cancelled");let l=s.ready;s.ready=l.filter(u=>o(u.to)&&(u.from===null||o(u.from)));for(let u of l)(!o(u.to)||u.from!==null&&!o(u.from))&&c.add(u.to);if(e.status==="failed"&&e.reason?.startsWith("ACTION_FAILED: ")){let u=e.reason.slice(15);o(u)||c.add(u)}let f=s.state;if(e.workflow.version==="1"&&f.phase==="verify"&&s.evidenceWaits?.some(u=>u.status==="pending"&&u.stepId.endsWith(".verify.report.evidence")))for(let u of s.evidenceWaits)u.status==="pending"&&u.stepId.endsWith(".verify.report.evidence")&&(u.status="cancelled",c.add(u.stepId));let a=s.actions.some(u=>["pending","running","unknown"].includes(u.status))||s.waits.some(u=>u.status==="pending")||s.evidenceWaits?.some(u=>u.status==="pending");if(c.size&&!a&&!s.ready.length&&!["completed","cancelled"].includes(e.status)){let u=[...s.actions].reverse().find(m=>m.stepId===f.workflow+".build.execute"&&m.status==="succeeded");if(!u)throw new Error("旧 Classic Run 缺少已接受的 Build 来源,原记录保持不变。");let p=f.phase==="build"&&n?n.apply({run:s,event:{kind:"action-outcome",stepId:u.stepId,outcome:u.outcome}}):void 0;p?s.state=p.state:f.phase==="build"&&(s.state=At(f,"build-complete").classic);let d=s.actionContexts[u.id];for(let m of p?.next??[f.workflow+".verify.run"])s.ready.push({from:u.stepId,to:typeof m=="string"?m:m.stepId,...typeof m=="string"?{}:{activation:m.input},results:{...d.results,[u.stepId]:{sequence:d.sequence,value:u.outcome.output}}});s.status="running",delete s.reason}s.workflow={id:r.id,version:r.version,hash:i};for(let u of Object.keys(s.definitionHashes))JSON.parse(u)[0]===r.id&&delete s.definitionHashes[u];return s.definitionHashes[JSON.stringify([r.id,r.version])]=i,s}import{randomUUID as lV}from"node:crypto";import ly from"node:path";bn();un();nt();Zi();import aV from"node:path";async function UI(e){let t=await ho(e,{allowPartialProject:!0,allowMissingNativeFields:!0});return t?.native?[aV.posix.join(t.native.artifact_root,"comet","changes")]:[]}function Of(e,t){return t.some(n=>e===n||e.startsWith(`${n}/`))}function Tf(e,t){return cV("git",t,{cwd:e,encoding:"utf8",windowsHide:!0,timeout:3e4,maxBuffer:Number.MAX_SAFE_INTEGER,stdio:["ignore","pipe","pipe"]})}function KI(e){let t;try{t=Tf(e,["diff","HEAD","--name-only","--no-renames","-z"])}catch{t=Tf(e,["ls-files","--cached","-z"])}return[...new Set([...t.split("\0"),...Tf(e,["ls-files","--others","--exclude-standard","-z"]).split("\0")].filter(Boolean))]}async function zI(e){let t=await Gn(e);return[".comet",t.openSpecRoot,t.superpowersRoot,...await UI(e)].map(n=>ly.isAbsolute(n)?ly.relative(e,n).replaceAll("\\","/"):n)}async function JI(e){return vn({singleWriter:!0,rootDir:ly.join(await Nr(e),"classic-delivery-baselines")})}async function uV(e){return Qt(e)?{schema:"comet.classic.workspace-baseline.v2",paths:KI(e)}:void 0}async function GI(e,t){let n=await uV(e);if(!n)return t;let r=lV();return await(await JI(e)).compareAndSwap(r,null,{runId:r,revision:1,paths:n.paths}),{...t,workspaceBaseline:{ref:r}}}async function dV(e,t){let n=t?.input?.workspaceBaseline?.ref;if(!n)return new Set;let r=await(await JI(e)).read(n);return new Set(r?.paths??Object.keys(r?.files??{}))}async function YI(e,t,n){if(!Qt(e))return[];let r=await zI(e),i=await dV(e,t);if(n){for(let s of n)if(ot(s,"Classic delivery path"),Of(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 KI(e).filter(s=>!s.split("/").includes("node_modules")&&!Of(s,r)&&!i.has(s)).sort()}async function XI(e,t){let n=t.state,r=[...t.actions].reverse().find(m=>m.stepId===n.workflow+".archive.deliver"),i=r?cr(t,r)?.repairCheckId:void 0,s=Pf(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 zI(e),a=(c.deliveryPaths??Object.keys(c.deliveryInputs??l??{})).filter(m=>!Of(m,f)),u=t.evidenceWaits?.slice().reverse().find(m=>m.stepId===n.workflow+".verify.report.evidence"&&m.status==="resolved")?.receipt,p=t.input.changeDir,d=t.outputs[n.workflow+".archive.execute"]?.value?.archiveDirectory;if(n.verificationReport&&!u)throw new Error("Classic 交付缺少已接受的验证报告");return u&&a.push(d?xt(u.ref,p,d):u.ref),uy(e,a)}async function uy(e,t,n){let r=Array.isArray(t)?t:Object.keys(t);for(let s of r)ot(s,"Classic delivery path");let i=r.length?Tf(e,["status","--porcelain","--untracked-files=all","--",...r]).trim():"";if(i)throw new Error("Classic 交付路径尚有未提交修改:"+i);return new Set(r)}import{createHash as fV}from"node:crypto";import{execFileSync as fy}from"node:child_process";function dy(e,t,n){let r=fy("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 na(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=dy(e,t,!1),r=dy(e,t,!0);if(n!==r)throw new Error("Classic delivery remote has different fetch and push URLs");return fV("sha256").update(n).digest("hex")}function ZI(e,t,n){let r=`refs/heads/${n}`,i=fy("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 pV(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 QI(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 e_(e){let t=pV(dy(e.projectRoot,e.remote,!1)),n=t&&QI(e.prUrl,t);if(!t||!n)return!1;let r=fy("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"&&QI(i.url,t)===n&&i.headRefName===e.targetBranch&&i.headRefOid===e.commit&&i.baseRefName===e.baseBranch&&(i.state==="OPEN"||i.state==="MERGED")}Ot();Re();nt();import rl from"node:path";async function ra(e,t,n){let r=await Gn(e),i=await V(e,t,{label:"Classic Verify report",expected:"file"}),s=rl.relative(r.superpowersReportsDir,i.target);if(!i.exists||!s||s.startsWith(`..${rl.sep}`)||rl.isAbsolute(s)||s.includes(rl.sep)||rl.extname(s).toLowerCase()!==".md")throw new Error("Classic Verify report is outside the configured reports directory");let o=i.relative.replaceAll("\\","/");if(!(await ue(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 Nf={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}}}},i_={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}}}},py={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===i_.id&&s?.contentHash===t.inputHash?{accepted:!0}:{accepted:!1,reason:"Classic Open has no approval for its current SDK request"}}},my={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 Ar(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 Oo({run:e,projectRoot:n.projectRoot,changeDir:zt.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)}}}},hy={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=vr(i);return s.missingFields.length||s.invalidFields.length?{accepted:!1,reason:"Classic Build configuration is incomplete or invalid"}:{accepted:!0}}},mV={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 Gn(i),[l,f]=await Promise.all([V(i,s.input.changeDir,{label:"Classic active change",expected:"directory"}),V(i,o.archiveDirectory,{label:"Classic archived change",expected:"directory"})]),a=zt.relative(c.archiveDir,f.target),u=zt.basename(f.target);if(l.exists||!f.exists||zt.dirname(l.target)!==c.changesDir||!a||a.startsWith(`..${zt.sep}`)||zt.isAbsolute(a)||a.includes(zt.sep)||!/^\d{4}-\d{2}-\d{2}-/u.test(u)||u.slice(11)!==zt.basename(l.target))return{accepted:!1,reason:"Classic Archive has not moved the approved change"};let p=await Eo(i,f.target);if(p.length>0)return{accepted:!1,reason:p.join(`
|
|
189
|
+
`)};let d=e.actions.find(m=>m.id===t.id);return d?.status==="succeeded"&&d.outcome&&D(d)===D(t)&&D(d.outcome)===D(n)?await Bs(i,e,d,o.archiveDirectory):await FI(i,e,t,o.archiveDirectory,n.artifacts),{accepted:!0}}catch(c){return{accepted:!1,reason:c instanceof Error?c.message:String(c)}}}};async function hV(e,t,n,r){let i=zt.relative(e,await le(zt.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 oe(e,zt.join(e,i),{label:"Classic state file"}),c=(0,yy.parseDocument)(s,{uniqueKeys:!0}),l=(0,yy.parseDocument)(o,{uniqueKeys:!0});if(c.errors.length>0||l.errors.length>0)return!1;let f=c.toJS(),a=l.toJS();return!Bn(f[Dt],r.runId)||!Bn(a[Dt],r.runId)||!el(a[Dt],Ls(r))&&!ta(a[Dt],r)?!1:(delete f[Dt],delete a[Dt],wy(f,a))}var gV={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=cr(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 u=rt(i);if(u!==l.targetBranch)return{accepted:!1,reason:`Classic 当前分支 ${u??"(detached HEAD)"} 与已批准目标 ${String(l.targetBranch)} 不一致`};if(l.deliveryAction!=="local"&&(typeof l.remote!="string"||a.remote!==l.remote||typeof l.remoteIdentity!="string"||na(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 d=Li("git",["rev-list","--reverse","--parents",`${l.baseCommit}..${p}`,"--"],{cwd:i,encoding:"utf8"}).trim().split(`
|
|
190
|
+
`).filter(Boolean);if(!d.length)return{accepted:!1,reason:`Classic 已批准基线 ${l.baseCommit} 之后没有交付提交`};let m=l.baseCommit,h=new Set,g=NI(i,d.map(j=>j.split(/\s+/u)[0]));for(let j of d){let[N,...W]=j.split(/\s+/u);if(W.length!==1)return{accepted:!1,reason:`Classic 交付范围包含非线性提交 ${N}(父提交数 ${W.length});只接受从已批准基线 ${l.baseCommit} 连续产生的单父提交`};if(W[0]!==m)return{accepted:!1,reason:`Classic 交付提交 ${N} 的父提交 ${W[0]} 不等于 ${m};交付范围必须从已批准基线 ${l.baseCommit} 连续开始`};let K=g.get(N);for(let se of K)h.add(se);m=N}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("\\","/"),C=Hs(e,t).outputs,q=C["full.build.plan"],T=C["full.design.document"]?.designDoc??q?.designEvidence?.ref,F=q?.plan;if(s==="full"&&(typeof T!="string"||typeof F!="string"))return{accepted:!1,reason:"Classic Archive documents are missing"};let B=zt.posix.basename(R),X=typeof T=="string"?xt(T,y,R):null,Y=typeof F=="string"?xt(F,y,R):null,de=s==="full"?Li("git",["show",`HEAD:${X}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,G=s==="full"?Li("git",["show",`HEAD:${Y}`],{cwd:i,encoding:"utf8",stdio:["ignore","pipe","pipe"]}):null,ie=await XI(i,e),Ye=e.actions.slice().reverse().find(j=>j.stepId===`${s}.archive.execute`&&j.status==="succeeded");if(!Ye)throw new Error("Classic delivery 缺少成功的 Archive Action");let O=await Bs(i,e,Ye,R);for(let j of O.optionalPaths){let N=j.startsWith(`${R}/`)?`${y}/${j.slice(R.length+1)}`:null;if(Li("git",["ls-tree","-z","HEAD","--",j],{cwd:i,encoding:"utf8"}))O.paths.push(j,...N?[N]:[]);else if(N&&[...g.values()].some(K=>K.includes(N)))throw new Error(`Classic archive commit deletes an optional input without committing the archived copy: ${j}`)}let U=await uy(i,O.paths),ne=j=>ie.has(j)||U.has(j)||O.stateFiles.includes(j),Ke=[...h].filter(j=>!ne(j));if(Ke.length)return{accepted:!1,reason:`Classic 交付提交范围包含未批准的路径:${Ke.join(", ")}`};let x=k!==""&&await hV(i,R,k,e);return w?k&&!x?{accepted:!1,reason:`Classic 归档目录与交付 HEAD 不一致:${k}`}:[...h].some(j=>j.startsWith(`${R}/`))?s==="full"&&(!X||!Y||!h.has(X)||!h.has(Y)||!de?.includes(`archived-with: ${B}`)||!de.includes("status: final")||!G?.includes(`archived-with: ${B}`))?{accepted:!1,reason:`Classic 交付范围缺少已归档的设计或计划,或归档标记不符:${X}, ${Y}`}:l.deliveryAction!=="local"&&ZI(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"||!e_({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(u){return{accepted:!1,reason:u instanceof Error?u.message:String(u)}}}};async function Ar(e,t,n={}){let r=await V(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 pi(e,r.target);if(i.problems.length)throw new Error(i.problems.join(`
|
|
191
|
+
`));return{ref:r.relative}}async function vy(e,t){let n=ot(t,"Classic Design document");if(!(await ue(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 $f(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 V(e,n.designDoc,{label:"Classic accepted Design",expected:"file"}),{ref:r.ref}}async function jf(e,t,n){if((await ws(e,t)).status!=="ready")throw new Error("Classic Build plan is not ready");let i=await V(e,t,{label:"Classic Build plan",expected:"file"}),s=await V(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 Df(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 Vs(e,t,n,r){await il(e,t,r);let i=vr(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=rt(e),o=dn({isolation:n.isolation,boundBranch:n.boundBranch,currentBranch:s,gitWorkTree:s===null?Qt(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 V(e,t,{label:"Classic change",expected:"directory"});if(!c.exists)throw new Error("Classic change directory does not exist");let l=zt.posix.join(c.relative.replaceAll("\\","/"),"tasks.md"),f=await ue(e,l,Number.MAX_SAFE_INTEGER,{label:"Classic Build tasks"}),a=Mt(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 Df(e,t,r),await $f(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 u=zt.posix.join(c.relative.replaceAll("\\","/"),"proposal.md");if(!(await ue(e,u,Number.MAX_SAFE_INTEGER,{label:"Classic Build proposal"})).bytes.toString("utf8").trim())throw new Error("Classic Build proposal is empty");let d=zt.posix.basename(c.relative.replaceAll("\\","/")),m=await sd(e,d,n);if(m.length>0)throw new Error(m.join(`
|
|
192
|
+
`))}async function il(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 t_={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 Ar(r.projectRoot,t,{run:e});let c=await xf(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)}}}},wV={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 vy(r.projectRoot,t),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},yV={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 jf(r.projectRoot,t,String(e.input.changeDir)),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},n_={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 ra(r.projectRoot,t,i.language),{accepted:!0,actualHash:s.inputHash}}catch(o){return{accepted:!1,actualHash:"",reason:String(o)}}}},vV=["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"]},r_={type:["boolean","null"]},gy={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 Ar(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 s_(e){let t=e==="full"?null:s_("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"?[i_]:t.executors,validators:t?.validators??[...e==="full"?[py,my,hy]:[],mV,gV,gy],evidenceValidators:t?.evidenceValidators??(e==="full"?[t_,wV,yV,n_]:[t_,n_]),workflow:{id:`comet-classic-${e}`,version:"2",entry:n,stateSchema:{type:"object",required:vV,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:r_,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:r_,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:py.id,version:py.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:my.id,version:my.version}}:{validator:{id:gy.id,version:gy.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:Nf,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:hy.id,version:hy.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:Nf,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:Nf,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:Nf,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 u=c.actions.find(p=>p.id===l.outcome.actionId);(u?.executionOrigin?.workflow.version!=="1"||u.status!=="succeeded"||c.outputs[l.stepId]?.sequence!==c.actionContexts[u.id]?.sequence||!wy(c.outputs[l.stepId]?.value,u.outcome?.output)||!wy(u.outcome,l.outcome))&&sa(a)}}if(l.kind==="action-outcome"&&l.outcome.status==="failed"&&c.actions.find(u=>u.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:{...At(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:At(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:At(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:At(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:At(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(u=>u.name==="revise-design"&&u.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:At(c.state,"design-complete").classic,next:[c.commands?.some(u=>u.name==="revise-design"&&["build","verify","archive"].includes(c.actions.find(p=>p.id===u.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 u=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"||u===void 0||p===void 0||D(u)!==D(p))throw new Error("Classic Build confirmation no longer matches the proposed choices");let d=u,m={...c.state,...d},h=vr(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:u}=l.outcome.output;return{state:{...c.state,plan:a,buildPause:u??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:At(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:At(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:At(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:At(c.state,"archive-reopen").classic,next:[`${e}.verify.run`]};if(l.choice==="later")return{state:c.state,next:[`${e}.archive.confirm`]};let u=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(u===void 0||p===void 0||D(u)!==D(p))throw new Error("Classic Archive choice no longer matches its proposal");let d=u,m=c.state;if(!["local","push","pr"].includes(l.choice)||!m.boundBranch||d.targetBranch!==m.boundBranch||l.choice!=="local"&&!d.remote||l.choice==="pr"&&!d.prBaseBranch)throw new Error("Classic Archive target does not match the bound branch or delivery");return{state:At(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(d=>d.stepId===`${e}.archive.confirm`&&d.status==="resolved"&&["local","push","pr"].includes(d.decision?.choice??"")),u=a?.proposal?.outputs?.[`${e}.archive.prepare`],p=l.outcome.output;if(!a||!u||a.decision?.choice!==p.deliveryAction||u.targetBranch!==p.targetBranch||a.decision?.choice==="pr"&&u.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=At(c.state,"archived"),u=c.input.changeDir.replaceAll("\\","/"),p=l.outcome.output.archiveDirectory.replaceAll("\\","/");return{state:{...a.classic,designDoc:xt(a.classic.designDoc,u,p),plan:xt(a.classic.plan,u,p),verificationReport:xt(a.classic.verificationReport,u,p),handoffContext:xt(a.classic.handoffContext,u,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:At(c.state,"open-complete").classic,next:[i]}}}}}function ia(e,t){let n=e.actions.slice().reverse().find(r=>r.stepId===t);if(!n)throw new Error("Classic evidence has no originating Action");return n.inputHash}function sa(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")}async function qf(e,t){let n=JSON.parse((await ui(zt.resolve(e,t),Number.MAX_SAFE_INTEGER,{label:"Classic check reports"})).bytes.toString("utf8"));if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(r=>!["checks","checksReason"].includes(r))||!Array.isArray(n.checks)||n.checksReason!==void 0&&typeof n.checksReason!="string"||n.checks.some(r=>!r||typeof r!="object"||typeof r.name!="string"||typeof r.result!="string"||r.note!==void 0&&typeof r.note!="string"||Object.keys(r).some(i=>!["name","result","note"].includes(i))))throw new Error("Classic checks file must contain checks with name/result/note and optional checksReason");return sa(n),{checks:n.checks,...n.checksReason===void 0?{}:{checksReason:n.checksReason}}}var oa=s_;import{AsyncLocalStorage as AV}from"node:async_hooks";vo();function o_(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&&sl(e,n)}function sl(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)}function ol(e){return e.ref==="classic-archive"&&(e.status==="running"||e.status==="unknown"||e.status==="cancelled"&&!!e.claim&&!e.outcome)}function Us(e){return e.status==="cancelled"&&e.children.length===0&&e.actions.every(t=>!["pending","running","unknown"].includes(t.status)&&!ol(t))&&e.waits.every(t=>t.status!=="pending")&&(e.evidenceWaits??[]).every(t=>t.status!=="pending")&&e.ready.length===0}Wu();un();import{AsyncLocalStorage as bV}from"node:async_hooks";kf();import{createHash as RV,randomUUID as c_}from"node:crypto";import by from"node:path";gh();import{promises as Lf}from"node:fs";import ky from"node:path";async function Wf(e,t){let n=hh(e),r=ky.join(n.workspaceRoot,"observability"),i=n.dataRoot;for(let o of["","workspaces",n.workspaceId,"observability"]){i=ky.join(i,o);let c;try{c=await Lf.lstat(i)}catch(l){if(!t||l.code!=="ENOENT")throw l;await Lf.mkdir(i,{recursive:o===""}).catch(f=>{if(f.code!=="EEXIST")throw f}),c=await Lf.lstat(i)}if(!c.isDirectory()||c.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let s=ky.join(r,"performance.sqlite");for(let o of["","-wal","-shm"])try{let c=await Lf.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 kV}from"node:util";function a_(e,t=process.env){let n=kV(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 SV=864e5,CV=1e4,Mf=new bV;function Ry(e){let t=Mf.getStore();t&&t.binding.workflow===e.workflow&&(!t.binding.runId||t.binding.runId===e.runId)&&Object.assign(t.binding,e)}function al(e,t){return a_(e).slice(0,t)}async function Ff(e,t){if(!t.length)return;let n=Mf.getStore();if(n){let i=s=>process.platform==="win32"?by.resolve(s).toLowerCase():by.resolve(s);if(i(e)===i(await n.projectRoot())){n.spans.push(...t);return}}let r=Qo(await Wf(e,!0));try{r.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
193
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
194
|
+
id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
|
|
195
|
+
change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
|
|
196
|
+
parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
197
|
+
started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
|
|
198
|
+
revision INTEGER NOT NULL, data TEXT NOT NULL);
|
|
199
|
+
CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
|
|
200
|
+
CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
|
|
201
|
+
BEGIN IMMEDIATE;`);let i=r.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
202
|
+
ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
|
|
203
|
+
started_at=COALESCE(trace_spans.started_at,excluded.started_at),
|
|
204
|
+
ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
|
|
205
|
+
WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
|
|
206
|
+
ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
|
|
207
|
+
revision=MAX(trace_spans.revision,excluded.revision),
|
|
208
|
+
data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
|
|
209
|
+
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:al(o.name,240),summary:o.summary?al(o.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(o.attributes??{}).slice(0,20).map(([a,u])=>[al(a,80),Array.isArray(u)?u.slice(0,30).map(p=>al(p,240)):typeof u=="string"?al(u,2e3):u]))};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(u=>u!=="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=RV("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*SV).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(CV),r.exec("COMMIT")}finally{r.close()}}async function l_(e,t){let n=Mf.getStore(),r=n?.binding.workflow===e.workflow?n:void 0;if(r)try{let p=(await Promise.all([e.projectRoot(),r.projectRoot()])).map(d=>{let m=by.resolve(d);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??c_(),spanId:c_(),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 u=[];for(let p=s;p;p=p.parent)u.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 Ff(await e.projectRoot(),u)}catch{}}let o,c,l=!1;try{o=await Mf.run(s,t)}catch(u){l=!0,c=u}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 Ff(await e.projectRoot(),s.spans)}catch{}if(l)throw c;return o}var EV=(e,t)=>`workflow:${e}:${t}`,u_=(e,t)=>{let n=e.split(".");return t==="classic"&&["full","hotfix","tweak"].includes(n[0])?n[1]??n[0]:n[0]},d_=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}))}),f_=e=>e&&typeof e=="object"?Array.isArray(e)?[`${e.length} items`]:Object.keys(e).slice(0,30):[e===null?"null":typeof e];function xV(e){let{workflow:t,previous:n,next:r,initial:i,observedAt:s}=e,o=EV(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])),u=[{...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 d=a.get(`${p.id}:${p.attempt}`);if(d&&d.status===p.status&&d.outcome?.outcomeId===p.outcome?.outcomeId&&d.reason===p.reason&&d.outcome?.summary===p.outcome?.summary)continue;let m=["succeeded","failed","cancelled"].includes(p.status);u.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"&&(d?.status==="pending"||i)?s:null,endedAt:m&&(i||n!==null)?s:null,summary:p.outcome?.summary??p.reason,attributes:{phase:u_(p.stepId,t),actionId:p.id,actionType:p.type,ref:p.ref??null,executor:p.claim?.executorId??null,inputFields:f_(p.input),outputFields:p.outcome?f_(p.outcome.output):[],artifacts:(p.outcome?.artifacts??[]).map(h=>h.uri)}})}for(let p of["wait","evidence"]){let d=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 d){let w=h.get(g.id);w?.status!==g.status&&u.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:u_(g.stepId,t),waitId:g.id,decision:"decision"in g?g.decision?.choice??null:null}})}}return u}function p_(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?d_(s):null}catch{r=null}return s&&Ry({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){Ry({workflow:t,change:i,runId:i});try{await Ff(e,xV({workflow:t,previous:c,next:o,initial:s===null,observedAt:new Date().toISOString()}))}catch{}try{r=d_(o)}catch{r=null}}return l}}}Ot();un();import{promises as IV}from"node:fs";var cl=St(_t(),1);import{createHash as _V}from"node:crypto";import Ks from"node:path";import{isDeepStrictEqual as PV}from"node:util";Ze();_n();Tt();Tt();var m_=new Set(["language","contextCompression","autoTransition","reviewMode"]);var h_=new AV;function OV(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 Vn(e,t){return PV(e,t)}function g_(e,t){return Object.keys(e).filter(n=>!Vn(e[n],t[n]))}function Sy(e){return e.actions.some(ol)}function Wi(e,t={},n=!1){let r=mt(e),i=!1,s=async(p=t.readOnly)=>{if(!p&&mt(e)!==r)throw new Error("Classic SDK workspace identity changed; reload the store in the current workspace");return!p&&!i&&(await hr(e),i=!0),r},o=p_(e,"classic",t.store??vn({singleWriter:!0,rootDir:Ks.join(r,"sdk-runs","classic")})),c=p=>JSON.stringify([r,p]);function l(p,d){if(t.identity){let h=["runtime","dispatch","--application-file",Ks.join(t.identity.packageRoot,"application.json"),"--project-root",e,"--request","<recovery-request.json>","--json"];throw new Error(`Classic SDK Run ${p} requires recovery: ${d}. 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.
|
|
210
|
+
Recovery argv: ${JSON.stringify(h)}
|
|
211
|
+
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: ${d}. ${m} in ${e} to restore or synchronize its recorded state.`)}async function f(p,d){let m=null;for(let B of await Xn(e,p)){let X;try{X=await oe(e,B,{label:"Classic state file"})}catch(Y){if(Y.code==="ENOENT")continue;throw Y}if(Lt(X)){if(m)throw new Error(`Classic change ${p} has multiple SDK state files`);m={file:B,source:X}}}if(!m)return null;let h=(0,cl.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=Bn(g[Dt],p,{preserveSourceRevision:!0});if(!w)return null;if(D(g.application_checkpoint??null)!==D(t.identity??null))throw new Error("Classic portable checkpoint requires its original fixed Application package");let k=ln(g).classic,y=w.input,R=w.workflow.id.replace(/^comet-classic-/u,""),S=k?g_(w.state,k):[],C=typeof y?.changeDir=="string"?await le(Ks.join(e,...y.changeDir.split("/"))):null,q=C!==null&&m.file!==C;if(!k||S.some(B=>!m_.has(B))||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&&!sl(w,R)||!t.allowBranchRebind&&k.boundBranch!==null&&k.boundBranch!==rt(e))throw new Error(`Classic portable Run checkpoint for ${p} does not match its state`);let T=w.revision,F={...w,revision:T,...d?{state:k}:{}};if(d&&D(d)!==D({...F,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((T>1||d)&&!o.restoreCheckpoint)throw new Error(`Classic RuntimeStore cannot restore checkpoint revision ${T}; use a store with restoreCheckpoint support or restore the original Run history`);return await hc(e,{schema:ks,workflow:"classic",change:p,format:"sdk",application:t.identity?.id??`classic-${R}`,runId:p}),T===1&&!d?await o.compareAndSwap(p,null,F):await o.restoreCheckpoint(p,d?1:null,F),o.read(p)}async function a(p){let d=p.input;if(d?.change!==p.runId||typeof d.changeDir!="string")throw new Error(`Classic SDK Run ${p.runId} has invalid change identity`);let m=d.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=Ks.join(e,...m.split("/"));try{if((await IV.stat(h)).isDirectory())return le(h)}catch(y){if(y.code!=="ENOENT")throw y}if(!p.state.archived&&!Sy(p))return null;let g=Ks.join(Ks.dirname(h),"archive"),w=await Zu(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 le(Ks.join(g,k[0]))}async function u(p,d){return await Xn(e,p),await s(),(async()=>{let h;if(n)try{h=(await jo(o,p)).record}catch(G){if(G.code!=="RUN_NOT_FOUND")throw G;h=null}else h=await o.read(p);if(!h){t.readOnly&&l(p,"the recorded Run is missing or incomplete");let G=await Ga(()=>f(p,h??void 0));if(h&&!G)throw new Error(`Classic SDK Run ${p} requires its matching portable checkpoint or original Run history before completing recovery`);h=G}if(!h)return null;let g=h,w=g.state,k=await a(g),y=g.revision===1&&g.actions.every(G=>G.status==="pending"&&!G.claim);if(!k)return t.readOnly&&!y&&l(p,"the change directory is missing"),g;let R;try{R=await oe(e,k,{label:"Classic state file"})}catch(G){if(G.code!=="ENOENT")throw G;R=null}let S=R===null?new cl.Document:(0,cl.parseDocument)(R,{uniqueKeys:!0});if(S.errors.length>0)throw new Error(`Invalid Classic state file: ${S.errors[0].message}`);let C=S.toJS(),q=R===null?null:ln(C).classic,T=ta(C?.[Dt],g,{projection:n});if(T)return(R===null||!Lt(R)||!Vn(q,T.state)||t.identity&&!Vn(C.application_checkpoint,t.identity))&&l(p,"the immutable archived delivery checkpoint has changed"),g;if(q){let G=Bn(C?.[Dt],p,{preserveSourceRevision:!0});if(g.revision===1&&G&&G.revision>g.revision){t.readOnly&&l(p,"the initial checkpoint import is incomplete");let O=await f(p,g);O||l(p,"the initial checkpoint import is incomplete"),g=O,w=g.state}let ie=G?.state??w,Ye=g_(ie,q);if(Ye.some(O=>!m_.has(O))){let O=g.input?.recoverySourceHash,U=g.revision===1&&typeof O=="string"&&R!==null&&_V("sha256").update(R).digest("hex")===O;if(!Vn(q,w)&&!U)throw new Error(`Classic state file ${k} changed a Runtime-owned field`)}else if(Ye.some(O=>!Vn(w[O],q[O]))){if(!d)throw new Error(`Classic state file ${k} changed during an SDK transition`);for(let U of Ye)if(!Vn(w[U],ie[U])&&!Vn(w[U],q[U]))throw new Error(`Classic state file ${k} conflicts with SDK field ${U}`);t.readOnly&&l(p,"state file settings have not been imported"),w={...w};for(let U of Ye)w[U]=q[U];let O={...g,revision:g.revision+1,state:w};if(await Ga(()=>Xn(e,p)),!await o.compareAndSwap(p,g.revision,O))throw new Error(`Classic SDK Run ${p} changed while importing state file settings`);g=O}}if(q&&w.boundBranch===null&&ps(w.isolation)&&!w.archived&&["running","waiting"].includes(g.status)&&!g.actions.some(G=>["running","unknown"].includes(G.status))){let G=dn({isolation:w.isolation,boundBranch:w.boundBranch,currentBranch:rt(e)});if(G.status==="needs-heal"){t.readOnly&&l(p,"the Git branch binding has not been recorded"),w={...w,boundBranch:G.branch};let ie={...g,revision:g.revision+1,state:w};if(await Ga(()=>Xn(e,p)),!await o.compareAndSwap(p,g.revision,ie))throw new Error(`Classic SDK Run ${p} changed while binding its Git branch`);g=ie}}if(t.readOnly){let G=C?.[Dt],ie=G===void 0;return G!==void 0&&n?ie=Ws(G,g):G!==void 0&&(ie=el(G,Ls(g))),(R===null||!Lt(R)||!q||!Vn(q,w)||!ie||t.identity&&C.application_checkpoint!==void 0&&!Vn(C.application_checkpoint,t.identity))&&l(p,"the state projection or portable checkpoint is missing or stale"),g}let F=Ku(w),B=C??{};for(let[G,ie]of Object.entries(F))Vn(B[G],ie)||(ie===void 0?S.delete(G):S.set(G,ie));let X=Cf(Ls(g));Vn(B[Dt],X)||S.set(Dt,X),t.identity&&!Vn(B.application_checkpoint,t.identity)&&S.set("application_checkpoint",t.identity);let Y=S.toString(),de=Lt(Y)?Y:ph+Y;return R!==de&&await Rn(e,k,de,{label:"Classic state file"}),Us(g)&&(t.identity||await ch(e,"classic",g.runId)),g})()}return{queryScope:o.queryScope,async read(p){if(!t.identity&&h_.getStore()?.has(c(p)))return await s(!0),o.read(p);if(!t.readOnly){await s(!0);try{let d=await Wi(e,{...t,store:o,readOnly:!0}).read(p);if(d&&!Us(d))return d}catch{}}return u(p,!0)},async readProjection(p){await s(!0);let d=await Wi(e,{...t,store:o,readOnly:!0},!0).read(p);return await s(!0),d},async compareAndSwap(p,d,m){return Ga(async()=>{if(t.readOnly)throw new Error("Classic SDK read-only store cannot change a Run");if(m.status==="cancelled"&&d!==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 Xn(e,p),d!==null&&await a(m),await s();let h=await o.compareAndSwap(p,d,m);if(h&&d!==null){let g=h_.getStore(),w=c(p);g&&!t.identity&&m.workflow.version==="2"&&!OV(m)?g.set(w,()=>u(p,!1)):(g?.delete(w),await u(p,!1))}return h})}}}async function w_(e){let t={change:e.name,changeDir:TV.relative(e.projectRoot,e.changeDir).replaceAll("\\","/"),...e.recoverySourceHash?{recoverySourceHash:e.recoverySourceHash}:{},...e.recoverySource?{recoverySource:e.recoverySource}:{}},n=e.recoverySourceHash?t:await GI(e.projectRoot,t),r=oa(e.profile),i=Wi(e.projectRoot);return Ds({store:{async read(c){let l=await i.read(c);if(l&&!await Ei(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 hc(e.projectRoot,{schema:ks,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})}Tt();Ze();async function $V(e,t){if(!Lt(t))return null;let n=(0,Cy.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Classic state: ${n.errors[0].message}`);let r=ln(n.toJS()).classic,i=await NV.readdir(e),s=[];for(let o of i)o===".comet-state.lock"&&await rS(y_.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=>$u(o)||o===".openspec.yaml")?r:null}async function jV(e,t,n){return await Xn(e,t),n()}async function Ey(e,t){await Xn(e,t);let n=await Ci(e,"classic",t);return n||jV(e,t,async()=>{let r=await Ci(e,"classic",t);if(r)return r;let i=(await Qn(t,e)).directory,s=y_.relative(e,await le(i)),o=await V(e,s,{label:"Classic legacy change state",expected:"file"});if(!o.exists)return null;let c=await oe(e,o.target,{label:"Classic change state"});if(Lt(c)){let l=(0,Cy.parseDocument)(c,{uniqueKeys:!0});if(l.errors.length>0)throw new Error(`Invalid Classic state: ${l.errors[0].message}`);let f=l.toJS(),a=ln(f).classic;if(a?.archived&&a.isolation==="worktree"&&f.application_checkpoint==null&&a.boundBranch&&a.boundBranch!==rt(e)&&Bn(f[Dt],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 Ci(e,"classic",t);if(!p||p.format!=="sdk")throw new Error(`Recovered Classic change ${t} has no Run ownership`);return p}let u=await $V(i,c);if(u){await w_({projectRoot:e,name:t,profile:u.workflow,changeDir:i,initialState:u});let p=await Ci(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 YC(e,{schema:ks,workflow:"classic",change:t,format:"compat"})})}import{randomUUID as Fi}from"node:crypto";import{isDeepStrictEqual as LV}from"node:util";var v_=St(_t(),1);import DV from"node:path";Ze();Ot();Tt();async function Hf(e,t,n,r="delivery",i){let s=Fs(t,n),o=t.state,c=dn({isolation:o.isolation,boundBranch:o.boundBranch,currentBranch:rt(e),gitWorkTree:Qt(e)});if(!["ok","not-applicable"].includes(c.status))throw new Error("Classic delivery repair requires its approved branch");await Bs(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 k_(e,t,n){if(!Af(t))throw new Error("Classic delivery repair requires the original archived Run with no unresolved execution");let r=Fs(t);{if(!n)throw new Error("Classic v2 delivery repair requires --checks <checks-json-file>");sa(n);let i={checkpointHash:await qV(e,t),archiveActionId:r.archive.id,checkActionId:r.check.id,reports:n};return await Hf(e,t,i,"prepare"),i}}async function qV(e,t){let n=Fs(t),r=await oe(e,await le(DV.join(e,n.archiveRef)),{label:"Classic archived delivery checkpoint",maxBytes:Number.MAX_SAFE_INTEGER}),i=(0,v_.parseDocument)(r,{uniqueKeys:!0});if(!Lt(r)||i.errors.length)throw new Error("Classic archived checkpoint is invalid");let s=Ue(i.toJS()),o=s.run_checkpoint;if(D(ln(s).classic)!==D(t.state)||!Ws(o,t)&&ta(o,t,{projection:!0})===null)throw new Error("Classic archived checkpoint changed after the authoritative Run was read");return D(o)}function b_(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:u}){let p=Ue(a);if(!u?.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):Ms(n);if(h.workflow.hash=l.workflow.hash,h.definitionHashes[JSON.stringify([l.workflow.id,l.workflow.version])]=l.workflow.hash,D(h)!==D(l))return{accepted:!1,reason:"Classic delivery repair no longer matches its authoritative source Run"}}let d=await k_(u.projectRoot,n??l,p.deliveryRepair.reports),m=D(d)===D(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:u}){if(!u?.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=ea(f);if(a.status!=="succeeded"||!LV(a.output,{...p.reports,deliveryPaths:ry(l,p)}))return{accepted:!1,reason:"Classic delivery repair reports differ from the submitted reports"}}return a.status==="succeeded"&&await Hf(u.projectRoot,l,ea(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 Hf(f.projectRoot,a,ea(l),"prepare")},async execute(l,f,a){if(!f?.projectRoot||!a)throw new Error("Classic delivery repair requires its project");{let u=ea(l);return{status:"succeeded",output:{...u.reports,deliveryPaths:ry(a,u)}}}}};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 _y(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 ll={id:"comet-classic-work-continuation-command",version:"1",async validate({run:e,name:t,input:n,context:r}){let i=n,s=_y(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"}}},R_={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===R_.id&&n.status==="succeeded"&&i?.status==="failed"&&i.type==="invoke_skill"&&D(n.output)===D({interruptedActionId:i.id,resumeStepId:i.stepId}),reason:"Classic continuation does not match its original failed Skill"}}};function Py(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 Ay={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"&&(Py(e)!==null||zs(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 Oy(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 Iy={id:"comet-classic-archive-repair-command",version:"1",async validate({run:e,name:t,input:n,context:r}){let i=n,s=Oy(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 WI(r.projectRoot,e,s),{accepted:!0,allowFailed:!0})}},ul={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)&&zs(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 zs(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 Bf={id:"comet-classic-verification-revision-command",version:"1",validate({run:e,name:t,input:n}){let r=n;return{accepted:t==="reopen-verification"&&zs(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 WV(e,t=!0,n=!0,r=!0,i=!0,s){let o=oa(e),c={...ll,async validate(f){if(!s)return ll.validate(f);let a=f.run.workflow.hash===s.workflow.hash?structuredClone(s):Ms(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,D(a)!==D(f.run)?{accepted:!1,reason:"Classic continuation no longer matches its authoritative source Run"}:ll.validate({...f,run:s})}},l=n&&t==="full"&&e!=="full"?oa("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:ll.id,version:ll.version}}}:{},...r?{"continue-build":{stepId:`${t==="full"?"full":e}.build.execute`,validator:{id:Ay.id,version:Ay.version}}}:{},...n?{"repair-archive":{stepId:`${t==="full"?"full":e}.open`,validator:{id:Iy.id,version:Iy.version}}}:{},...t?{"reopen-verification":{stepId:`${t==="full"?"full":e}.verify.run`,validator:{id:Bf.id,version:Bf.version}}}:{},"revise-design":{stepId:"full.design.handoff",validator:{id:ul.id,version:ul.version}},"revise-plan":{stepId:"full.build.plan",validator:{id:ul.id,version:ul.version}}}},commandValidators:[...i?[c]:[],...r?[Ay]:[],...n?[Iy]:[],ul,...t?[{...Bf,validate:f=>f.run.state.workflow!==(t==="full"?"full":e)?{accepted:!1,reason:"Classic verification command does not match the active workflow profile"}:Bf.validate(f)}]:[]],executors:[...o.executors,...i?[R_]:[]],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,u=f.run.actions.find(d=>d.id===a.interruptedActionId),p=u?.stepId.endsWith(".archive.deliver")?u.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 S_(e,t,n={}){let r={...oa(e),commandValidators:[]};if(!t||t.workflow.hash===D(ar(r.workflow)))return r;let i=t.state.workflow,s=WV(e,i==="full"&&e!=="full"?"full":!0);if(t.workflow.hash===D(ar(s.workflow)))return s;let o=b_(s,i);if(t.workflow.hash===D(ar(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}async function Vf(e,t,n={}){let r=t.state,i=t.runId,s=t.input,o=t.revision,c=[],l=(u,p)=>{let d=`revise-${u}`;c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:p,remediation:`Run comet state ${d} ${i} --expected-revision ${o}, then ${u==="design"?"propose-design and approve the new proposal":"submit-plan and follow its next action"}`,commandArgs:["comet","state",d,i,"--expected-revision",String(o)]})};if(r.workflow!=="full"&&!r.archived&&["build","verify","archive"].includes(r.phase)&&!t.waits.some(u=>u.status==="pending"&&u.stepId===`${r.workflow}.build.escalation-confirm`))try{await il(e,s.changeDir,t)}catch(u){c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:u instanceof Error?u.message:String(u),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(u=>u.stepId==="full.design.handoff"&&u.status==="pending")){let u=t.outputs["full.design.handoff"]?.value,p=u?.requirementsEvidence??t.outputs["full.open.evidence"]?.value;if(p)try{let d=await Ar(e,s.changeDir,{designRequirements:!!u?.requirementsEvidence});p.ref!==d.ref&&l("design","Classic Design requirements changed after the proposal")}catch(d){l("design",d instanceof Error?d.message:String(d))}}let f=!1;if(r.workflow==="full"&&["build","verify","archive"].includes(r.phase)&&!r.archived&&!t.actions.some(u=>u.stepId==="full.design.handoff"&&u.status==="pending"))try{await Df(e,s.changeDir,t),await $f(e,t)}catch(u){f=!0,l("design",u instanceof Error?u.message:String(u))}if(!f&&r.workflow==="full"&&["build","verify","archive"].includes(r.phase)&&!r.archived&&r.plan&&!t.actions.some(u=>u.stepId==="full.build.plan"&&u.status==="pending")){let p=t.outputs["full.build.plan"]?.value?.planEvidence??t.evidenceWaits?.slice().reverse().find(d=>d.stepId==="full.build.plan.evidence"&&d.status==="resolved")?.receipt;if(p)try{let d=await jf(e,r.plan,s.changeDir);p.ref!==d.ref&&l("plan","Classic Build plan or task requirements changed after accepted evidence")}catch(d){l("plan",d instanceof Error?d.message:String(d))}}let a=u=>{if(!zs(t)){c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:u,remediation:"Reconcile the unresolved work before replacing accepted Verify evidence",commandArgs:["comet","state","next",i]});return}c.push({code:"CLASSIC_EVIDENCE_DRIFT",message:u,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 u=`${r.workflow}.verify.run`,p=t.actions.slice().reverse().find(h=>h.stepId===u),d=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"&&d!==void 0&&h.results[u]?.sequence===d)?.receipt;if(m)try{let h=await ra(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}import{execFileSync as C_}from"node:child_process";import{randomUUID as Ny}from"node:crypto";import E_ from"node:path";ds();gd();import{AsyncLocalStorage as Ty}from"node:async_hooks";vu();var Jee=new Ty,Gee=new Ty,Yee=new Ty;function FV(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 aa(e,t){try{let n=e.state;if(!n||!o_(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=FV(e);await il(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=Hs(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 Vs(t,String(e.input.changeDir),n,e)}let s=rt(t);if(!s||s!==n.boundBranch||s!==r.targetBranch)throw new Error("Classic Archive branch differs from the approved bound branch");return await HV(e,t,n),r}catch(n){throw new dl(n instanceof Error?n.message:String(n),{cause:n})}}async function HV(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");Pf(e)||sa(o);return}}async function BV(e,t,n){let r=E_.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 aa(e,r),o=s.targetBranch,c=s.remote?na(r,s.remote):void 0,l=C_("git",["rev-parse","HEAD"],{cwd:r,encoding:"utf8"}).trim();if(rt(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 YI(r,e,s.deliveryPaths),...s.remote?{remote:s.remote,remoteIdentity:c}:{},...s.prBaseBranch?{prBaseBranch:s.prBaseBranch}:{}}}}async function x_(e,t){let n=E_.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 BV(r,s,n),c=o.output,l=Ny(),f=Ny();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(rt(n)!==c.verifiedBranch||C_("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:Ny(),...o}})}catch(a){let p=(await e.inspect(r.runId)).actions.find(d=>d.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}}var KV=St(_t(),1);import{execFileSync as VV}from"node:child_process";import{randomUUID as jy}from"node:crypto";import{promises as UV}from"node:fs";import ca from"node:path";Re();ic();nt();Tu();Tu();_n();Dm();function $y(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,u=o.status??s.status,{current:p,...d}=l,m=p===void 0?l:{...d,currentRef:r.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof o.phase=="string"?o.phase:null,status:typeof u=="string"?u: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}}:{}}}nt();rh();Ze();async function A_(e=process.cwd()){let t=await ct(e),n=await Tr(t);await Ou(t,n);let r=process.env.COMET_OPENSPEC||"openspec";try{ku(r,[],{cwd:n.openSpecBase})}catch(i){throw new Error(`OpenSpec CLI unavailable: ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}Ze();Ot();Tt();function zV(e,t){return/^\d{4}-\d{2}-\d{2}-/u.test(e)&&e.slice(11)===t}async function Dy(e,t){try{return new Set((await UV.readdir(e)).filter(n=>zV(n,t)))}catch(n){if(n.code==="ENOENT")return new Set;throw n}}async function I_(e,t,n,r){if(!t)return;let i=await V(e,t,{label:"Classic Archive document",expected:"file"});if(!i.exists)return;let s=await oe(e,i.target,{label:"Classic Archive document"});await Rn(e,i.target,ny(s,n,r),{label:"Classic Archive document"})}async function __(e,t,n){let r=e.state.workflow,i=e.actions.slice().reverse().find(u=>u.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 aa(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!==na(n,s.remote))||VV("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 Gn(n),f=await V(n,c.changeDir,{label:"Classic active change",expected:"directory"});if(!f.exists||f.target!==ca.join(l.changesDir,c.change))throw new Error("Classic Archive active change differs from the SDK Run");await le(f.target);let a=await Dy(l.archiveDir,c.change);return await A_(n),{active:f,runInput:{change:c.change,changeDir:c.changeDir},layout:l,before:a}}async function JV(e,t,n){let r;try{r=await __(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 dS(n,i.target),l=await LI(n,e,t,ca.relative(n,o.specsDir).replaceAll("\\","/")),await aa(e,n)}catch(y){return{status:"failed",output:{archiveStarted:!1,reason:y instanceof Error?y.message:String(y)}}}let f=await go(["archive",s.change,"--yes"],n);if(f.exitCode!==0){let y=[f.stderr,f.stdout].filter(Boolean).join(`
|
|
212
|
+
`);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 V(n,s.changeDir,{label:"Classic active change",expected:"directory"}),S=[...await Dy(o.archiveDir,s.change)].some(C=>!c.has(C));if(!R.exists&&S)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 u=[...await Dy(o.archiveDir,s.change)].filter(y=>!c.has(y));if(u.length!==1)throw new Error("OpenSpec Archive did not produce one unambiguous archived change");let p=u[0],d=ca.join(o.archiveDir,p),m=await V(n,ca.relative(n,d).replaceAll("\\","/"),{label:"Classic archived change",expected:"directory"}),h=await V(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 Eo(n,m.target);if(g.length)throw new Error(g.join(`
|
|
213
|
+
`));let w=e.state,k=ca.relative(n,m.target).replaceAll("\\","/");return await I_(n,xt(w.designDoc,s.changeDir,k),p,"status: final"),await I_(n,xt(w.plan,s.changeDir,k),p,""),{status:"succeeded",artifacts:await MI(n,e,t,k,l),output:{archiveDirectory:k}}}async function P_(e,t){let n=ca.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 __(r,s,n);let o=jy(),c=jy();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(u=>u.id===s.id),a=await JV(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:jy(),...a}})}catch(l){let a=(await e.inspect(r.runId)).actions.find(u=>u.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}}import{randomUUID as Qy}from"node:crypto";Ze();import n2 from"node:path";un();un();cn();Re();import ZU from"node:path";var GV="@rpamis/comet",Kte=`https://registry.npmjs.org/${GV}/latest`;Wu();function My(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ys=My();function L_(e){Ys=e}var Js={exec:()=>null};function la(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(Jt.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,t)};return r}var YV=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Jt={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:la(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:la(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:la(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:la(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:la(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:la(e=>new RegExp(`^ {0,${e}}>`))},XV=/^(?:[ \t]*(?:\n|$))+/,QV=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ZV=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ml=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,eU=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Fy=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,W_=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,M_=ke(W_).replace(/bull/g,Fy).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(),tU=ke(W_).replace(/bull/g,Fy).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(),Hy=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,nU=/^[^\n]+/,By=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,rU=ke(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",By).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),iU=ke(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Fy).getRegex(),Gf="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",Vy=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,sU=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",Vy).replace("tag",Gf).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),F_=e=>ke(Hy).replace("hr",ml).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",Gf).getRegex(),oU=F_(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),aU=F_(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),cU=ke(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",aU).getRegex(),Uy={blockquote:cU,code:QV,def:rU,fences:ZV,heading:eU,hr:ml,html:sU,lheading:M_,list:iU,newline:XV,paragraph:oU,table:Js,text:nU},O_=ke("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ml).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",Gf).getRegex(),lU={...Uy,lheading:tU,table:O_,paragraph:ke(Hy).replace("hr",ml).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",O_).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",Gf).getRegex()},uU={...Uy,html:ke(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Vy).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:Js,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ke(Hy).replace("hr",ml).replace("heading",` *#{1,6} *[^
|
|
214
|
+
]`).replace("lheading",M_).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},dU=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,fU=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,H_=/^( {2,}|\\)\n(?!\s*$)/,pU=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Vr=/[\p{P}\p{S}]/u,ua=/[\s\p{P}\p{S}]/u,hl=/[^\s\p{P}\p{S}]/u,mU=ke(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ua).getRegex(),hU=/[\p{Pi}\p{Ps}"']/u,B_=/(?!~)[\p{P}\p{S}]/u,gU=/(?!~)[\s\p{P}\p{S}]/u,wU=/(?:[^\s\p{P}\p{S}]|~)/u,yU=ke(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",YV?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),V_=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,vU=ke(V_,"u").replace(/punct/g,Vr).getRegex(),kU=ke(V_,"u").replace(/punct/g,B_).getRegex(),bU=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,RU=ke(bU,"u").replace(/openQuote/g,hU).replace(/punct/g,Vr).getRegex(),U_="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",SU=ke(U_,"gu").replace(/notPunctSpace/g,hl).replace(/punctSpace/g,ua).replace(/punct/g,Vr).getRegex(),CU=ke(U_,"gu").replace(/notPunctSpace/g,wU).replace(/punctSpace/g,gU).replace(/punct/g,B_).getRegex(),EU="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",xU=ke(EU,"gu").replace(/notPunctSpace/g,hl).replace(/punctSpace/g,ua).replace(/punct/g,Vr).getRegex(),AU=ke("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,hl).replace(/punctSpace/g,ua).replace(/punct/g,Vr).getRegex(),IU="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",_U=ke(IU,"gu").replace(/notPunctSpace/g,hl).replace(/punctSpace/g,ua).replace(/punct/g,Vr).getRegex(),PU=ke(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Vr).getRegex(),OU="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",TU=ke(OU,"gu").replace(/notPunctSpace/g,hl).replace(/punctSpace/g,ua).replace(/punct/g,Vr).getRegex(),NU=ke(/\\(punct)/,"gu").replace(/punct/g,Vr).getRegex(),$U=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(),jU=ke(Vy).replace("(?:-->|$)","-->").getRegex(),DU=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",jU).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Kf=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,qU=ke(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Kf).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),K_=ke(/^!?\[(label)\]\[(ref)\]/).replace("label",Kf).replace("ref",By).getRegex(),z_=ke(/^!?\[(ref)\](?:\[\])?/).replace("ref",By).getRegex(),LU=ke("reflink|nolink(?!\\()","g").replace("reflink",K_).replace("nolink",z_).getRegex(),T_=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ky={_backpedal:Js,anyPunctuation:NU,autolink:$U,blockSkip:yU,br:H_,code:fU,del:Js,delLDelim:Js,delRDelim:Js,emStrongLDelim:vU,emStrongRDelimAst:SU,emStrongRDelimUnd:AU,escape:dU,link:qU,nolink:z_,punctuation:mU,reflink:K_,reflinkSearch:LU,tag:DU,text:pU,url:Js},WU={...Ky,emStrongLDelim:RU,emStrongRDelimAst:xU,emStrongRDelimUnd:_U,link:ke(/^!?\[(label)\]\((.*?)\)/).replace("label",Kf).getRegex(),reflink:ke(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Kf).getRegex()},qy={...Ky,emStrongRDelimAst:CU,emStrongLDelim:kU,delLDelim:PU,delRDelim:TU,url:ke(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",T_).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:ke(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",T_).getRegex()},MU={...qy,br:ke(H_).replace("{2,}","*").getRegex(),text:ke(qy.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Uf={normal:Uy,gfm:lU,pedantic:uU},fl={normal:Ky,gfm:qy,breaks:MU,pedantic:WU},FU={"&":"&","<":"<",">":">",'"':""","'":"'"},N_=e=>FU[e];function Ir(e,t){if(t){if(Jt.escapeTest.test(e))return e.replace(Jt.escapeReplace,N_)}else if(Jt.escapeTestNoEncode.test(e))return e.replace(Jt.escapeReplaceNoEncode,N_);return e}function $_(e){try{e=encodeURI(e).replace(Jt.percentDecode,"%")}catch{return null}return e}function j_(e,t){let n=e.replace(Jt.findPipe,(s,o,c)=>{let l=!1,f=o;for(;--f>=0&&c[f]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Jt.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(Jt.slashPipe,"|");return r}function Mi(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 D_(e){let t=e.split(`
|
|
215
|
+
`),n=t.length-1;for(;n>=0&&Jt.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
216
|
+
`)}function HU(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 BU(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 q_(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 u=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:u}}function VU(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
217
|
+
`).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(`
|
|
218
|
+
`)}var zf=class{options;rules;lexer;constructor(e){this.options=e||Ys}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]:D_(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=VU(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=Mi(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:Mi(t[0],`
|
|
219
|
+
`),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:Mi(t[0],`
|
|
220
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Mi(t[0],`
|
|
221
|
+
`).split(`
|
|
222
|
+
`),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(`
|
|
223
|
+
`),a=f.replace(this.rules.other.blockquoteSetextReplace,`
|
|
224
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
225
|
+
${f}`:f,i=i?`${i}
|
|
226
|
+
${a}`:a;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(a,s,!0),this.lexer.state.top=u,n.length===0)break;let p=s.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let d=p,m=n.join(`
|
|
227
|
+
`),h=d.raw+`
|
|
228
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),g=this.blockquote(h);s[s.length-1]=g,r=`${r}
|
|
229
|
+
${m}`,i=i.substring(0,i.length-d.text.length)+g.text;break}else if(p?.type==="list"){let d=p,m=d.raw+`
|
|
230
|
+
`+n.join(`
|
|
231
|
+
`),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-d.raw.length)+h.raw,n=m.substring(s.at(-1).raw.length).split(`
|
|
232
|
+
`);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 u=BU(t[2].split(`
|
|
233
|
+
`,1)[0],t[1].length),p=e.split(`
|
|
234
|
+
`,1)[0],d=!u.trim(),m=0;if(this.options.pedantic?(m=2,a=u.trimStart()):d?m=t[1].length+1:(m=u.search(this.rules.other.nonSpaceChar),m=m>4?1:m,a=u.slice(m),m+=t[1].length),d&&this.rules.other.blankLine.test(p)&&(f+=p+`
|
|
235
|
+
`,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 S=e.split(`
|
|
236
|
+
`,1)[0],C;if(p=S,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),C=p):C=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(C.search(this.rules.other.nonSpaceChar)>=m||!p.trim())a+=`
|
|
237
|
+
`+C.slice(m);else{if(d||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(u)||k.test(u)||g.test(u))break;a+=`
|
|
238
|
+
`+p}d=!p.trim(),f+=S+`
|
|
239
|
+
`,e=e.substring(S.length+1),u=C.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(u=>u.type==="space"),a=f.length>0&&f.some(u=>this.rules.other.anyLine.test(u.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 u=this.lexer.inlineQueue.length-1;u>=0;u--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[u].src)){this.lexer.inlineQueue[u].src=this.lexer.inlineQueue[u].src.replace(this.rules.other.listReplaceTask,"");break}let a=this.rules.other.listTaskCheckbox.exec(l.raw);if(a){let u={type:"checkbox",raw:a[0]+" ",checked:a[0]!=="[ ]"};l.checked=u.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=u.raw+l.tokens[0].raw,l.tokens[0].text=u.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(u)):l.tokens.unshift({type:"paragraph",raw:u.raw,text:u.raw,tokens:[u]}):l.tokens.unshift(u)}}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=D_(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:Mi(t[0],`
|
|
240
|
+
`),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=j_(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
241
|
+
`):[],s={type:"table",raw:Mi(t[0],`
|
|
242
|
+
`),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(j_(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:Mi(t[0],`
|
|
243
|
+
`),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)===`
|
|
244
|
+
`?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=Mi(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=HU(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)),q_(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 q_(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,u=f==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,t=t.slice(-1*e.length+i);(r=u.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,d=e.slice(0,i+r.index+p+o);if(Math.min(i,o)%2){let h=d.slice(1,-1);return{type:"em",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}let m=d.slice(2,-2);return{type:"strong",raw:d,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),u=a.slice(i,-i);return{type:"del",raw:a,text:u,tokens:this.lexer.inlineTokens(u)}}}}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}}}},Un=class Ly{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ys,this.options.tokenizer=this.options.tokenizer||new zf,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:Jt,block:Uf.normal,inline:fl.normal};this.options.pedantic?(n.block=Uf.pedantic,n.inline=fl.pedantic):this.options.gfm&&(n.block=Uf.gfm,this.options.breaks?n.inline=fl.breaks:n.inline=fl.gfm),this.tokenizer.rules=n}static get rules(){return{block:Uf,inline:fl}}static lex(t,n){return new Ly(n).lex(t)}static lexInline(t,n){return new Ly(n).inlineTokens(t)}lex(t){t=t.replace(Jt.carriageReturn,`
|
|
245
|
+
`),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(Jt.tabCharGlobal," ").replace(Jt.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+=`
|
|
246
|
+
`: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(`
|
|
247
|
+
`)?"":`
|
|
248
|
+
`)+s.raw,c.text+=`
|
|
249
|
+
`+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(`
|
|
250
|
+
`)?"":`
|
|
251
|
+
`)+s.raw,c.text+=`
|
|
252
|
+
`+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(`
|
|
253
|
+
`)?"":`
|
|
254
|
+
`)+s.raw,c.text+=`
|
|
255
|
+
`+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(`
|
|
256
|
+
`)?"":`
|
|
257
|
+
`)+s.raw,c.text+=`
|
|
258
|
+
`+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 u=f.slice(1,a-1);if(this.linkInText(u))return"["+u.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),u;this.options.extensions.startInline.forEach(p=>{u=p.call({lexer:this},a),typeof u=="number"&&u>=0&&(f=Math.min(f,u))}),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)}},Jf=class{options;parser;constructor(e){this.options=e||Ys}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(Jt.notSpaceStart)?.[0],i=e.replace(Jt.endingNewline,"")+`
|
|
259
|
+
`;return r?'<pre><code class="language-'+Ir(r)+'">'+(n?i:Ir(i,!0))+`</code></pre>
|
|
260
|
+
`:"<pre><code>"+(n?i:Ir(i,!0))+`</code></pre>
|
|
261
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
262
|
+
${this.parser.parse(e)}</blockquote>
|
|
263
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
264
|
+
`}hr(e){return`<hr>
|
|
265
|
+
`}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+`>
|
|
266
|
+
`+r+"</"+i+`>
|
|
267
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
268
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
269
|
+
`}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>
|
|
270
|
+
<thead>
|
|
271
|
+
`+t+`</thead>
|
|
272
|
+
`+r+`</table>
|
|
273
|
+
`}tablerow({text:e}){return`<tr>
|
|
274
|
+
${e}</tr>
|
|
275
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
276
|
+
`}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>${Ir(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=$_(e);if(i===null)return r;e=i;let s='<a href="'+e+'"';return t&&(s+=' title="'+Ir(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=$_(e);if(i===null)return Ir(n);e=i;let s=`<img src="${e}" alt="${Ir(n)}"`;return t&&(s+=` title="${Ir(t)}"`),s+=">",s}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ir(e.text)}},zy=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}},lr=class Wy{options;renderer;textRenderer;constructor(t){this.options=t||Ys,this.options.renderer=this.options.renderer||new Jf,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new zy}static parse(t,n){return new Wy(n).parse(t)}static parseInline(t,n){return new Wy(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}},pl=class{options;block;constructor(e){this.options=e||Ys}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?Un.lex:Un.lexInline}provideParser(e=this.block){return e?lr.parse:lr.parseInline}},UU=class{defaults=My();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=lr;Renderer=Jf;TextRenderer=zy;Lexer=Un;Tokenizer=zf;Hooks=pl;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 Jf(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 zf(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 pl;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];pl.passThroughHooks.has(s)?i[o]=f=>{if(this.defaults.async&&pl.passThroughHooksRespectAsync.has(s))return(async()=>{let u=await c.call(i,f);return l.call(i,u)})();let a=c.call(i,f);return l.call(i,a)}:i[o]=(...f)=>{if(this.defaults.async)return(async()=>{let u=await c.apply(i,f);return u===!1&&(u=await l.apply(i,f)),u})();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 Un.lex(e,t??this.defaults)}parser(e,t){return lr.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?Un.lex:Un.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?lr.parse:lr.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?Un.lex:Un.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?lr.parse:lr.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+=`
|
|
277
|
+
Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+Ir(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Gs=new UU;function Fe(e,t){return Gs.parse(e,t)}Fe.options=Fe.setOptions=function(e){return Gs.setOptions(e),Fe.defaults=Gs.defaults,L_(Fe.defaults),Fe};Fe.getDefaults=My;Fe.defaults=Ys;function KU(...e){return Gs.use(...e),Fe.defaults=Gs.defaults,L_(Fe.defaults),Fe}Fe.use=KU;Fe.walkTokens=function(e,t){return Gs.walkTokens(e,t)};Fe.parseInline=Gs.parseInline;Fe.Parser=lr;Fe.parser=lr.parse;Fe.Renderer=Jf;Fe.TextRenderer=zy;Fe.Lexer=Un;Fe.lexer=Un.lex;Fe.Tokenizer=zf;Fe.Hooks=pl;Fe.parse=Fe;var Jte=Fe.options,Gte=Fe.setOptions,zU=Fe.walkTokens,Yte=Fe.parseInline;var Xte=lr.parse,Qte=Un.lex;Re();function da(e){throw new b("INVALID_WORKFLOW",`${e};请修正适配契约或恢复已固定的依赖后继续`)}cn();Re();Re();Re();Re();function e2(e){return(typeof e!="string"||!/^[a-z][a-z\d]*(?:[.-][a-z\d]+)*$/u.test(e))&&da("应用身份必须是小写名称"),e}function t2(e,t){return ZU.join(e,"applications",e2(t))}async function G_(e,t,n){return vn({rootDir:t2(mt(e),t),mirroredRevisionPaths:["run.revision"]}).readPartitionMetadata(n)}async function Jy(e,t,n){let r=n??await Ei(e,"classic",t.runId,{readOnly:!0}),i=r&&!["classic-full","classic-hotfix","classic-tweak"].includes(r.application)?await G_(e,r.application,t.runId):await vn({rootDir:n2.join(mt(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"&&ol(l)),c=[...t.status==="cancelled"&&!Us(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}}import Xs from"node:path";Re();_n();Ot();var r2="执行当前检查 Action;Runtime 会绑定原命令、输入快照和收据,并校验后续证据。默认单次真实执行;--local 不是执行位置开关,而是允许确定性检查复用。任务要求每阶段真实执行、命令有副作用或读取外部状态时,禁止添加 --local;只有任务允许且完整输入和执行条件确定时才显式选择复用。使用 --json 时解析完整 stdout,stderr 单独保留,不合并后截断解析。",i2="交付修复检查已固定原 Verify 命令。按 data.continuation.commandArgs 执行 state next --continue,使用当前 Run 的原 Action、命令和收据继续检查;不使用 check run 或 check rerun 重新登记检查,不重放 Archive。检查成功后展示新交付范围,结束当前回复并等待用户针对本范围的实际回答。使用 --json 时解析完整 stdout,stderr 单独保留。",Gy="提交本次交付修复的 Agent 平台检查报告,保留原 Run、归档和批准的路径,不运行受管命令或重放 Archive。随后展示交付范围并取得当前提案的明确批准。";function Yy(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"?Gy:i2:r2}:{}}}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 _r(e,t,n={}){await Xn(e,t);let r=(await Qn(t,e)).directory,i=n.owner??await Ei(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=S_(s,c);if(c){let y=cy(c,l.workflow);y!==c&&(await Ds({...l,workflows:[l.workflow],transitionHandlers:[l.transitionHandler],store:{read:async()=>y,compareAndSwap:async()=>!1}}).inspect(i.runId),c=y)}let f=!0,a=Ds({store:{...o,async read(y){if(f&&y===i.runId)return f=!1,c;let R=await o.read(y);return R&&cy(R,l.workflow)}},workflows:[l.workflow],transitionHandlers:[l.transitionHandler],evidenceValidators:l.evidenceValidators,validators:l.validators,executors:l.executors,commandValidators:l.commandValidators}),u=await a.inspect(i.runId),p=u.state,d=u.input&&typeof u.input=="object"&&!Array.isArray(u.input)&&typeof u.input.changeDir=="string"?Xs.resolve(e,u.input.changeDir):null,m=d?Xs.join(Xs.dirname(d),"archive"):null,h=sl(u,s),g=h?"full":s,w=u.actions.some(y=>y.stepId===`${g}.archive.execute`&&(y.status==="running"||y.status==="unknown")),k=d!==null&&(r===d||(p?.archived===!0||w)&&Xs.dirname(r)===m&&/^\d{4}-\d{2}-\d{2}-/u.test(Xs.basename(r))&&Xs.basename(r).slice(11)===t);if(u.workflow.id!==l.workflow.id||u.workflow.version!==l.workflow.version||!u.input||typeof u.input!="object"||Array.isArray(u.input)||u.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:u,state:p,runtime:a,profile:g,owner:i}}async function Xy(e,t,n={}){let r=Xs.resolve(e),i=n.owner??await Ei(r,"classic",t,{readOnly:!0});return i?{projectRoot:r,...await _r(r,t,{...n,owner:i})}:null}async function Y_(e){let{projectRoot:t,change:n}=e,{run:r,state:i,runtime:s,profile:o}=await _r(t,n);if(i.phase!=="build")throw new Error("Classic Build completion requires an SDK change in Build");if(r.actions.some(p=>p.status==="running"||p.status==="unknown"))throw new Error("Classic SDK has a claimed Action with an unknown outcome");let c=r.actions.find(p=>p.stepId===`${o}.build.execute`&&p.status==="pending");if(!c)throw new Error("Classic SDK Run has no pending Build execution Action");let l=r.input&&typeof r.input=="object"&&!Array.isArray(r.input)&&typeof r.input.changeDir=="string"?r.input.changeDir:null;if(!l)throw new Error("Classic SDK Run has no change directory");if(await Vs(t,l,i,r),e.sessionId!==void 0&&(!e.sessionId.trim()||e.sessionId.includes("\0")))throw new Error("Classic Builder session must be a nonempty execution reference");let f=r.workflow.version==="2"?await qf(t,e.checksRef??(()=>{throw new Error("Classic Build requires --checks <checks-json-file>")})()):{},a=Qy(),u=await s.claim({runId:r.runId,expectedRevision:r.revision,actionId:c.id,attempt:c.attempt,inputHash:c.inputHash,executorId:"comet-classic-state",sessionId:e.sessionId??`classic-builder/${c.id}/${c.attempt}`,claimToken:a});return s.recordOutcome({runId:r.runId,expectedRevision:u.revision,outcome:{actionId:c.id,attempt:c.attempt,inputHash:c.inputHash,claimToken:a,outcomeId:Qy(),status:"succeeded",output:{event:"build-complete",...f}},context:{requestId:Qy(),projectRoot:t}})}import{randomUUID as gl}from"node:crypto";import Yf from"node:path";Ze();async function s2(e){let{projectRoot:t,change:n,run:r,state:i}=e,s=r.input,o=r.outputs["full.design.handoff"]?.value,c=!!(o?.sourceEvidence&&o.requirementsEvidence),l=c?e.allowDesignDocumentChanges?o.requirementsEvidence:o.sourceEvidence:r.outputs["full.open.evidence"]?.value,f=await Ar(t,s.changeDir,{designRequirements:c&&e.allowDesignDocumentChanges===!0});if(!l||l.ref!==f.ref)throw new Error(`Classic Design OpenSpec artifacts changed after the approved proposal; run comet state revise-design ${n} --expected-revision ${r.revision}, then propose and approve the revised design`);if(!i.handoffContext||!await Oo({run:r,projectRoot:t,changeDir:Yf.join(t,s.changeDir),change:n,contextCompression:i.contextCompression,handoffContext:i.handoffContext,handoffHash:i.handoffHash,allowDesignDocumentChanges:c&&e.allowDesignDocumentChanges===!0}))throw new Error(`Classic Design handoff changed after the approved proposal; run comet state revise-design ${n} --expected-revision ${r.revision}, then propose and approve the revised design`)}async function o2(e){let{projectRoot:t,change:n,designDoc:r}=e,i=e.inspected??await _r(t,n),{run:s,state:o,profile:c}=i;if(c!=="full"||!["design","build"].includes(o.phase))throw new Error("Classic Design completion requires a full SDK change in Design");if(o.designDoc&&o.designDoc!==r)throw new Error("Classic Design must preserve its registered document");let l=dn({isolation:o.isolation,boundBranch:o.boundBranch,currentBranch:rt(t),gitWorkTree:Qt(t)});if(l.status!=="ok"&&l.status!=="not-applicable")throw new Error(`Classic SDK branch binding is ${l.status}`);if(s.actions.some(d=>d.status==="running"||d.status==="unknown"))throw new Error("Classic SDK has a claimed Action with an unknown outcome");let f=s.waits.slice().reverse().find(d=>d.stepId==="full.design.confirm");if(!f)throw new Error("Classic Design has no pending proposal");if(f.status==="resolved"&&f.decision?.choice!=="approved")throw new Error("Classic Design proposal was not approved");let a=s.input;await s2({projectRoot:t,change:n,run:s,state:o,allowDesignDocumentChanges:Yf.resolve(t,r)===Yf.resolve(t,a.changeDir,"design.md")});let u=await hd(t,Yf.join(t,a.changeDir),{...o,designDoc:r});if(u.design!=="ready")throw new Error(u.issues.map(d=>d.message).join(`
|
|
278
|
+
`)||"Classic Design document is not ready");if(o.language!=="en"&&o.language!=="zh-CN")throw new Error("Classic change language is not set");let p=await vy(t,r);return{...i,decision:f,receipt:p}}async function X_(e){let t=await o2(e),n=e.apply&&t.state.phase==="design"&&e.approvalHash===t.decision.proposalHash?await a2(t,{projectRoot:e.projectRoot,designDoc:e.designDoc,approvalHash:e.approvalHash}):null;return{inspected:t,completed:n}}async function a2(e,t){let{projectRoot:n,designDoc:r,approvalHash:i}=t,{run:s}=e,{runtime:o,decision:c,receipt:l}=e;if(c.proposalHash!==i)throw new Error("Classic Design approval does not match the pending proposal");c.status==="pending"&&(s=await o.resolveWait({runId:s.runId,expectedRevision:s.revision,waitId:c.id,proposalHash:i,decisionId:`classic-design-${i}`,choice:"approved"}));let f=s.actions.find(u=>u.stepId==="full.design.document"&&u.status==="pending");if(f){let u=gl();s=await o.claim({runId:s.runId,expectedRevision:s.revision,actionId:f.id,attempt:f.attempt,inputHash:f.inputHash,executorId:"comet-classic-state",claimToken:u}),s=await o.recordOutcome({runId:s.runId,expectedRevision:s.revision,outcome:{actionId:f.id,attempt:f.attempt,inputHash:f.inputHash,claimToken:u,outcomeId:gl(),status:"succeeded",output:{designDoc:r}},context:{requestId:gl(),projectRoot:n}})}let a=s.evidenceWaits?.find(u=>u.stepId==="full.design.evidence"&&u.status==="pending");if(a&&(s=await o.recordEvidence({runId:s.runId,expectedRevision:s.revision,evidenceId:a.id,kind:a.kind,ref:l.ref,contentHash:ia(s,"full.design.document"),submissionId:gl(),context:{requestId:gl(),projectRoot:n}})),s.state?.phase!=="build")throw new Error("Classic Design remains pending in the SDK Run");return s}_n();import Q_ from"node:path";async function Z_(e,t){let n=t.actions.find(o=>["running","unknown"].includes(o.status));if(!n)return null;if(lc(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:Q_.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:Q_.resolve(e)}}}:{},retryRequestTemplate:{operation:"retry",...i,actionId:n.id,attempt:n.attempt,reconciliation:{resolution:"not-executed",evidence:{summary:"<只有证实原任务从未执行时才能填写>"}}}}}function eP(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 fa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function c2(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=fa(t.input),o=cr(e,t)?.outputs??(s?fa(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=fa(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 u=e.actionContexts[t.id]?.results??{},p=r.startsWith("build.")?e.actions.filter(m=>{let h=u[m.stepId],g=fa(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 d=r.startsWith("build.")?(e.evidenceWaits??[]).find(m=>m.status==="invalidated"&&u[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}:{},...d?.invalidation?{invalidatedEvidence:d.invalidation}:{}}}}function l2(e,t,n,r={}){let i=Yy(e),s=e.state,o=eP(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 S=e.actions.find(C=>C.id===R.id);return e.actionContexts[R.id]?.results[y.stepId]?.sequence===y.sequence||cr(e,S)?.approvalWaitIds.includes(y.id)})),a={actions:o.actions.map(y=>({...y,...y.type==="invoke_skill"?{contextRequest:mc(s,t,y.claim?.sessionId,e.runId)}:{},...c2(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:S,proposalHash:C,choices:q,decision:T})=>({id:y,stepId:R,proposal:S,proposalHash:C,choices:q,decision:T}))},u={...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:mc(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{...u,...y,current:a}}let d=(y,...R)=>["comet","state",y,n,...R,"--json"];if(Py(e))return p({mode:"execute",commandArgs:d("continue-build","--expected-revision",String(e.revision)),requiredInputs:[],instruction:"原 Builder 已回报失败并结束。保留部分实现、已完成任务和配置,继续原 Run;只完成缺失工作,不重放已经完成的副作用。"});if(_y(e))return p({mode:"execute",commandArgs:d("continue-work","--expected-revision",String(e.revision)),requiredInputs:[],instruction:"原 Skill 已回报真实失败。保留原执行、已确认阶段和部分产物,在同一 Run 创建后续工作,只补缺失步骤,不重放已完成副作用。"});if(Oy(e))return p({mode:"execute",commandArgs:d("repair-archive","--expected-revision",String(e.revision)),requiredInputs:[],instruction:"归档进程已失败。此命令先核对原输入和规格均未变化、没有归档目录,再重开 Open 修正输入;保留原失败记录并重新确认需求、验收和交付。核对失败时保留现场并恢复原执行。"});if(e.status==="cancelled"&&!Us(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"&&Af(e))return p({mode:"execute",commandArgs:d("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&&lc(m))return p({mode:"reconcile",commandArgs:d("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`?d("check","archive","--recover"):d("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"]:d("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(S=>S.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?d(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:d("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:d("next","--continue"),requiredInputs:[],instruction:"由原 Open 执行器重新校验已批准的产物;授权或来源变化仍由 Runtime 拒绝。"}):m.ref==="classic-check"&&m.stepId.endsWith(".delivery.check")?p({mode:"execute",commandArgs:d("next","--continue"),requiredInputs:[],instruction:Gy}):["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=d("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=d("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=d("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=d("submit-plan","--plan","<plan-ref>"),w=["plan-ref: 引用当前 Design Doc 和 task IDs 的真实计划"],k="先完成当前计划;仅用户明确要求计划完成后暂停时添加 --pause。";else if(m.stepId.endsWith(".build.execute"))g=d("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=d("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=d("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&&u.automatic?"execute":"wait",...h&&!u.automatic?{waitReason:"manual-transition"}:{},commandArgs:null,requiredInputs:w,...h?{skill:h}:{},...g?{completion:{commandArgs:g,requiredInputs:w,instruction:`仅在当前 Skill 的真实工作完成且满足所列前提后提交。${k}`}}:{},instruction:h?`${u.automatic?"加载":"等待用户手动加载"} ${h},仅完成 ${m.stepId} 的当前工作,并沿用本次 Run 与工作区。${u.automatic?"":"用户已明确调用本 Skill 时,执行当前工作;仅停止自动加载后续 Skill。"}${k}`:"此 Action 需要应用声明的宿主执行器;不要把工具或子流程引用当作 Skill。"})}function u2(e){let t=e.state.workflow,n=fa(e.outputs[`${t}.archive.preflight`]?.value);if(!n)return{delivery:null,verification:{status:"needsAuthorization"}};let r=fa(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 tP(e,t,n=!1,r={}){let{run:i,projectRoot:s}=t,o=i.state,c=l2(i,s,e,r),l=Yy(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"?u2(i):null,projectRoot:s,workspace:{projectRoot:s},run:eP(i,n)};try{let{directory:a}=await Qn(e,s),u=await Vf(s,i,r),p=!["completed","cancelled"].includes(i.status)&&ps(o.isolation)?rt(s):null;(["completed","cancelled"].includes(i.status)?null:dn({isolation:o.isolation,boundBranch:o.boundBranch,currentBranch:p,gitWorkTree:ps(o.isolation)&&o.boundBranch===null&&p===null?Qt(s):!0}))?.status==="drift"&&u.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 Rd(s,a,o,n,null,{editReview:!1}),g=i.actions.some(w=>w.status==="unknown")?await Z_(s,i):null;return{...f,diagnostics:await Jy(s,i,t.owner).then(w=>u.length?{...w,healthy:!1,issues:[...w.issues,...u]}:w),...u.length?{issues:u,recoveryActions:u.map(w=>({commandArgs:w.commandArgs})),...m?{}:{continuation:{...f.continuation,mode:"reconcile",commandArgs:u[0].commandArgs[0]==="comet"?[...u[0].commandArgs,"--json"].filter((w,k,y)=>w!=="--json"||k===y.indexOf("--json")):u[0].commandArgs,requiredInputs:[],instruction:`${u[0].message};${u[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 Qs(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 nP(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}。先修复或核对所列问题;不要重复原失败命令,也不要重放已领取的工作。`}}async function be(e,t,n,r,i,s,o,c){let l=i!==void 0,f=c??(s?await tP(e,{run:s,projectRoot:n},!1,!l&&t==="open"&&r?{openApprovalHash:r}:{}):null),a=l&&s?(await Vf(n,s)).find(u=>u.commandArgs[2]==="reopen-verification"):void 0;return!a&&l&&s&&t==="archive"&&zs(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:nP(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?[kr(i)]:[]},stderr:l?`BLOCKED — ${i}
|
|
279
|
+
`:`ALL CHECKS PASSED — ${t==="open"?"approval required before applying":`phase=${t}`}
|
|
280
|
+
`}}function rP(e){let t=e.input;if(!t||typeof t!="object"||Array.isArray(t)||typeof t.changeDir!="string")throw new Error("Classic SDK Run has no change directory");return t.changeDir}async function iP(e){let{projectRoot:t,change:n,apply:r,approvalHash:i}=e,s=e.inspected??await _r(t,n),{run:o}=s,{state:c,runtime:l,profile:f}=s,a=Qs(s.run,"open");if(c.phase!=="open")return be(n,c.phase,t,null,`Classic SDK change is in ${c.phase}, not open`,o,a);let u=rt(t),p=dn({isolation:c.isolation,boundBranch:c.boundBranch,currentBranch:u,gitWorkTree:Qt(t)});if(p.status!=="ok"&&p.status!=="not-applicable")return be(n,"open",t,null,`Classic SDK branch binding is ${p.status}`,o,a);if(o.actions.some(C=>C.status==="running"||C.status==="unknown"))return be(n,"open",t,null,o.actions.some(C=>C.status==="unknown")?"Classic SDK has an unknown Action outcome; reconcile the original attempt":"Classic SDK has a running Action; wait for its original executor",o,a);let d=rP(o),m=await Ar(t,d),h=ia(o,f+".open"),g=await xf(t,d,c.language);if(g)return be(n,"open",t,null,g,o,a);if(!r)return be(n,"open",t,h,void 0,o,a);if(!i||!/^[a-f0-9]{64}$/u.test(i))return be(n,"open",t,h,"The current Open request identity is required",o,a);if(i!==h)return be(n,"open",t,h,"Classic Open approval belongs to another request",o,a);let w={requestId:Fi(),projectRoot:t},k=`${f}.open`,y=o.actions.find(C=>C.stepId===k&&C.status==="pending");if(y){let C=Fi();o=await l.claim({runId:o.runId,expectedRevision:o.revision,actionId:y.id,attempt:y.attempt,inputHash:y.inputHash,executorId:"comet-classic-guard",claimToken:C}),o=await l.recordOutcome({runId:o.runId,expectedRevision:o.revision,outcome:{actionId:y.id,attempt:y.attempt,inputHash:y.inputHash,claimToken:C,outcomeId:Fi(),status:"succeeded",output:{event:"open-complete",...f==="full"?{}:{requirementsEvidence:await Ar(t,d,{presetRequirements:!0})}}},context:w})}let R=o.evidenceWaits?.find(C=>C.kind==="classic-open-artifacts"&&C.status==="pending");if(R&&(o=await l.recordEvidence({runId:o.runId,expectedRevision:o.revision,evidenceId:R.id,kind:R.kind,ref:m.ref,contentHash:h,submissionId:Fi(),context:w})),f==="full"){let C=o.waits.find(T=>T.stepId==="full.open.confirm"&&T.status==="pending");if(C){let T=C.proposal&&typeof C.proposal=="object"&&!Array.isArray(C.proposal)&&"outputs"in C.proposal&&C.proposal.outputs&&typeof C.proposal.outputs=="object"&&!Array.isArray(C.proposal.outputs)?C.proposal.outputs["full.open.evidence"]:null;if(!T||typeof T!="object"||Array.isArray(T)||T.ref!==m.ref||T.contentHash!==i)return be(n,"open",t,h,"The pending Open decision does not match approved artifacts",o,a);o=await l.resolveWait({runId:o.runId,expectedRevision:o.revision,waitId:C.id,proposalHash:C.proposalHash,decisionId:`classic-open-${i}`,choice:"approved"})}let q=o.actions.find(T=>T.stepId==="full.open.revalidate"&&T.status==="pending");q&&(o=await l.execute({runId:o.runId,expectedRevision:o.revision,actionId:q.id,executorId:"comet-classic-open-revalidate",context:w}))}let S=o.state;return S?.phase==="open"?be(n,"open",t,h,"Classic Open remains pending in the SDK Run",o,a):be(n,String(S?.phase??"unknown"),t,h,void 0,o,a)}async function sP(e){let{projectRoot:t,change:n,designDoc:r,apply:i,approvalHash:s}=e,{inspected:o,completed:c}=await X_({inspected:e.inspected,projectRoot:t,change:n,designDoc:r,apply:i,approvalHash:s}),l=Qs(o.run,"design");if(o.state.phase!=="design")return be(n,o.state.phase,t,o.decision.proposalHash,"Classic SDK Design has already advanced",o.run,l);if(!i)return be(n,"design",t,o.decision.proposalHash,void 0,o.run,l);if(!s||s!==o.decision.proposalHash)return be(n,"design",t,o.decision.proposalHash,"Classic Design approval does not match the pending proposal",o.run,l);let f=c;return be(n,String(f.state?.phase??"unknown"),t,s,void 0,f,l)}async function oP(e){let{projectRoot:t,change:n,apply:r,argv:i}=e,s=e.inspected??await _r(t,n),{run:o,state:c,profile:l}=s,f=Qs(s.run,"build");if(c.phase!=="build")return be(n,c.phase,t,null,`Classic SDK Build Guard requires Build; current phase is ${c.phase}`,o,f);if(o.actions.some(m=>m.status==="running"||m.status==="unknown"))return be(n,"build",t,null,o.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",o,f);let a=o.input;if(typeof a?.changeDir!="string")return be(n,"build",t,null,"Classic SDK Run has no change directory",o,f);try{await Vs(t,a.changeDir,c,o)}catch(m){return be(n,"build",t,null,m instanceof Error?m.message:String(m),o,f)}let u=o.actions.some(m=>m.stepId===`${l}.build.execute`&&m.status==="pending"),p=o.actions.some(m=>m.stepId===`${l}.build.check`&&m.status==="pending"),d=o.evidenceWaits?.some(m=>m.stepId===`${l}.build.check.evidence`&&m.status==="pending");if(!u&&!p&&!d)return be(n,"build",t,null,"Classic SDK has no pending Build Action",o,f);if(!r)return be(n,"build",t,null,void 0,o,f);{if(i?.length)throw new Error("Run checks with platform tools and submit --checks; Runtime does not repeat them");let m=await Y_({projectRoot:t,change:n,sessionId:e.sessionId,checksRef:e.checksRef});return be(n,m.state.phase,t,null,void 0,m,f)}}async function aP(e){let{projectRoot:t,change:n,reportRef:r,apply:i,argv:s}=e,o=e.inspected??await _r(t,n),{run:c}=o,{state:l,runtime:f,profile:a}=o,u=Qs(o.run,"verify");if(l.phase!=="verify")return be(n,l.phase,t,null,`Classic SDK Verify Guard requires Verify; current phase is ${l.phase}`,c,u);if(c.actions.some(C=>C.status==="running"||C.status==="unknown"))return be(n,"verify",t,null,c.actions.some(C=>C.status==="unknown")?"Classic SDK has an unknown Action outcome; reconcile the original attempt":"Classic SDK has a running Action; wait for its original executor",c,u);let p;try{await Vs(t,rP(c),l,c),p=await ra(t,r,l.language)}catch(C){return be(n,"verify",t,null,C instanceof Error?C.message:String(C),c,u)}let d=`${a}.verify.run`,m=c.actions.slice().reverse().find(C=>C.stepId===d),h=m?.status==="pending"?m:void 0;if(!h&&l.verificationReport&&l.verificationReport!==p.ref)return be(n,"verify",t,null,"Classic SDK Verify report does not match the current Run",c,u);let g=c.evidenceWaits?.find(C=>C.stepId===`${a}.verify.report.evidence`&&C.status==="pending"),w=c.actions.find(C=>C.stepId===`${a}.verify.check`&&C.status==="pending"),k=c.evidenceWaits?.find(C=>C.stepId===`${a}.verify.check.evidence`&&C.status==="pending");if(!h&&!g&&!w&&!k)return be(n,"verify",t,null,"Classic SDK has no pending Verify Action",c,u);if(!i)return be(n,"verify",t,null,void 0,c,u);let y=h?await qf(t,e.checksRef??(()=>{throw new Error("Classic Verify requires --checks <checks-json-file>")})()):{};if(s?.length)throw new Error("Run checks with platform tools and submit --checks; Runtime does not repeat them");let R={requestId:Fi(),projectRoot:t};if(h){let C=Fi();c=await f.claim({runId:c.runId,expectedRevision:c.revision,actionId:h.id,attempt:h.attempt,inputHash:h.inputHash,executorId:"comet-classic-guard",claimToken:C}),c=await f.recordOutcome({runId:c.runId,expectedRevision:c.revision,outcome:{actionId:h.id,attempt:h.attempt,inputHash:h.inputHash,claimToken:C,outcomeId:Fi(),status:"succeeded",output:{event:"verification-ready",verificationReport:p.ref,...y}},context:R})}let S=c.evidenceWaits?.find(C=>C.stepId===`${a}.verify.report.evidence`&&C.status==="pending");return S&&(c=await f.recordEvidence({runId:c.runId,expectedRevision:c.revision,evidenceId:S.id,kind:S.kind,ref:p.ref,contentHash:ia(c,a+".verify.run"),submissionId:Fi(),context:R})),be(n,c.state.phase,t,null,void 0,c,u)}async function cP(e){let{projectRoot:t,change:n,apply:r}=e,i=e.inspected??await _r(t,n),{run:s,state:o,runtime:c,profile:l}=i,f=Qs(i.run,"archive");if(o.phase!=="archive")return be(n,o.phase,t,null,`Classic SDK Archive Guard requires Archive; current phase is ${o.phase}`,s,f);if(o.archived)return be(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 be(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 aa(s,t)}catch(m){return be(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"),u=s.actions.some(m=>m.stepId===`${l}.archive.execute`&&m.status==="pending");if(!a&&!u)return be(n,"archive",t,null,"Classic SDK has no pending Archive Action",s,f);if(!r)return be(n,"archive",t,null,void 0,s,f);let p;try{if(a){let m=await x_(c,{runId:s.runId,projectRoot:t});Object.assign(f,Qs(m,"archive",f))}p=await P_(c,{runId:s.runId,projectRoot:t})}catch(m){if(!(m instanceof dl))throw m;let h=await c.inspect(s.runId);return be(n,"archive",t,null,m.message,h,f)}return p.state?.archived===!0?be(n,"archive",t,null,void 0,p,f):be(n,"archive",t,null,"Classic SDK Archive did not complete",p,f)}Hu();import d2 from"path";var f2=d2.join(".comet","state-events.jsonl"),p2=Number.MAX_SAFE_INTEGER;async function lP(e,t){let n={schemaVersion:1,timestamp:new Date().toISOString(),...t};return await Mu(e,f2,`${JSON.stringify(n)}
|
|
281
|
+
`,p2,"Classic state event log"),n}Ot();Ot();Tt();var vl=St(_t(),1);_n();Ze();Tt();vo();import Xf from"path";var m2="\x1B[32m",wl="\x1B[31m",h2="\x1B[33m",g2="\x1B[0m",w2=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],y2={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct","autonomous"],build_pause:["plan-ready"],subagent_dispatch:["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"]},v2=new Set([...mr,...ls,"classic_profile","classic_migration"]);function Zs(e,t){return`${e}${t}${g2}`}function yl(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}var uP=yo(async e=>{if(e.length!==1)return{exitCode:64,stderr:"Usage: comet classic validate <change-name>"};let t=e[0],n=us(t);if(n)return{exitCode:1,stderr:Zs(wl,`ERROR: ${n}`)};let r=De(),{directory:i,label:s}=await Qn(t,r),o=await le(i),c=[`[VALIDATE] ${s}/${Xf.basename(o)}`],l=0,f=0,a=h=>{l+=1,c.push(Zs(wl,` FAIL: ${h}`))},u=h=>{f+=1,c.push(Zs(h2,` WARN: ${h}`))},p;try{p=await oe(r,o,{label:`Classic state ${s}/${Xf.basename(o)}`})}catch(h){if(h.code==="ENOENT")return a(`${Xf.basename(o)} does not exist`),c.push("",Zs(wl,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(`
|
|
282
|
+
`)};throw h}let d=(0,vl.parseDocument)(p);if(d.errors.length>0||!(0,vl.isMap)(d.contents)){for(let h of d.errors)a(h.message);return(0,vl.isMap)(d.contents)||a("document root must be a mapping"),c.push("",Zs(wl,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(`
|
|
283
|
+
`)}}let m=d.toJS();for(let h of w2)Object.prototype.hasOwnProperty.call(m,h)||a(`missing required field '${h}'`);for(let[h,g]of Object.entries(y2)){if(!Object.prototype.hasOwnProperty.call(m,h))continue;let w=yl(m[h]);if(!w){h==="auto_transition"&&a(`${h}='' is not valid. Expected: ${g.join(" ")}`);continue}g.includes(w)||a(`${h}='${w}' is not valid. Expected: ${g.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(m,"bound_branch")){let h=m.bound_branch;h!==null&&typeof h!="string"&&a(`bound_branch='${yl(h)}' is not a string or null`)}m.change_id!==void 0&&(typeof m.change_id!="string"||!ec.test(m.change_id))&&a("change_id must be an immutable UUID");for(let h of["verify_failures","check_epoch"]){if(!Object.prototype.hasOwnProperty.call(m,h))continue;let g=m[h];(typeof g!="number"||!Number.isSafeInteger(g)||g<0)&&a(`${h}='${yl(g)}' is not a non-negative safe integer`)}for(let h of["design_doc","plan","handoff_context","verification_report"]){let g=yl(m[h]);if(g){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(g)||g.split(/[\\/]/u).includes("..")){a(`${h}='${g}' must be a relative repository path`);continue}try{await lt(r,Xf.resolve(r,g),{label:`${h} artifact pointer`,expected:"file"})||a(`${h}='${g}' does not exist on disk`)}catch(w){a(`${h}='${g}' is unsafe: ${w instanceof Error?w.message:String(w)}`)}}}for(let h of["handoff_hash"]){let g=yl(m[h]);g&&!/^[a-f0-9]{64}$/u.test(g)&&a(`${h}='${g}' is not a sha256 hex digest`)}for(let h of Object.keys(m))v2.has(h)||u(`unknown field '${h}' found; guard treats unknown fields as fatal — remove the field or realign it with this Comet version before advancing the phase`);return c.push(""),l>0?(c.push(Zs(wl,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(`
|
|
284
|
+
`)}):(c.push(Zs(m2,`0 errors, ${f} warning(s) — validation PASSED`)),{exitCode:0,stderr:c.join(`
|
|
285
|
+
`)})});var k2="\x1B[32m",b2="\x1B[31m",R2="\x1B[33m",ev="\x1B[0m",S2=["open","design","build","verify","archive"],C2={open:"=== Guard: open → next ===",design:"=== Guard: design → build ===",build:"=== Guard: build → verify ===",verify:"=== Guard: verify → archive ===",archive:"=== Guard: archive completeness ==="},E2={open:" [APPLY] .comet.yaml updated: phase=PLACEHOLDER",design:" [APPLY] .comet.yaml updated: phase=build",build:" [APPLY] .comet.yaml updated: phase=verify, verify_result=pending",verify:" [APPLY] .comet.yaml updated: phase=archive, verify_result=pass"},x2={branchStatus:"branch_status",checkEpoch:"check_epoch",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",verifyResult:"verify_result"};function Hi(e){return`${k2}${e}${ev}`}function Ur(e){return`${b2}${e}${ev}`}function A2(e){return`${R2}${e}${ev}`}function I2(e){return x2[e]??String(e)}function _2(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}var He=class extends Error{constructor(n,r=1){super(n);this.exitCode=r}exitCode},Zy=class{stderr=[];diagnostics;envelope;checksPassed=0;checksFailed=0;issues=[];data;toResult(t=0){return{exitCode:t,data:{...this.data,checks:{passed:this.checksPassed,total:this.checksPassed+this.checksFailed,blocked:t!==0},issues:this.issues,...this.diagnostics?{diagnostics:this.diagnostics}:{}},...this.diagnostics?{stdout:JSON.stringify({diagnostics:this.diagnostics})+`
|
|
286
|
+
`}:{},...this.stderr.length>0?{stderr:this.stderr.join(`
|
|
287
|
+
`)+`
|
|
288
|
+
`}:{},...this.envelope===void 0?{}:{envelope:this.envelope}}}};async function zr(e){let t=De();return lt(t,e,{label:`Classic guard path ${Rt.relative(t,Rt.resolve(t,e)).replaceAll("\\","/")}`})}async function Kr(e){let t=De();return Yn(t,e,`Classic guard file ${Rt.relative(t,Rt.resolve(t,e)).replaceAll("\\","/")}`)}function P2(e){let t=us(e);if(t)throw new He(Ur(`ERROR: ${t}`))}async function O2(e){return(await Qn(e,De())).directory}async function ft(e,t){let n=await le(e),r=(0,dP.parseDocument)(await oe(De(),n,{label:`Classic state ${e}/.comet.yaml`}),{uniqueKeys:!1});if(r.errors.length>0)throw new He(`ERROR: Invalid .comet.yaml: ${r.errors[0].message}`);let s=r.toJS()[t];return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)}async function T2(e,t){if(!await zr(e))throw new He(Ur(`FATAL: change directory not found: ${e}`));if(!await zr(await le(e)))throw new He(Ur(`FATAL: .comet.yaml not found in ${e}`));await $r(De(),Rt.join(e,".comet"),{label:`Classic runtime directory for ${t}`,expected:"directory"});let n=await uP([t],{json:!1});if(n.exitCode!==0)throw n.stderr&&process.stderr.write(n.stderr.endsWith(`
|
|
289
|
+
`)?n.stderr:`${n.stderr}
|
|
290
|
+
`),new He(Ur("FATAL: .comet.yaml schema validation failed"));let r=await Wt(e),i=Array.from(new Set(r.unknownKeys)).sort();if(i.length>0)throw new He(Ur(`FATAL: .comet.yaml has unknown field(s): ${i.join(", ")}. Remove them (or realign them with this Comet version, e.g. after a version rollback), then rerun comet classic validate`))}function N2(e,t){if(t.passed){if(e.checksPassed+=1,e.stderr.push(Hi(` [PASS] ${t.description}`)),t.detail)for(let n of t.detail.split(`
|
|
291
|
+
`))e.stderr.push(Hi(` ${n}`))}else if(e.checksFailed+=1,e.issues.push(kr(t.detail||t.description,{code:"CLASSIC_GUARD_CHECK_FAILED",path:`checks.${t.description}`,expected:"pass",actual:"fail",remediation:"Repair this prerequisite using the reported detail, then retry the same guard. Preserve valid artifacts and evidence."})),e.stderr.push(Ur(` [FAIL] ${t.description}`)),t.detail)for(let n of t.detail.split(`
|
|
292
|
+
`))e.stderr.push(Ur(` ${n}`))}function Ie(e,t){return async()=>{try{let n=await t();return{description:e,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:e,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function ve(e){return{passed:!0,...e?{detail:e}:{}}}function Se(e){return{passed:!1,detail:e}}async function Bi(e,t){let n=!1;for(let r of t){let i=await r();N2(e,i),i.passed||(n=!0)}return n}function $2(e){return`Evidence: recorded command-check at ${e.timestamp}; command: ${e.command}; cwd: ${e.cwd}`}async function fP(e,t,n,r){let i=await Ah(De(),e,n,r);return i.record?{status:0,output:$2(i.record)}:{status:1,output:i.reason??"请在 Agent 平台执行本阶段检查,再使用 state record-check 提交真实退出码。"}}async function tv(e){let t=Rt.join(e,"tasks.md");if(!await zr(t))return Se(`tasks.md is missing at ${t}
|
|
293
|
+
Next: restore or create tasks.md for this change before leaving build.`);let n=await oe(De(),t,{label:`Classic tasks ${t}`}),r=Mt(n);if(!r.some(s=>s.completed))return Se(`tasks.md has no completed tasks.
|
|
294
|
+
Next: complete implementation tasks and mark them with '- [x]'.`);let i=r.filter(s=>!s.completed);return i.length>0?Se(`Unfinished tasks:
|
|
295
|
+
${i.map(s=>`${s.line}:${s.text}`).join(`
|
|
296
|
+
`)}
|
|
297
|
+
Next: complete or explicitly remove unfinished tasks, then mark tasks.md with '- [x]'.`):ve()}async function j2(e){let t=Rt.join(e,"tasks.md");return await zr(t)?Mt(await oe(De(),t,{label:`Classic tasks ${t}`})).length>0:!1}async function D2(e){let t=await ft(e,"plan");if(!t||t==="null")return ve();if(!await zr(t))return Se(`plan file is missing at ${t}
|
|
298
|
+
Next: restore the implementation plan or update .comet.yaml plan before leaving build.`);let n=await oe(De(),t,{label:`Classic plan ${t}`}),r=Rt.join(e,"tasks.md"),i=Mt(await oe(De(),r,{label:"Classic plan task authority"})),s=Rt.relative(De(),r).replaceAll("\\","/");if(US(n,s,i)==="canonical")return ve();let{unmapped:o}=od(n,i);return o.length>0?Se(`Unmapped implementation plan tasks:
|
|
299
|
+
${o.map(c=>`${c.line}:${c.text}`).join(`
|
|
300
|
+
`)}
|
|
301
|
+
Next: reconcile these items against implementation and acceptance, map them to tasks.md IDs or add genuinely extra tasks. Checkbox state alone is not evidence of completion.`):ve()}async function nv(e,t){let n;try{n=await CS(e,{heal:!0,cwd:ju()})}catch(r){throw new He(`ERROR: ${r instanceof Error?r.message:String(r)}`)}switch(n.status){case"drift":return Se(ES(t,n.boundBranch,n.currentBranch));case"unbound-detached":return Se(xS(t));case"healed":return ve(`bound_branch lazily set to ${n.branch}`);case"needs-heal":case"ok":case"not-applicable":return ve();default:{let r=n;throw new Error(`unhandled branch binding status: ${JSON.stringify(r)}`)}}}async function q2(e,t){let n=await ft(e,"isolation");return n==="current"||n==="branch"||n==="worktree"?ve():Se(`isolation must be current, branch, or worktree, got '${n||"null"}'
|
|
302
|
+
Next: choose a valid workspace mode, prepare it when needed, then run:
|
|
303
|
+
comet state set ${t} isolation <current|branch|worktree>`)}async function L2(e,t){let n=await ft(e,"build_mode");return["subagent-driven-development","executing-plans","direct","autonomous"].includes(n)?ve():Se(`build_mode must be selected before leaving build, got '${n||"null"}'
|
|
304
|
+
Next: ask the user to choose an execution mode, then run:
|
|
305
|
+
comet state set ${t} build_mode <subagent-driven-development|executing-plans|autonomous>`)}async function W2(e){let t=await ft(e,"workflow"),n=await ft(e,"build_mode"),r=await ft(e,"direct_override");return n!=="direct"||t==="hotfix"||t==="tweak"||r==="true"?ve():Se(`build_mode=direct is only allowed for hotfix/tweak unless direct_override: true is recorded
|
|
306
|
+
Next: choose executing-plans or subagent-driven-development, or stop and ask the user for an explicit direct override.`)}async function M2(e,t){let n=await ft(e,"build_mode"),r=await ft(e,"subagent_dispatch");return n!=="subagent-driven-development"||r==="confirmed"?ve():Se(`subagent_dispatch must be confirmed after the user selects subagent-driven-development
|
|
307
|
+
Next: resume /comet-build and use the single joint decision to confirm the supported execution configuration for ${t}`)}async function F2(e,t){let n=await ft(e,"workflow");if(n==="hotfix"||n==="tweak")return ve();let r=await ft(e,"tdd_mode");return r==="tdd"||r==="direct"?ve():Se(`tdd_mode must be tdd or direct for full workflow, got '${r||"null"}'
|
|
308
|
+
Next: ask the user to choose TDD enforcement level, then run:
|
|
309
|
+
comet state set ${t} tdd_mode <tdd|direct>`)}async function H2(e,t){let n=await ft(e,"workflow");if(n==="hotfix"||n==="tweak")return ve();let r=await ft(e,"review_mode");return r==="off"||r==="standard"||r==="thorough"?ve():Se(`review_mode must be off, standard, or thorough before leaving build, got '${r||"null"}'
|
|
310
|
+
Next: ask the user to choose review strength, then run:
|
|
311
|
+
comet state set ${t} review_mode <off|standard|thorough>`)}async function B2(e){let t=await ft(e,"verification_report");return!!t&&t!=="null"&&await zr(t)}async function V2(e){return await ft(e,"branch_status")==="handled"}async function U2(e){return await ft(e,"archived")==="true"}async function K2(e,t){let n=await ft(e,"design_doc");return n&&n!=="null"&&await zr(n)?ve():Se(`design_doc must point to an existing Superpowers Design Doc for full workflow before leaving design.
|
|
312
|
+
Next: create the Design Doc and run: comet state set ${t} design_doc <path>`)}async function z2(e,t){let n=await ft(e,"handoff_context");return!n||n==="null"?Se("Design proposal has no source reference"):await Oo({projectRoot:De(),changeDir:e,change:t,contextCompression:await ft(e,"context_compression")==="beta"?"beta":"off",handoffContext:n})?ve():Se("Design context must reference the selected change sources")}async function J2(e,t){let n=await ft(t,"workflow"),r=await pi(De(),t),i=[Ie("OpenSpec required dependency closure is ready",async()=>r.problems.length?Se(r.problems.join(`
|
|
313
|
+
`)):ve()),Ie("proposal.md exists and non-empty",async()=>await Kr(Rt.join(t,"proposal.md"))?ve():Se("")),Ie("tasks.md exists and non-empty",async()=>await Kr(Rt.join(t,"tasks.md"))?ve():Se("")),Ie("tasks.md has at least one task",async()=>await j2(t)?ve():Se(""))];return n==="full"&&(r.designRequired||await zr(Rt.join(t,"design.md")))&&i.splice(1,0,Ie("design.md exists and non-empty",async()=>await Kr(Rt.join(t,"design.md"))?ve():Se(""))),Bi(e,i)}async function G2(e,t,n){let r=await ft(t,"design_doc"),i=await ft(t,"workflow"),s=await pi(De(),t),o=s.designRequired||await zr(Rt.join(t,"design.md")),c=[Ie("OpenSpec required dependency closure is ready",async()=>s.problems.length?Se(s.problems.join(`
|
|
314
|
+
`)):ve()),Ie("proposal.md exists",async()=>await Kr(Rt.join(t,"proposal.md"))?ve():Se("")),Ie("design.md exists",async()=>!o||await Kr(Rt.join(t,"design.md"))?ve():Se("")),Ie("tasks.md exists",async()=>await Kr(Rt.join(t,"tasks.md"))?ve():Se("")),Ie("design handoff context exists",()=>z2(t,n))];i==="full"&&c.push(Ie("design_doc is recorded for full workflow",()=>K2(t,n)));let l=await Bi(e,c);return r&&r!=="null"?l=await Bi(e,[Ie(`Design Doc (${r}) exists`,async()=>await Kr(r)?ve():Se(""))])||l:i!=="full"&&e.stderr.push(A2(" [WARN] No design_doc recorded in .comet.yaml (optional for hotfix/tweak)")),l}async function Y2(e,t,n,r){return await Bi(e,[Ie("bound branch matches workspace mode",()=>nv(t,n)),Ie("isolation selected",()=>q2(t,n)),Ie("build_mode selected",()=>L2(t,n)),Ie("build_mode allowed for workflow",()=>W2(t)),Ie("autonomous full build prerequisites",async()=>{let s=(await Wt(t,{migrate:!1})).classic;if(!s)return Se("Classic state is missing");let o=await sd(De(),n,s);return o.length?Se(o.join(`
|
|
315
|
+
`)):ve()}),Ie("subagent dispatch confirmed",()=>M2(t,n)),Ie("tdd_mode selected",()=>F2(t,n)),Ie("review_mode selected",()=>H2(t,n)),Ie("tasks.md all tasks checked",()=>tv(t)),Ie("plan task mapping is valid",()=>D2(t)),Ie("proposal.md exists",async()=>await Kr(Rt.join(t,"proposal.md"))?ve():Se(""))])?!0:Bi(e,[Ie("Build passes",async()=>{let s=await fP(t,n,r,"build");return s.status===0?ve(s.output):Se(s.output)})])}async function X2(e,t,n,r){return await Bi(e,[Ie("bound branch matches workspace mode",()=>nv(t,n)),Ie("tasks.md all tasks checked",()=>tv(t)),Ie("verification_report exists",async()=>await B2(t)?ve():Se(""))])?!0:Bi(e,[Ie("Verification passes",async()=>{let s=await fP(t,n,r,"verify");return s.status===0?ve(s.output):Se(s.output)})])}async function Q2(e,t,n){return Bi(e,[Ie("bound branch matches workspace mode",()=>nv(t,n)),Ie("archived is true",async()=>await U2(t)?ve():Se("")),Ie("proposal.md exists",async()=>await Kr(Rt.join(t,"proposal.md"))?ve():Se("")),Ie("archived required artifacts exist",async()=>{let r=await Eo(De(),t);return r.length?Se(r.join(`
|
|
316
|
+
`)):ve()}),Ie("tasks.md all tasks checked",()=>tv(t)),Ie("branch_status=handled",async()=>await V2(t)?ve():Se(""))])}async function Z2(e,t,n,r){return Nt(n,()=>eK(e,t,n,r))}async function eK(e,t,n,r){let i=VI[r];if(!i)return;let s=await Po(n);if((r==="build"||r==="verify")&&process.env.COMET_SKIP_BUILD!=="1"){let f=await Ah(De(),n,s.run,r);if(!f.record)throw new He(f.reason??"请提交本阶段真实检查结果。")}let o=At(s.classic,i);if(r==="verify"&&process.env.COMET_SKIP_BUILD!=="1"){let f=await xh(De(),n,s.run,"verify");if(!f)throw new He("Verify 检查已变化,不能记录接受证据");await FS(De(),n,s.run,o.classic,f)}await fd(n,o.classic,s.run,{event:i,phase:r,source:"comet-guard"}),await lP(n,{change:t,event:i,source:"comet-guard",from:s.classic,to:o.classic,effects:o.effects});for(let f of o.effects)e.stderr.push(Hi(`[SET] ${I2(f.field)}=${_2(f.to)}`));e.stderr.push(Hi(`[TRANSITION] ${i}`));let c=E2[r],l=r==="open"?c.replace("PLACEHOLDER",o.classic.phase):c;e.stderr.push(Hi(l))}var rv=yo(async(e,t)=>{let n=new Zy,[r,i,s]=e;try{if(e.length<2)throw new He("Usage: comet guard <change-name> <open|design|build|verify|archive> [--apply]");if(P2(r),!i||!S2.includes(i))throw new He(`${Ur(`Unknown phase: ${i??""}`)}
|
|
317
|
+
Valid phases: open, design, build, verify, archive`);let o=De(),l=(await Ey(o,r))?.format==="compat"?null:await Xy(o,r);if(l){let m,h=e.indexOf("--checks"),g=e.indexOf("--");if(h>=0&&(g<0||h<g)){if(m=e[h+1],!["build","verify"].includes(i)||!m||m.startsWith("--")||l.run.workflow.version!=="2")throw new He("--checks requires a new built-in Classic Build or Verify");e=e.filter((F,B)=>B!==h&&B!==h+1)}let w=e.indexOf("--session"),k=e.indexOf("--"),y;if(w>=0&&(k<0||w<k)){if(y=e[w+1],i!=="build"||!y?.trim()||y.startsWith("--"))throw new He("--session requires a Builder execution reference");e=e.filter((F,B)=>B!==w&&B!==w+1)}let R=e.indexOf("--local"),S=e.indexOf("--"),C=R>=0&&(S<0||R<S);if(C){if(!["build","verify"].includes(i)||!e.includes("--apply"))throw new He("--local requires an applied Build or Verify check");e=e.filter((F,B)=>B!==R)}let q,T;for(let F of["--cwd","--timeout-ms"]){let B=e.indexOf(F),X=e.indexOf("--");if(B<0||X>=0&&B>X)continue;let Y=e[B+1];if(!["build","verify"].includes(i)||!e.includes("--apply")||!Y||Y.startsWith("--"))throw new He(`${F} requires an applied Build or Verify check and a value`);if(F==="--cwd")q=Y;else if(T=Number(Y),!Number.isSafeInteger(T)||T<=0)throw new He("--timeout-ms requires a positive integer");e=e.filter((de,G)=>G!==B&&G!==B+1)}if((q!==void 0||T!==void 0)&&!e.includes("--"))throw new He("Check cwd and timeout options require a literal program after --");if(i==="open"){let F=e.length===5&&e[2]==="--apply"&&e[3]==="--approval-hash";if(e.length!==2&&!F)throw new He("Usage: comet guard <change-name> open [--apply --approval-hash <sha256>]");return iP({inspected:l,projectRoot:l.projectRoot,change:r,apply:F,...F?{approvalHash:e[4]}:{}})}if(i==="design"){let F=e.length===7&&e[4]==="--apply"&&e[5]==="--approval-hash";if(e[2]!=="--design-doc"||!e[3]||e.length!==4&&!F)throw new He("Usage: comet guard <change-name> design --design-doc <repo-relative-ref> [--apply --approval-hash <sha256>]");return sP({inspected:l,projectRoot:l.projectRoot,change:r,designDoc:e[3],apply:F,...F?{approvalHash:e[6]}:{}})}if(i==="build"){let F=e[2]==="--apply",B=e.indexOf("--");if(e.length!==2&&!(F&&e.length===3)&&!(F&&B===3&&e.length>=5))throw new He("Usage: comet guard <change-name> build [--apply [-- <program> [args...]]]");let X=B===3?e.slice(B+1):void 0,Y=q,de=T;return oP({inspected:l,projectRoot:l.projectRoot,invocationCwd:ju(),change:r,apply:F,reusable:C,sessionId:y,checksRef:m,...X?{argv:X}:{},...Y?{checkCwd:Y}:{},...de===void 0?{}:{checkTimeoutMs:de}})}if(i==="verify"){let F=e[4]==="--apply",B=e.indexOf("--");if(e[2]!=="--report"||!e[3]||e.length!==4&&!(F&&e.length===5)&&!(F&&B===5&&e.length>=7))throw new He("Usage: comet guard <change-name> verify --report <repo-relative-ref> [--apply -- <program> [args...]]");let X=B===5?e.slice(B+1):void 0,Y=q,de=T;return aP({inspected:l,projectRoot:l.projectRoot,invocationCwd:ju(),change:r,reportRef:e[3],apply:F,reusable:C,checksRef:m,...X?{argv:X}:{},...Y?{checkCwd:Y}:{},...de===void 0?{}:{checkTimeoutMs:de}})}if(i==="archive"){if(e.length!==2&&!(e.length===3&&e[2]==="--apply"))throw new He("Usage: comet guard <change-name> archive [--apply]");return cP({inspected:l,projectRoot:l.projectRoot,change:r,apply:e.length===3})}throw new He(`Classic SDK ${i} Guard is not yet available`)}if(e.length>3||s!==void 0&&s!=="--apply")throw new He("Usage: comet guard <change-name> <open|design|build|verify|archive> [--apply]");await Tr(De());let f=await O2(r);await T2(f,r);let a=await Po(f);n.data={change:r,phase:a.classic.phase,projectRoot:De(),changeDir:f};let u=await kC(f,r);t.json&&(n.diagnostics={change:r,phase:i,currentStep:u.currentStep,runtimeEval:u.runtimeEval}),n.stderr.push(C2[i]);let p;i==="open"?p=await J2(n,f):i==="design"?p=await G2(n,f,r):i==="build"?p=await Y2(n,f,r,a.run):i==="verify"?p=await X2(n,f,r,a.run):p=await Q2(n,f,r);let d=bC({name:r,phase:i,failed:n.checksFailed,total:n.checksPassed+n.checksFailed,locale:md(a.classic.language)});if(n.envelope=d,p)return n.stderr.push(""),n.stderr.push(d.summary),d.user_message&&n.stderr.push(`RELAY TO USER: ${d.user_message}`),n.stderr.push(""),n.stderr.push(Ur("BLOCKED — fix failing checks before proceeding to next phase")),n.toResult(1);if(n.stderr.push(""),n.stderr.push(d.summary),i==="archive")n.stderr.push(Hi("ALL CHECKS PASSED — archive completeness verified; no further phase transition."));else if(s==="--apply"){n.stderr.push(Hi("ALL CHECKS PASSED — ready for next phase"));let m=await Nt(f,async()=>(await Z2(n,r,f,i),Wt(f,{migrate:!1})));m.classic&&(n.data={...await Rd(De(),f,m.classic,!1,m.run??null),change:r,phase:m.classic.phase,configuration:m.classic})}else n.stderr.push(Hi("ALL CHECKS PASSED — ready for next phase")),n.stderr.push(`Check only: phase unchanged. To advance, run comet guard ${r} ${i} --apply`);return n.toResult(0)}catch(o){if(n.issues.push(kr(o)),o instanceof He){for(let c of o.message.split(`
|
|
318
|
+
`))n.stderr.push(c);return n.toResult(o.exitCode)}return n.stderr.push(o instanceof Error?o.message:String(o)),n.toResult(70)}});import{realpathSync as aK}from"fs";import{pathToFileURL as wP}from"url";Tt();var tK=new Set([...ls,"archive_confirmation","verify_failures","check_epoch","classic_profile","classic_migration","bound_branch"]),pP=new Set(mr.filter(e=>!tK.has(e))),iv={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"]};Tt();var nK=`
|
|
319
|
+
Options: --json (machine-readable output), --compact (requires --json), --help
|
|
320
|
+
精简视图用 outputView.references 的 JSON Pointer 定位重复字段;Request 模板保留完整;没有字节收益时返回原完整协议。去掉 --compact 获取完整协议。
|
|
321
|
+
JSON: one object with command and exitCode; data, stdout, stderr, summary and next are optional.
|
|
322
|
+
Use exitCode for success; do not parse human-readable stdout. Help text is in stdout in JSON mode.
|
|
323
|
+
`;function mP(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: ${[...mr,...ls].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):",...[...pP].map(l=>` ${l}${iv[l]?`: ${iv[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: ${BI.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(`
|
|
324
|
+
`)}
|
|
325
|
+
${nK}Command placeholders must be replaced with actual values.
|
|
326
|
+
`:void 0}ds();import{randomUUID as rK}from"node:crypto";kf();import{performance as hP}from"node:perf_hooks";ds();var iK=7*864e5,sK=1e4;async function oK(e,t){let n=Qo(await Wf(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
327
|
+
CREATE TABLE IF NOT EXISTS samples (
|
|
328
|
+
id TEXT PRIMARY KEY, workflow TEXT NOT NULL, kind TEXT NOT NULL, command TEXT NOT NULL,
|
|
329
|
+
occurredAt TEXT NOT NULL, durationMs REAL NOT NULL, exitCode INTEGER NOT NULL,
|
|
330
|
+
gitCommands INTEGER NOT NULL, gitDurationMs REAL NOT NULL);
|
|
331
|
+
CREATE INDEX IF NOT EXISTS samples_time ON samples(occurredAt);
|
|
332
|
+
BEGIN IMMEDIATE;`),n.prepare("DELETE FROM samples WHERE occurredAt < ?").run(new Date(Date.now()-iK).toISOString()),n.prepare("INSERT INTO samples VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(rK(),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(sK),n.exec("COMMIT")}finally{n.close()}}async function gP(e,t){let n=hP.now(),r,i,s=!1,o=1,c=!0,{metrics:l}=await l_({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"}},()=>gS(async()=>{try{r=await t()}catch(a){s=!0,i=a}})),f=Math.max(0,hP.now()-n);try{if(!c)throw new Error("Runtime result classification unavailable");await oK(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}nt();function cK(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e,exitCode:t.exitCode,agent:$y(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}})+`
|
|
333
|
+
`,...t.envelope===void 0?{}:{envelope:t.envelope}}}async function yP(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=mP(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 hS(()=>gP({projectRoot:()=>r.projectRoot??ct(r.invocationCwd??process.cwd()),workflow:"classic",command:e,errorExitCode:u=>u instanceof ns?1:70},a))}catch(f){l={exitCode:f instanceof ns?1:70,stderr:f instanceof Error?f.message:String(f),data:{issues:[kr(f)]}}}return o?cK(e,l):l}function vP(e,t){return async(n,r={})=>n[0]!==e?{exitCode:64,stderr:`Expected Classic command: ${e}`}:yP(e,t,n.slice(1),r)}function kP(e){let t=process.argv[1];if(!t)return!1;if(e===wP(t).href)return!0;try{return e===wP(aK(t)).href}catch{return!1}}async function bP(e,t,n=process.argv.slice(2)){let r=await yP(e,t,n);return r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr+(r.stderr.endsWith(`
|
|
334
|
+
`)?"":`
|
|
335
|
+
`)),r.exitCode}var Qse=vP("guard",rv);kP(import.meta.url)&&(process.exitCode=await bP("guard",rv));export{Qse as runClassicCli};
|