comet-dsh-plugin 0.0.0-stage → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +176 -0
- package/README.md +152 -2
- package/client.js +349 -0
- package/cordis.patch.yml +4 -0
- package/icon.png +0 -0
- package/index.js +183 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +57 -4
- package/rules/comet-workflow-guard.md +63 -0
- package/rules/migration-assets.json +218 -0
- package/server/comet-plugin-setup.mjs +192 -0
- package/skills/comet/SKILL.md +37 -0
- package/skills/comet/agents/openai.yaml +3 -0
- package/skills/comet/reference/change-walkthrough.md +77 -0
- package/skills/comet/reference/edit-review.md +26 -0
- package/skills/comet/reference/host-check.md +11 -0
- package/skills/comet/reference/platform-execution.md +34 -0
- package/skills/comet/reference/task-learning.md +39 -0
- package/skills/comet/runtime/classic/checks.yaml +6 -0
- package/skills/comet/runtime/classic/guardrails.yaml +13 -0
- package/skills/comet/runtime/classic/skill.yaml +122 -0
- package/skills/comet/scripts/comet-archive.mjs +310 -0
- package/skills/comet/scripts/comet-check.mjs +179 -0
- package/skills/comet/scripts/comet-entry-runtime.mjs +151 -0
- package/skills/comet/scripts/comet-env.mjs +15 -0
- package/skills/comet/scripts/comet-guard.mjs +335 -0
- package/skills/comet/scripts/comet-handoff.mjs +289 -0
- package/skills/comet/scripts/comet-hook-guard.mjs +294 -0
- package/skills/comet/scripts/comet-hook-router-guard.mjs +628 -0
- package/skills/comet/scripts/comet-hook-router.mjs +17 -0
- package/skills/comet/scripts/comet-intent.mjs +181 -0
- package/skills/comet/scripts/comet-plugin-hook.mjs +213 -0
- package/skills/comet/scripts/comet-resume-probe.mjs +205 -0
- package/skills/comet/scripts/comet-runtime.mjs +571 -0
- package/skills/comet/scripts/comet-state.mjs +381 -0
- package/skills/comet/scripts/comet-yaml-validate.mjs +182 -0
- package/skills/comet-any/SKILL.md +47 -0
- package/skills/comet-any/agents/openai.yaml +5 -0
- package/skills/comet-any/reference/sdk-creation.md +100 -0
- package/skills/comet-archive/SKILL.md +28 -0
- package/skills/comet-archive/agents/openai.yaml +5 -0
- package/skills/comet-archive/reference/compat.md +188 -0
- package/skills/comet-build/SKILL.md +35 -0
- package/skills/comet-build/agents/openai.yaml +5 -0
- package/skills/comet-build/reference/compat.md +191 -0
- package/skills/comet-classic/SKILL.md +98 -0
- package/skills/comet-classic/agents/openai.yaml +3 -0
- package/skills/comet-classic/reference/auto-transition.md +34 -0
- package/skills/comet-classic/reference/classic-layout.md +36 -0
- package/skills/comet-classic/reference/comet-yaml-fields.md +82 -0
- package/skills/comet-classic/reference/context-recovery.md +128 -0
- package/skills/comet-classic/reference/debug-gate.md +30 -0
- package/skills/comet-classic/reference/decision-point.md +109 -0
- package/skills/comet-classic/reference/dirty-worktree.md +59 -0
- package/skills/comet-classic/reference/file-structure.md +32 -0
- package/skills/comet-classic/reference/intent-frame.md +132 -0
- package/skills/comet-classic/reference/scripts.md +144 -0
- package/skills/comet-classic/reference/sdk-methods.md +136 -0
- package/skills/comet-classic/reference/subagent-dispatch.md +75 -0
- package/skills/comet-classic/reference/workspace.md +23 -0
- package/skills/comet-design/SKILL.md +25 -0
- package/skills/comet-design/agents/openai.yaml +5 -0
- package/skills/comet-design/reference/compat.md +191 -0
- package/skills/comet-hotfix/SKILL.md +46 -0
- package/skills/comet-hotfix/agents/openai.yaml +5 -0
- package/skills/comet-hotfix/reference/compat.md +240 -0
- package/skills/comet-memory/SKILL.md +68 -0
- package/skills/comet-memory/agents/openai.yaml +5 -0
- package/skills/comet-native/SKILL.md +139 -0
- package/skills/comet-native/agents/openai.yaml +3 -0
- package/skills/comet-native/reference/artifacts.md +118 -0
- package/skills/comet-native/reference/clarification.md +120 -0
- package/skills/comet-native/reference/commands.md +321 -0
- package/skills/comet-native/reference/edit-review.md +26 -0
- package/skills/comet-native/reference/recovery.md +64 -0
- package/skills/comet-native/reference/workspace.md +70 -0
- package/skills/comet-native/scripts/comet-native-archive.mjs +475 -0
- package/skills/comet-native/scripts/comet-native-cancel.mjs +461 -0
- package/skills/comet-native/scripts/comet-native-doctor.mjs +475 -0
- package/skills/comet-native/scripts/comet-native-hook-guard.mjs +470 -0
- package/skills/comet-native/scripts/comet-native-init.mjs +465 -0
- package/skills/comet-native/scripts/comet-native-new.mjs +478 -0
- package/skills/comet-native/scripts/comet-native-next.mjs +464 -0
- package/skills/comet-native/scripts/comet-native-root.mjs +472 -0
- package/skills/comet-native/scripts/comet-native-runtime.mjs +525 -0
- package/skills/comet-native/scripts/comet-native-select.mjs +468 -0
- package/skills/comet-native/scripts/comet-native-show.mjs +462 -0
- package/skills/comet-native/scripts/comet-native-spec.mjs +468 -0
- package/skills/comet-native/scripts/comet-native-status.mjs +467 -0
- package/skills/comet-native/scripts/comet-native-transfer.mjs +466 -0
- package/skills/comet-open/SKILL.md +265 -0
- package/skills/comet-open/agents/openai.yaml +5 -0
- package/skills/comet-open/reference/batch-changes.md +51 -0
- package/skills/comet-review/SKILL.md +121 -0
- package/skills/comet-review/agents/openai.yaml +5 -0
- package/skills/comet-tweak/SKILL.md +49 -0
- package/skills/comet-tweak/agents/openai.yaml +5 -0
- package/skills/comet-tweak/reference/compat.md +232 -0
- package/skills/comet-verify/SKILL.md +30 -0
- package/skills/comet-verify/agents/openai.yaml +5 -0
- package/skills/comet-verify/reference/compat.md +202 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
|
+
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
+
var Sg=Object.create;var Os=Object.defineProperty;var Eg=Object.getOwnPropertyDescriptor;var xg=Object.getOwnPropertyNames;var Ag=Object.getPrototypeOf,Pg=Object.prototype.hasOwnProperty;var xi=(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 ne=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var _=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Og=(e,t)=>{for(var n in t)Os(e,n,{get:t[n],enumerable:!0})},Ig=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of xg(t))!Pg.call(e,i)&&i!==n&&Os(e,i,{get:()=>t[i],enumerable:!(r=Eg(t,i))||r.enumerable});return e};var De=(e,t,n)=>(n=e!=null?Sg(Ag(e)):{},Ig(t||!e||!e.__esModule?Os(n,"default",{value:e,enumerable:!0}):n,e));function Is(e){return e.charCodeAt(0)===65279?e.slice(1):e}var _s=ne(()=>{"use strict"});import{AsyncLocalStorage as _g}from"node:async_hooks";function Ts(){let e=Ns.getStore();return e?.active?e:null}async function Ai(e){if(Ts()!==null)return e();let t={entries:new Map,active:!0};return Ns.run(t,async()=>{try{return await e()}finally{t.active=!1,t.entries.clear()}})}async function sn(e){return Ns.run({entries:new Map,active:!1},e)}function Hl(e,t){let n=e;for(let r of t)n+="\0"+(typeof r=="string"?r:JSON.stringify(r));return n}function Re(e,t){return(...n)=>{let r=Ts();if(r===null)return t(...n);let i=Hl(`async:${e}`,n),o=r.entries.get(i);if(o)return o.value;let a=t(...n).catch(u=>{throw r.entries.get(i)?.value===a&&r.entries.delete(i),u});return r.entries.set(i,{value:a}),a}}function dt(e,t){return(...n)=>{let r=Ts();if(r===null)return t(...n);let i=Hl(`sync:${e}`,n),o=r.entries.get(i);if(o)return o.value;let a=t(...n);return r.entries.set(i,{value:a}),a}}var Ns,Ke=ne(()=>{"use strict";Ns=new _g});function _t(e){return e!==0&&e!==0n&&e!=="0"}function _i(e,t){return _t(e.dev)&&_t(t.dev)&&_t(e.ino)&&_t(t.ino)}function ze(e,t){let n=_t(e.dev)&&_t(t.dev);if(n&&e.dev!==t.dev)return!1;let r=_t(e.ino)&&_t(t.ino);return r&&e.ino!==t.ino?!1:n&&r?!0:e.birthtime===t.birthtime}var yr=ne(()=>{"use strict"});import{constants as Nt,promises as qe}from"fs";import{createHash as Bg}from"node:crypto";function $s(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ni(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function jt(e){return{dev:e.dev,ino:e.ino,birthtime:$s(e)}}function Hg(e,t){let n=jt(e),r=jt(t);return _i(n,r)?ze(n,r):ze(n,r)&&$s(e)===$s(t)&&Ni(e)===Ni(t)&&e.size===t.size}function Tt(e,t){let n=r=>"mtimeNs"in r?r.mtimeNs:r.mtimeMs;return Hg(e,t)&&e.size===t.size&&e.mode===t.mode&&n(e)===n(t)&&Ni(e)===Ni(t)}async function an(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,o=await qe.lstat(e,{bigint:i});if(!o.isFile()||o.isSymbolicLink())throw new Ae("not-regular-file",`${r} must be a regular file`);if(BigInt(o.size)>BigInt(t))throw new Ae("too-large",`${r} exceeds ${t} bytes`);let a=await qe.realpath(e);await n.verify?.("pre-open",{realPath:a,identity:jt(o)});let u=process.platform==="win32"?Nt.O_RDONLY:Nt.O_RDONLY|Nt.O_NOFOLLOW|Nt.O_NONBLOCK,f;try{f=await qe.open(e,u)}catch(d){throw d.code==="ELOOP"?new Ae("not-regular-file",`${r} must be a regular file`,{cause:d}):d}try{let[d,s,l]=await Promise.all([f.stat({bigint:i}),qe.lstat(e,{bigint:i}),qe.realpath(e)]);if(!d.isFile()||!s.isFile()||s.isSymbolicLink()||l!==a||!Tt(o,d)||!Tt(o,s))throw new Ae("changed",`${r} changed while opening`);await n.verify?.("post-open",{realPath:l,identity:jt(d)}),await n.hooks?.afterOpen?.();let m=[],c=0,p=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let v=t+1-c,{bytesRead:k}=await f.read(p,0,Math.min(p.length,v),null);if(k===0)break;if(c+=k,c>t)throw new Ae("too-large",`${r} exceeds ${t} bytes`);m.push(Buffer.from(p.subarray(0,k)))}await n.hooks?.beforeFinalCheck?.();let[h,g,w]=await Promise.all([f.stat({bigint:i}),qe.lstat(e,{bigint:i}),qe.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||w!==a||!Tt(o,h)||!Tt(o,g))throw new Ae("changed",`${r} changed while reading`);return await n.verify?.("post-read",{realPath:w,identity:jt(h)}),{bytes:Buffer.concat(m,c),stat:h,realPath:w}}finally{await f.close()}}async function Kl(e,t={}){let n=t.label??"file",r=t.bigint===!0,i=await qe.lstat(e,{bigint:r});if(!i.isFile()||i.isSymbolicLink())throw new Ae("not-regular-file",`${n} must be a regular file`);let o=await qe.realpath(e);await t.verify?.("pre-open",{realPath:o,identity:jt(i)});let a=process.platform==="win32"?Nt.O_RDONLY:Nt.O_RDONLY|Nt.O_NOFOLLOW|Nt.O_NONBLOCK,u;try{u=await qe.open(e,a)}catch(f){throw f.code==="ELOOP"?new Ae("not-regular-file",`${n} must be a regular file`,{cause:f}):f}try{let[f,d,s]=await Promise.all([u.stat({bigint:r}),qe.lstat(e,{bigint:r}),qe.realpath(e)]);if(!f.isFile()||!d.isFile()||d.isSymbolicLink()||s!==o||!Tt(i,f)||!Tt(i,d))throw new Ae("changed",`${n} changed while opening`);await t.verify?.("post-open",{realPath:s,identity:jt(f)}),await t.hooks?.afterOpen?.();let l=Bg(t.algorithm??"sha256"),m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:g}=await u.read(m,0,m.length,null);if(g===0)break;l.update(m.subarray(0,g))}await t.hooks?.beforeFinalCheck?.();let[c,p,h]=await Promise.all([u.stat({bigint:r}),qe.lstat(e,{bigint:r}),qe.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||h!==o||!Tt(i,c)||!Tt(i,p))throw new Ae("changed",`${n} changed while reading`);return await t.verify?.("post-read",{realPath:h,identity:jt(c)}),{digest:l.digest("hex"),stat:c,realPath:h}}finally{await u.close()}}var Ae,cn=ne(()=>{"use strict";yr();Ae=class extends Error{reason;constructor(t,n,r){super(n,r),this.name="RaceSafeReadError",this.reason=t}}});var H=_(Se=>{"use strict";var Hs=Symbol.for("yaml.alias"),ru=Symbol.for("yaml.document"),Di=Symbol.for("yaml.map"),iu=Symbol.for("yaml.pair"),Vs=Symbol.for("yaml.scalar"),Li=Symbol.for("yaml.seq"),Rt=Symbol.for("yaml.node.type"),Kg=e=>!!e&&typeof e=="object"&&e[Rt]===Hs,zg=e=>!!e&&typeof e=="object"&&e[Rt]===ru,Gg=e=>!!e&&typeof e=="object"&&e[Rt]===Di,Yg=e=>!!e&&typeof e=="object"&&e[Rt]===iu,ou=e=>!!e&&typeof e=="object"&&e[Rt]===Vs,Xg=e=>!!e&&typeof e=="object"&&e[Rt]===Li;function su(e){if(e&&typeof e=="object")switch(e[Rt]){case Di:case Li:return!0}return!1}function Qg(e){if(e&&typeof e=="object")switch(e[Rt]){case Hs:case Di:case Vs:case Li:return!0}return!1}var Zg=e=>(ou(e)||su(e))&&!!e.anchor;Se.ALIAS=Hs;Se.DOC=ru;Se.MAP=Di;Se.NODE_TYPE=Rt;Se.PAIR=iu;Se.SCALAR=Vs;Se.SEQ=Li;Se.hasAnchor=Zg;Se.isAlias=Kg;Se.isCollection=su;Se.isDocument=zg;Se.isMap=Gg;Se.isNode=Qg;Se.isPair=Yg;Se.isScalar=ou;Se.isSeq=Xg});var kr=_(Us=>{"use strict";var he=H(),$e=Symbol("break visit"),au=Symbol("skip children"),ft=Symbol("remove node");function qi(e,t){let n=cu(t);he.isDocument(e)?Mn(null,e.contents,n,Object.freeze([e]))===ft&&(e.contents=null):Mn(null,e,n,Object.freeze([]))}qi.BREAK=$e;qi.SKIP=au;qi.REMOVE=ft;function Mn(e,t,n,r){let i=lu(e,t,n,r);if(he.isNode(i)||he.isPair(i))return uu(e,r,i),Mn(e,i,n,r);if(typeof i!="symbol"){if(he.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let a=Mn(o,t.items[o],n,r);if(typeof a=="number")o=a-1;else{if(a===$e)return $e;a===ft&&(t.items.splice(o,1),o-=1)}}}else if(he.isPair(t)){r=Object.freeze(r.concat(t));let o=Mn("key",t.key,n,r);if(o===$e)return $e;o===ft&&(t.key=null);let a=Mn("value",t.value,n,r);if(a===$e)return $e;a===ft&&(t.value=null)}}return i}async function $i(e,t){let n=cu(t);he.isDocument(e)?await Wn(null,e.contents,n,Object.freeze([e]))===ft&&(e.contents=null):await Wn(null,e,n,Object.freeze([]))}$i.BREAK=$e;$i.SKIP=au;$i.REMOVE=ft;async function Wn(e,t,n,r){let i=await lu(e,t,n,r);if(he.isNode(i)||he.isPair(i))return uu(e,r,i),Wn(e,i,n,r);if(typeof i!="symbol"){if(he.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let a=await Wn(o,t.items[o],n,r);if(typeof a=="number")o=a-1;else{if(a===$e)return $e;a===ft&&(t.items.splice(o,1),o-=1)}}}else if(he.isPair(t)){r=Object.freeze(r.concat(t));let o=await Wn("key",t.key,n,r);if(o===$e)return $e;o===ft&&(t.key=null);let a=await Wn("value",t.value,n,r);if(a===$e)return $e;a===ft&&(t.value=null)}}return i}function cu(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 lu(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(he.isMap(t))return n.Map?.(e,t,r);if(he.isSeq(t))return n.Seq?.(e,t,r);if(he.isPair(t))return n.Pair?.(e,t,r);if(he.isScalar(t))return n.Scalar?.(e,t,r);if(he.isAlias(t))return n.Alias?.(e,t,r)}function uu(e,t,n){let r=t[t.length-1];if(he.isCollection(r))r.items[e]=n;else if(he.isPair(r))e==="key"?r.key=n:r.value=n;else if(he.isDocument(r))r.contents=n;else{let i=he.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Us.visit=qi;Us.visitAsync=$i});var Js=_(fu=>{"use strict";var du=H(),ew=kr(),tw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},nw=e=>e.replace(/[!,[\]{}]/g,t=>tw[t]),br=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[o,a]=r;return this.tags[o]=a,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let a=/^\d+\.\d+$/.test(o);return n(6,`Unsupported YAML version ${o}`,a),!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 a=t.slice(2,-1);return a==="!"||a==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),a)}let[,r,i]=t.match(/^(.*!)([^!]*)$/s);i||n(`The ${t} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(i)}catch(a){return n(String(a)),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+nw(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&&du.isNode(t.contents)){let o={};ew.visit(t.contents,(a,u)=>{du.isNode(u)&&u.tag&&(o[u.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,a]of r)o==="!!"&&a==="tag:yaml.org,2002:"||(!t||i.some(u=>u.startsWith(a)))&&n.push(`%TAG ${o} ${a}`);return n.join(`
|
|
5
|
+
`)}};br.defaultYaml={explicit:!1,version:"1.2"};br.defaultTags={"!!":"tag:yaml.org,2002:"};fu.Directives=br});var Mi=_(Rr=>{"use strict";var pu=H(),rw=kr();function iw(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 mu(e){let t=new Set;return rw.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function hu(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function ow(e,t){let n=[],r=new Map,i=null;return{onAnchor:o=>{n.push(o),i??(i=mu(e));let a=hu(t,i);return i.add(a),a},setAnchors:()=>{for(let o of n){let a=r.get(o);if(typeof a=="object"&&a.anchor&&(pu.isScalar(a.node)||pu.isCollection(a.node)))a.node.anchor=a.anchor;else{let u=new Error("Failed to resolve repeated object (this should not happen)");throw u.source=o,u}}},sourceObjects:r}}Rr.anchorIsValid=iw;Rr.anchorNames=mu;Rr.createNodeAnchors=ow;Rr.findNewAnchor=hu});var Ks=_(gu=>{"use strict";function Cr(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,o=r.length;i<o;++i){let a=r[i],u=Cr(e,r,String(i),a);u===void 0?delete r[i]:u!==a&&(r[i]=u)}else if(r instanceof Map)for(let i of Array.from(r.keys())){let o=r.get(i),a=Cr(e,r,i,o);a===void 0?r.delete(i):a!==o&&r.set(i,a)}else if(r instanceof Set)for(let i of Array.from(r)){let o=Cr(e,r,i,i);o===void 0?r.delete(i):o!==i&&(r.delete(i),r.add(o))}else for(let[i,o]of Object.entries(r)){let a=Cr(e,r,i,o);a===void 0?delete r[i]:a!==o&&(r[i]=a)}return e.call(t,n,r)}gu.applyReviver=Cr});var Lt=_(yu=>{"use strict";var sw=H();function wu(e,t,n){if(Array.isArray(e))return e.map((r,i)=>wu(r,String(i),n));if(e&&typeof e.toJSON=="function"){if(!n||!sw.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=o=>{r.res=o,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}yu.toJS=wu});var Wi=_(ku=>{"use strict";var aw=Ks(),vu=H(),cw=Lt(),zs=class{constructor(t){Object.defineProperty(this,vu.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:o}={}){if(!vu.isDocument(t))throw new TypeError("A document argument is required");let a={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},u=cw.toJS(this,"",a);if(typeof i=="function")for(let{count:f,res:d}of a.anchors.values())i(d,f);return typeof o=="function"?aw.applyReviver(o,{"":u},"",u):u}};ku.NodeBase=zs});var Sr=_(bu=>{"use strict";var lw=Mi(),uw=kr(),Fn=H(),dw=Wi(),fw=Lt(),Gs=class extends dw.NodeBase{constructor(t){super(Fn.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=[],uw.visit(t,{Node:(o,a)=>{(Fn.isAlias(a)||Fn.hasAnchor(a))&&r.push(a)}}),n&&(n.aliasResolveCache=r));let i;for(let o of r){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(t,n){if(!n)return{source:this.source};let{anchors:r,doc:i,maxAliasCount:o}=n,a=this.resolve(i,n);if(!a){let f=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(f)}let u=r.get(a);if(u||(fw.toJS(a,null,n),u=r.get(a)),u?.res===void 0){let f="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(f)}if(o>=0&&(u.count+=1,u.aliasCount===0&&(u.aliasCount=Fi(i,a,r)),u.count*u.aliasCount>o)){let f="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(f)}return u.res}toString(t,n,r){let i=`*${this.source}`;if(t){if(lw.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${i} `}return i}};function Fi(e,t,n){if(Fn.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(Fn.isCollection(t)){let r=0;for(let i of t.items){let o=Fi(e,i,n);o>r&&(r=o)}return r}else if(Fn.isPair(t)){let r=Fi(e,t.key,n),i=Fi(e,t.value,n);return Math.max(r,i)}return 1}bu.Alias=Gs});var de=_(Ys=>{"use strict";var pw=H(),mw=Wi(),hw=Lt(),gw=e=>!e||typeof e!="function"&&typeof e!="object",qt=class extends mw.NodeBase{constructor(t){super(pw.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:hw.toJS(this.value,t,n)}toString(){return String(this.value)}};qt.BLOCK_FOLDED="BLOCK_FOLDED";qt.BLOCK_LITERAL="BLOCK_LITERAL";qt.PLAIN="PLAIN";qt.QUOTE_DOUBLE="QUOTE_DOUBLE";qt.QUOTE_SINGLE="QUOTE_SINGLE";Ys.Scalar=qt;Ys.isScalarValue=gw});var Er=_(Cu=>{"use strict";var ww=Sr(),dn=H(),Ru=de(),yw="tag:yaml.org,2002:";function vw(e,t,n){if(t){let r=n.filter(o=>o.tag===t),i=r.find(o=>!o.format)??r[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return n.find(r=>r.identify?.(e)&&!r.format)}function kw(e,t,n){if(dn.isDocument(e)&&(e=e.contents),dn.isNode(e))return e;if(dn.isPair(e)){let l=n.schema[dn.MAP].createNode?.(n.schema,null,n);return l.items.push(e),l}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:o,schema:a,sourceObjects:u}=n,f;if(r&&e&&typeof e=="object"){if(f=u.get(e),f)return f.anchor??(f.anchor=i(e)),new ww.Alias(f.anchor);f={anchor:null,node:null},u.set(e,f)}t?.startsWith("!!")&&(t=yw+t.slice(2));let d=vw(e,t,a.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let l=new Ru.Scalar(e);return f&&(f.node=l),l}d=e instanceof Map?a[dn.MAP]:Symbol.iterator in Object(e)?a[dn.SEQ]:a[dn.MAP]}o&&(o(d),delete n.onTagObj);let s=d?.createNode?d.createNode(n.schema,e,n):typeof d?.nodeClass?.from=="function"?d.nodeClass.from(n.schema,e,n):new Ru.Scalar(e);return t?s.tag=t:d.default||(s.tag=d.tag),f&&(f.node=s),s}Cu.createNode=kw});var Hi=_(Bi=>{"use strict";var bw=Er(),pt=H(),Rw=Wi();function Xs(e,t,n){let r=n;for(let i=t.length-1;i>=0;--i){let o=t[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let a=[];a[o]=r,r=a}else r=new Map([[o,r]])}return bw.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 Su=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Qs=class extends Rw.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=>pt.isNode(r)||pt.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Su(t))this.add(n);else{let[r,...i]=t,o=this.get(r,!0);if(pt.isCollection(o))o.addIn(i,n);else if(o===void 0&&this.schema)this.set(r,Xs(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(pt.isCollection(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...i]=t,o=this.get(r,!0);return i.length===0?!n&&pt.isScalar(o)?o.value:o:pt.isCollection(o)?o.getIn(i,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!pt.isPair(n))return!1;let r=n.value;return r==null||t&&pt.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 pt.isCollection(i)?i.hasIn(r):!1}setIn(t,n){let[r,...i]=t;if(i.length===0)this.set(r,n);else{let o=this.get(r,!0);if(pt.isCollection(o))o.setIn(i,n);else if(o===void 0&&this.schema)this.set(r,Xs(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};Bi.Collection=Qs;Bi.collectionFromPath=Xs;Bi.isEmptyPath=Su});var xr=_(Vi=>{"use strict";var Cw=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Zs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Sw=(e,t,n)=>e.endsWith(`
|
|
6
|
+
`)?Zs(n,t):n.includes(`
|
|
7
|
+
`)?`
|
|
8
|
+
`+Zs(n,t):(e.endsWith(" ")?"":" ")+n;Vi.indentComment=Zs;Vi.lineComment=Sw;Vi.stringifyComment=Cw});var xu=_(Ar=>{"use strict";var Ew="flow",ea="block",Ui="quoted";function xw(e,t,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:o=20,onFold:a,onOverflow:u}={}){if(!i||i<0)return e;i<o&&(o=0);let f=Math.max(1+o,1+i-t.length);if(e.length<=f)return e;let d=[],s={},l=i-t.length;typeof r=="number"&&(r>i-Math.max(2,o)?d.push(0):l=i-r);let m,c,p=!1,h=-1,g=-1,w=-1;n===ea&&(h=Eu(e,h,t.length),h!==-1&&(l=h+f));for(let k;k=e[h+=1];){if(n===Ui&&k==="\\"){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(k===`
|
|
9
|
+
`)n===ea&&(h=Eu(e,h,t.length)),l=h+t.length+f,m=void 0;else{if(k===" "&&c&&c!==" "&&c!==`
|
|
10
|
+
`&&c!==" "){let S=e[h+1];S&&S!==" "&&S!==`
|
|
11
|
+
`&&S!==" "&&(m=h)}if(h>=l)if(m)d.push(m),l=m+f,m=void 0;else if(n===Ui){for(;c===" "||c===" ";)c=k,k=e[h+=1],p=!0;let S=h>w+1?h-2:g-1;if(s[S])return e;d.push(S),s[S]=!0,l=S+f,m=void 0}else p=!0}c=k}if(p&&u&&u(),d.length===0)return e;a&&a();let v=e.slice(0,d[0]);for(let k=0;k<d.length;++k){let S=d[k],E=d[k+1]||e.length;S===0?v=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(n===Ui&&s[S]&&(v+=`${e[S]}\\`),v+=`
|
|
13
|
+
${t}${e.slice(S+1,E)}`)}return v}function Eu(e,t,n){let r=t,i=t+1,o=e[i];for(;o===" "||o===" ";)if(t<i+n)o=e[++t];else{do o=e[++t];while(o&&o!==`
|
|
14
|
+
`);r=t,i=t+1,o=e[i]}return r}Ar.FOLD_BLOCK=ea;Ar.FOLD_FLOW=Ew;Ar.FOLD_QUOTED=Ui;Ar.foldFlowLines=xw});var Or=_(Au=>{"use strict";var ot=de(),$t=xu(),Ki=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),zi=e=>/^(%|---|\.\.\.)/m.test(e);function Aw(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let o=0,a=0;o<i;++o)if(e[o]===`
|
|
15
|
+
`){if(o-a>r)return!0;if(a=o+1,i-a<=r)return!1}return!0}function Pr(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,o=t.indent||(zi(e)?" ":""),a="",u=0;for(let f=0,d=n[f];d;d=n[++f])if(d===" "&&n[f+1]==="\\"&&n[f+2]==="n"&&(a+=n.slice(u,f)+"\\ ",f+=1,u=f,d="\\"),d==="\\")switch(n[f+1]){case"u":{a+=n.slice(u,f);let s=n.substr(f+2,4);switch(s){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:s.substr(0,2)==="00"?a+="\\x"+s.substr(2):a+=n.substr(f,6)}f+=5,u=f+1}break;case"n":if(r||n[f+2]==='"'||n.length<i)f+=1;else{for(a+=n.slice(u,f)+`
|
|
16
|
+
|
|
17
|
+
`;n[f+2]==="\\"&&n[f+3]==="n"&&n[f+4]!=='"';)a+=`
|
|
18
|
+
`,f+=2;a+=o,n[f+2]===" "&&(a+="\\"),f+=1,u=f+1}break;default:f+=1}return a=u?a+n.slice(u):n,r?a:$t.foldFlowLines(a,o,$t.FOLD_QUOTED,Ki(t,!1))}function ta(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Pr(e,t);let n=t.indent||(zi(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${n}`)+"'";return t.implicitKey?r:$t.foldFlowLines(r,n,$t.FOLD_FLOW,Ki(t,!1))}function Bn(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Pr;else{let i=e.includes('"'),o=e.includes("'");i&&!o?r=ta:o&&!i?r=Pr:r=n?ta:Pr}return r(e,t)}var na;try{na=new RegExp(`(^|(?<!
|
|
21
|
+
))
|
|
22
|
+
+(?!
|
|
23
|
+
|$)`,"g")}catch{na=/\n+(?!\n|$)/g}function Ji({comment:e,type:t,value:n},r,i,o){let{blockQuote:a,commentString:u,lineWidth:f}=r.options;if(!a||/\n[\t ]+$/.test(n))return Bn(n,r);let d=r.indent||(r.forceBlockIndent||zi(n)?" ":""),s=a==="literal"?!0:a==="folded"||t===ot.Scalar.BLOCK_FOLDED?!1:t===ot.Scalar.BLOCK_LITERAL?!0:!Aw(n,f,d.length);if(!n)return s?`|
|
|
24
|
+
`:`>
|
|
25
|
+
`;let l,m;for(m=n.length;m>0;--m){let E=n[m-1];if(E!==`
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let c=n.substring(m),p=c.indexOf(`
|
|
27
|
+
`);p===-1?l="-":n===c||p!==c.length-1?(l="+",o&&o()):l="",c&&(n=n.slice(0,-c.length),c[c.length-1]===`
|
|
28
|
+
`&&(c=c.slice(0,-1)),c=c.replace(na,`$&${d}`));let h=!1,g,w=-1;for(g=0;g<n.length;++g){let E=n[g];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)w=g;else break}let v=n.substring(0,w<g?w+1:g);v&&(n=n.substring(v.length),v=v.replace(/\n+/g,`$&${d}`));let S=(h?d?"2":"1":"")+l;if(e&&(S+=" "+u(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!s){let E=n.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`),A=!1,M=Ki(r,!0);a!=="folded"&&t!==ot.Scalar.BLOCK_FOLDED&&(M.onOverflow=()=>{A=!0});let O=$t.foldFlowLines(`${v}${E}${c}`,d,$t.FOLD_BLOCK,M);if(!A)return`>${S}
|
|
31
|
+
${d}${O}`}return n=n.replace(/\n+/g,`$&${d}`),`|${S}
|
|
32
|
+
${d}${v}${n}${c}`}function Pw(e,t,n,r){let{type:i,value:o}=e,{actualString:a,implicitKey:u,indent:f,indentStep:d,inFlow:s}=t;if(u&&o.includes(`
|
|
33
|
+
`)||s&&/[[\]{},]/.test(o))return Bn(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return u||s||!o.includes(`
|
|
34
|
+
`)?Bn(o,t):Ji(e,t,n,r);if(!u&&!s&&i!==ot.Scalar.PLAIN&&o.includes(`
|
|
35
|
+
`))return Ji(e,t,n,r);if(zi(o)){if(f==="")return t.forceBlockIndent=!0,Ji(e,t,n,r);if(u&&f===d)return Bn(o,t)}let l=o.replace(/\n+/g,`$&
|
|
36
|
+
${f}`);if(a){let m=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(l),{compat:c,tags:p}=t.doc.schema;if(p.some(m)||c?.some(m))return Bn(o,t)}return u?l:$t.foldFlowLines(l,f,$t.FOLD_FLOW,Ki(t,!1))}function Ow(e,t,n,r){let{implicitKey:i,inFlow:o}=t,a=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:u}=e;u!==ot.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(a.value)&&(u=ot.Scalar.QUOTE_DOUBLE);let f=s=>{switch(s){case ot.Scalar.BLOCK_FOLDED:case ot.Scalar.BLOCK_LITERAL:return i||o?Bn(a.value,t):Ji(a,t,n,r);case ot.Scalar.QUOTE_DOUBLE:return Pr(a.value,t);case ot.Scalar.QUOTE_SINGLE:return ta(a.value,t);case ot.Scalar.PLAIN:return Pw(a,t,n,r);default:return null}},d=f(u);if(d===null){let{defaultKeyType:s,defaultStringType:l}=t.options,m=i&&s||l;if(d=f(m),d===null)throw new Error(`Unsupported default string type ${m}`)}return d}Au.stringifyString=Ow});var Ir=_(ra=>{"use strict";var Iw=Mi(),Mt=H(),_w=xr(),Nw=Or();function Tw(e,t){let n=Object.assign({blockQuote:!0,commentString:_w.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 jw(e,t){if(t.tag){let i=e.filter(o=>o.tag===t.tag);if(i.length>0)return i.find(o=>o.format===t.format)??i[0]}let n,r;if(Mt.isScalar(t)){r=t.value;let i=e.filter(o=>o.identify?.(r));if(i.length>1){let o=i.filter(a=>a.test);o.length>0&&(i=o)}n=i.find(o=>o.format===t.format)??i.find(o=>!o.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 Dw(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],o=(Mt.isScalar(e)||Mt.isCollection(e))&&e.anchor;o&&Iw.anchorIsValid(o)&&(n.add(o),i.push(`&${o}`));let a=e.tag??(t.default?null:t.tag);return a&&i.push(r.directives.tagString(a)),i.join(" ")}function Lw(e,t,n,r){if(Mt.isPair(e))return e.toString(t,n,r);if(Mt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,o=Mt.isNode(e)?e:t.doc.createNode(e,{onTagObj:f=>i=f});i??(i=jw(t.doc.schema.tags,o));let a=Dw(o,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart??0)+a.length+1);let u=typeof i.stringify=="function"?i.stringify(o,t,n,r):Mt.isScalar(o)?Nw.stringifyString(o,t,n,r):o.toString(t,n,r);return a?Mt.isScalar(o)||u[0]==="{"||u[0]==="["?`${a} ${u}`:`${a}
|
|
37
|
+
${t.indent}${u}`:u}ra.createStringifyContext=Tw;ra.stringify=Lw});var _u=_(Iu=>{"use strict";var Ct=H(),Pu=de(),Ou=Ir(),_r=xr();function qw({key:e,value:t},n,r,i){let{allNullValues:o,doc:a,indent:u,indentStep:f,options:{commentString:d,indentSeq:s,simpleKeys:l}}=n,m=Ct.isNode(e)&&e.comment||null;if(l){if(m)throw new Error("With simple keys, key nodes cannot have comments");if(Ct.isCollection(e)||!Ct.isNode(e)&&typeof e=="object"){let M="With simple keys, collection cannot be used as a key value";throw new Error(M)}}let c=!l&&(!e||m&&t==null&&!n.inFlow||Ct.isCollection(e)||(Ct.isScalar(e)?e.type===Pu.Scalar.BLOCK_FOLDED||e.type===Pu.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!c&&(l||!o),indent:u+f});let p=!1,h=!1,g=Ou.stringify(e,n,()=>p=!0,()=>h=!0);if(!c&&!n.inFlow&&g.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");c=!0}if(n.inFlow){if(o||t==null)return p&&r&&r(),g===""?"?":c?`? ${g}`:g}else if(o&&!l||t==null&&c)return g=`? ${g}`,m&&!p?g+=_r.lineComment(g,n.indent,d(m)):h&&i&&i(),g;p&&(m=null),c?(m&&(g+=_r.lineComment(g,n.indent,d(m))),g=`? ${g}
|
|
38
|
+
${u}:`):(g=`${g}:`,m&&(g+=_r.lineComment(g,n.indent,d(m))));let w,v,k;Ct.isNode(t)?(w=!!t.spaceBefore,v=t.commentBefore,k=t.comment):(w=!1,v=null,k=null,t&&typeof t=="object"&&(t=a.createNode(t))),n.implicitKey=!1,!c&&!m&&Ct.isScalar(t)&&(n.indentAtStart=g.length+1),h=!1,!s&&f.length>=2&&!n.inFlow&&!c&&Ct.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let S=!1,E=Ou.stringify(t,n,()=>S=!0,()=>h=!0),A=" ";if(m||w||v){if(A=w?`
|
|
39
|
+
`:"",v){let M=d(v);A+=`
|
|
40
|
+
${_r.indentComment(M,n.indent)}`}E===""&&!n.inFlow?A===`
|
|
41
|
+
`&&k&&(A=`
|
|
42
|
+
|
|
43
|
+
`):A+=`
|
|
44
|
+
${n.indent}`}else if(!c&&Ct.isCollection(t)){let M=E[0],O=E.indexOf(`
|
|
45
|
+
`),L=O!==-1,$=n.inFlow??t.flow??t.items.length===0;if(L||!$){let J=!1;if(L&&(M==="&"||M==="!")){let F=E.indexOf(" ");M==="&"&&F!==-1&&F<O&&E[F+1]==="!"&&(F=E.indexOf(" ",F+1)),(F===-1||O<F)&&(J=!0)}J||(A=`
|
|
46
|
+
${n.indent}`)}}else(E===""||E[0]===`
|
|
47
|
+
`)&&(A="");return g+=A+E,n.inFlow?S&&r&&r():k&&!S?g+=_r.lineComment(g,n.indent,d(k)):h&&i&&i(),g}Iu.stringifyPair=qw});var oa=_(ia=>{"use strict";var Nu=xi("process");function $w(e,...t){e==="debug"&&console.log(...t)}function Mw(e,t){(e==="debug"||e==="warn")&&(typeof Nu.emitWarning=="function"?Nu.emitWarning(t):console.warn(t))}ia.debug=$w;ia.warn=Mw});var Zi=_(Qi=>{"use strict";var Xi=H(),Tu=de(),Gi="<<",Yi={identify:e=>e===Gi||typeof e=="symbol"&&e.description===Gi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Tu.Scalar(Symbol(Gi)),{addToJSMap:ju}),stringify:()=>Gi},Ww=(e,t)=>(Yi.identify(t)||Xi.isScalar(t)&&(!t.type||t.type===Tu.Scalar.PLAIN)&&Yi.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Yi.tag&&n.default);function ju(e,t,n){let r=Du(e,n);if(Xi.isSeq(r))for(let i of r.items)sa(e,t,i);else if(Array.isArray(r))for(let i of r)sa(e,t,i);else sa(e,t,r)}function sa(e,t,n){let r=Du(e,n);if(!Xi.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,e,Map);for(let[o,a]of i)t instanceof Map?t.has(o)||t.set(o,a):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0});return t}function Du(e,t){return e&&Xi.isAlias(t)?t.resolve(e.doc,e):t}Qi.addMergeToJSMap=ju;Qi.isMergeKey=Ww;Qi.merge=Yi});var ca=_($u=>{"use strict";var Fw=oa(),Lu=Zi(),Bw=Ir(),qu=H(),aa=Lt();function Hw(e,t,{key:n,value:r}){if(qu.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Lu.isMergeKey(e,n))Lu.addMergeToJSMap(e,t,r);else{let i=aa.toJS(n,"",e);if(t instanceof Map)t.set(i,aa.toJS(r,i,e));else if(t instanceof Set)t.add(i);else{let o=Vw(n,i,e),a=aa.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:a,writable:!0,enumerable:!0,configurable:!0}):t[o]=a}}return t}function Vw(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(qu.isNode(e)&&n?.doc){let r=Bw.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),Fw.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(t)}$u.addPairToJSMap=Hw});var Wt=_(la=>{"use strict";var Mu=Er(),Uw=_u(),Jw=ca(),eo=H();function Kw(e,t,n){let r=Mu.createNode(e,void 0,n),i=Mu.createNode(t,void 0,n);return new to(r,i)}var to=class e{constructor(t,n=null){Object.defineProperty(this,eo.NODE_TYPE,{value:eo.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return eo.isNode(n)&&(n=n.clone(t)),eo.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return Jw.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?Uw.stringifyPair(this,t,n,r):JSON.stringify(this)}};la.Pair=to;la.createPair=Kw});var ua=_(Fu=>{"use strict";var fn=H(),Wu=Ir(),no=xr();function zw(e,t,n){return(t.inFlow??e.flow?Yw:Gw)(e,t,n)}function Gw({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:o,onChompKeep:a,onComment:u}){let{indent:f,options:{commentString:d}}=n,s=Object.assign({},n,{indent:o,type:null}),l=!1,m=[];for(let p=0;p<t.length;++p){let h=t[p],g=null;if(fn.isNode(h))!l&&h.spaceBefore&&m.push(""),ro(n,m,h.commentBefore,l),h.comment&&(g=h.comment);else if(fn.isPair(h)){let v=fn.isNode(h.key)?h.key:null;v&&(!l&&v.spaceBefore&&m.push(""),ro(n,m,v.commentBefore,l))}l=!1;let w=Wu.stringify(h,s,()=>g=null,()=>l=!0);g&&(w+=no.lineComment(w,o,d(g))),l&&g&&(l=!1),m.push(r+w)}let c;if(m.length===0)c=i.start+i.end;else{c=m[0];for(let p=1;p<m.length;++p){let h=m[p];c+=h?`
|
|
48
|
+
${f}${h}`:`
|
|
49
|
+
`}}return e?(c+=`
|
|
50
|
+
`+no.indentComment(d(e),f),u&&u()):l&&a&&a(),c}function Yw({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:o,flowCollectionPadding:a,options:{commentString:u}}=t;r+=o;let f=Object.assign({},t,{indent:r,inFlow:!0,type:null}),d=!1,s=0,l=[];for(let p=0;p<e.length;++p){let h=e[p],g=null;if(fn.isNode(h))h.spaceBefore&&l.push(""),ro(t,l,h.commentBefore,!1),h.comment&&(g=h.comment);else if(fn.isPair(h)){let v=fn.isNode(h.key)?h.key:null;v&&(v.spaceBefore&&l.push(""),ro(t,l,v.commentBefore,!1),v.comment&&(d=!0));let k=fn.isNode(h.value)?h.value:null;k?(k.comment&&(g=k.comment),k.commentBefore&&(d=!0)):h.value==null&&v?.comment&&(g=v.comment)}g&&(d=!0);let w=Wu.stringify(h,f,()=>g=null);d||(d=l.length>s||w.includes(`
|
|
51
|
+
`)),p<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=l.reduce((v,k)=>v+k.length+2,2)+(w.length+2)>t.options.lineWidth)),d&&(w+=",")),g&&(w+=no.lineComment(w,r,u(g))),l.push(w),s=l.length}let{start:m,end:c}=n;if(l.length===0)return m+c;if(!d){let p=l.reduce((h,g)=>h+g.length+2,2);d=t.options.lineWidth>0&&p>t.options.lineWidth}if(d){let p=m;for(let h of l)p+=h?`
|
|
52
|
+
${o}${i}${h}`:`
|
|
53
|
+
`;return`${p}
|
|
54
|
+
${i}${c}`}else return`${m}${a}${l.join(" ")}${a}${c}`}function ro({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let o=no.indentComment(t(r),e);n.push(o.trimStart())}}Fu.stringifyCollection=zw});var Bt=_(fa=>{"use strict";var Xw=ua(),Qw=ca(),Zw=Hi(),Ft=H(),io=Wt(),ey=de();function Nr(e,t){let n=Ft.isScalar(t)?t.value:t;for(let r of e)if(Ft.isPair(r)&&(r.key===t||r.key===n||Ft.isScalar(r.key)&&r.key.value===n))return r}var da=class extends Zw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ft.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:i,replacer:o}=r,a=new this(t),u=(f,d)=>{if(typeof o=="function")d=o.call(n,f,d);else if(Array.isArray(o)&&!o.includes(f))return;(d!==void 0||i)&&a.items.push(io.createPair(f,d,r))};if(n instanceof Map)for(let[f,d]of n)u(f,d);else if(n&&typeof n=="object")for(let f of Object.keys(n))u(f,n[f]);return typeof t.sortMapEntries=="function"&&a.items.sort(t.sortMapEntries),a}add(t,n){let r;Ft.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new io.Pair(t,t?.value):r=new io.Pair(t.key,t.value);let i=Nr(this.items,r.key),o=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${r.key} already set`);Ft.isScalar(i.value)&&ey.isScalarValue(r.value)?i.value.value=r.value:i.value=r.value}else if(o){let a=this.items.findIndex(u=>o(r,u)<0);a===-1?this.items.push(r):this.items.splice(a,0,r)}else this.items.push(r)}delete(t){let n=Nr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let i=Nr(this.items,t)?.value;return(!n&&Ft.isScalar(i)?i.value:i)??void 0}has(t){return!!Nr(this.items,t)}set(t,n){this.add(new io.Pair(t,n),!0)}toJSON(t,n,r){let i=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(i);for(let o of this.items)Qw.addPairToJSMap(n,i,o);return i}toString(t,n,r){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Ft.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})),Xw.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};fa.YAMLMap=da;fa.findPair=Nr});var Hn=_(Hu=>{"use strict";var ty=H(),Bu=Bt(),ny={collection:"map",default:!0,nodeClass:Bu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ty.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>Bu.YAMLMap.from(e,t,n)};Hu.map=ny});var Ht=_(Vu=>{"use strict";var ry=Er(),iy=ua(),oy=Hi(),so=H(),sy=de(),ay=Lt(),pa=class extends oy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(so.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=oo(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=oo(t);if(typeof r!="number")return;let i=this.items[r];return!n&&so.isScalar(i)?i.value:i}has(t){let n=oo(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=oo(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[r];so.isScalar(i)&&sy.isScalarValue(n)?i.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let i=0;for(let o of this.items)r.push(ay.toJS(o,String(i++),n));return r}toString(t,n,r){return t?iy.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,o=new this(t);if(n&&Symbol.iterator in Object(n)){let a=0;for(let u of n){if(typeof i=="function"){let f=n instanceof Set?u:String(a++);u=i.call(n,f,u)}o.items.push(ry.createNode(u,void 0,r))}}return o}};function oo(e){let t=so.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Vu.YAMLSeq=pa});var Vn=_(Ju=>{"use strict";var cy=H(),Uu=Ht(),ly={collection:"seq",default:!0,nodeClass:Uu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return cy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>Uu.YAMLSeq.from(e,t,n)};Ju.seq=ly});var Tr=_(Ku=>{"use strict";var uy=Or(),dy={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),uy.stringifyString(e,t,n,r)}};Ku.string=dy});var ao=_(Yu=>{"use strict";var zu=de(),Gu={identify:e=>e==null,createNode:()=>new zu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Gu.test.test(e)?e:t.options.nullStr};Yu.nullTag=Gu});var ma=_(Qu=>{"use strict";var fy=de(),Xu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new fy.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&Xu.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};Qu.boolTag=Xu});var Un=_(Zu=>{"use strict";function py({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 o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let a=o.indexOf(".");a<0&&(a=o.length,o+=".");let u=t-(o.length-a-1);for(;u-- >0;)o+="0"}return o}Zu.stringifyNumber=py});var ga=_(co=>{"use strict";var my=de(),ha=Un(),hy={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:ha.stringifyNumber},gy={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():ha.stringifyNumber(e)}},wy={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 my.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:ha.stringifyNumber};co.float=wy;co.floatExp=gy;co.floatNaN=hy});var ya=_(uo=>{"use strict";var ed=Un(),lo=e=>typeof e=="bigint"||Number.isInteger(e),wa=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function td(e,t,n){let{value:r}=e;return lo(r)&&r>=0?n+r.toString(t):ed.stringifyNumber(e)}var yy={identify:e=>lo(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>wa(e,2,8,n),stringify:e=>td(e,8,"0o")},vy={identify:lo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>wa(e,0,10,n),stringify:ed.stringifyNumber},ky={identify:e=>lo(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>wa(e,2,16,n),stringify:e=>td(e,16,"0x")};uo.int=vy;uo.intHex=ky;uo.intOct=yy});var rd=_(nd=>{"use strict";var by=Hn(),Ry=ao(),Cy=Vn(),Sy=Tr(),Ey=ma(),va=ga(),ka=ya(),xy=[by.map,Cy.seq,Sy.string,Ry.nullTag,Ey.boolTag,ka.intOct,ka.int,ka.intHex,va.floatNaN,va.floatExp,va.float];nd.schema=xy});var sd=_(od=>{"use strict";var Ay=de(),Py=Hn(),Oy=Vn();function id(e){return typeof e=="bigint"||Number.isInteger(e)}var fo=({value:e})=>JSON.stringify(e),Iy=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:fo},{identify:e=>e==null,createNode:()=>new Ay.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:fo},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:fo},{identify:id,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})=>id(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:fo}],_y={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Ny=[Py.map,Oy.seq].concat(Iy,_y);od.schema=Ny});var Ra=_(ad=>{"use strict";var jr=xi("buffer"),ba=de(),Ty=Or(),jy={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof jr.Buffer=="function")return jr.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,o){if(!n)return"";let a=n,u;if(typeof jr.Buffer=="function")u=a instanceof jr.Buffer?a.toString("base64"):jr.Buffer.from(a.buffer).toString("base64");else if(typeof btoa=="function"){let f="";for(let d=0;d<a.length;++d)f+=String.fromCharCode(a[d]);u=btoa(f)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=ba.Scalar.BLOCK_LITERAL),t!==ba.Scalar.QUOTE_DOUBLE){let f=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),d=Math.ceil(u.length/f),s=new Array(d);for(let l=0,m=0;l<d;++l,m+=f)s[l]=u.substr(m,f);u=s.join(t===ba.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Ty.stringifyString({comment:e,type:t,value:u},r,i,o)}};ad.binary=jy});var ho=_(mo=>{"use strict";var po=H(),Ca=Wt(),Dy=de(),Ly=Ht();function cd(e,t){if(po.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!po.isPair(r)){if(po.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let i=r.items[0]||new Ca.Pair(new Dy.Scalar(null));if(r.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${r.commentBefore}
|
|
56
|
+
${i.key.commentBefore}`:r.commentBefore),r.comment){let o=i.value??i.key;o.comment=o.comment?`${r.comment}
|
|
57
|
+
${o.comment}`:r.comment}r=i}e.items[n]=po.isPair(r)?r:new Ca.Pair(r)}}else t("Expected a sequence for this tag");return e}function ld(e,t,n){let{replacer:r}=n,i=new Ly.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let a of t){typeof r=="function"&&(a=r.call(t,String(o++),a));let u,f;if(Array.isArray(a))if(a.length===2)u=a[0],f=a[1];else throw new TypeError(`Expected [key, value] tuple: ${a}`);else if(a&&a instanceof Object){let d=Object.keys(a);if(d.length===1)u=d[0],f=a[u];else throw new TypeError(`Expected tuple with one key, not ${d.length} keys`)}else u=a;i.items.push(Ca.createPair(u,f,n))}return i}var qy={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:cd,createNode:ld};mo.createPairs=ld;mo.pairs=qy;mo.resolvePairs=cd});var xa=_(Ea=>{"use strict";var ud=H(),Sa=Lt(),Dr=Bt(),$y=Ht(),dd=ho(),pn=class e extends $y.YAMLSeq{constructor(){super(),this.add=Dr.YAMLMap.prototype.add.bind(this),this.delete=Dr.YAMLMap.prototype.delete.bind(this),this.get=Dr.YAMLMap.prototype.get.bind(this),this.has=Dr.YAMLMap.prototype.has.bind(this),this.set=Dr.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 o,a;if(ud.isPair(i)?(o=Sa.toJS(i.key,"",n),a=Sa.toJS(i.value,o,n)):o=Sa.toJS(i,"",n),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,a)}return r}static from(t,n,r){let i=dd.createPairs(t,n,r),o=new this;return o.items=i.items,o}};pn.tag="tag:yaml.org,2002:omap";var My={collection:"seq",identify:e=>e instanceof Map,nodeClass:pn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=dd.resolvePairs(e,t),r=[];for(let{key:i}of n.items)ud.isScalar(i)&&(r.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new pn,n)},createNode:(e,t,n)=>pn.from(e,t,n)};Ea.YAMLOMap=pn;Ea.omap=My});var gd=_(Aa=>{"use strict";var fd=de();function pd({value:e,source:t},n){return t&&(e?md:hd).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var md={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 fd.Scalar(!0),stringify:pd},hd={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 fd.Scalar(!1),stringify:pd};Aa.falseTag=hd;Aa.trueTag=md});var wd=_(go=>{"use strict";var Wy=de(),Pa=Un(),Fy={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:Pa.stringifyNumber},By={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():Pa.stringifyNumber(e)}},Hy={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 Wy.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:Pa.stringifyNumber};go.float=Hy;go.floatExp=By;go.floatNaN=Fy});var vd=_(qr=>{"use strict";var yd=Un(),Lr=e=>typeof e=="bigint"||Number.isInteger(e);function wo(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 a=BigInt(e);return i==="-"?BigInt(-1)*a:a}let o=parseInt(e,n);return i==="-"?-1*o:o}function Oa(e,t,n){let{value:r}=e;if(Lr(r)){let i=r.toString(t);return r<0?"-"+n+i.substr(1):n+i}return yd.stringifyNumber(e)}var Vy={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>wo(e,2,2,n),stringify:e=>Oa(e,2,"0b")},Uy={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>wo(e,1,8,n),stringify:e=>Oa(e,8,"0")},Jy={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>wo(e,0,10,n),stringify:yd.stringifyNumber},Ky={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>wo(e,2,16,n),stringify:e=>Oa(e,16,"0x")};qr.int=Jy;qr.intBin=Vy;qr.intHex=Ky;qr.intOct=Uy});var _a=_(Ia=>{"use strict";var ko=H(),yo=Wt(),vo=Bt(),mn=class e extends vo.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;ko.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new yo.Pair(t.key,null):n=new yo.Pair(t,null),vo.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=vo.findPair(this.items,t);return!n&&ko.isPair(r)?ko.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=vo.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new yo.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,o=new this(t);if(n&&Symbol.iterator in Object(n))for(let a of n)typeof i=="function"&&(a=i.call(n,a,a)),o.items.push(yo.createPair(a,null,r));return o}};mn.tag="tag:yaml.org,2002:set";var zy={collection:"map",identify:e=>e instanceof Set,nodeClass:mn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>mn.from(e,t,n),resolve(e,t){if(ko.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new mn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ia.YAMLSet=mn;Ia.set=zy});var Ta=_(bo=>{"use strict";var Gy=Un();function Na(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,i=a=>t?BigInt(a):Number(a),o=r.replace(/_/g,"").split(":").reduce((a,u)=>a*i(60)+i(u),i(0));return n==="-"?i(-1)*o:o}function kd(e){let{value:t}=e,n=a=>a;if(typeof t=="bigint")n=a=>BigInt(a);else if(isNaN(t)||!isFinite(t))return Gy.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let i=n(60),o=[t%i];return t<60?o.unshift(0):(t=(t-o[0])/i,o.unshift(t%i),t>=60&&(t=(t-o[0])/i,o.unshift(t))),r+o.map(a=>String(a).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Yy={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})=>Na(e,n),stringify:kd},Xy={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=>Na(e,!1),stringify:kd},bd={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(bd.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,i,o,a,u]=t.map(Number),f=t[7]?Number((t[7]+"00").substr(1,3)):0,d=Date.UTC(n,r-1,i,o||0,a||0,u||0,f),s=t[8];if(s&&s!=="Z"){let l=Na(s,!1);Math.abs(l)<30&&(l*=60),d-=6e4*l}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};bo.floatTime=Xy;bo.intTime=Yy;bo.timestamp=bd});var Sd=_(Cd=>{"use strict";var Qy=Hn(),Zy=ao(),ev=Vn(),tv=Tr(),nv=Ra(),Rd=gd(),ja=wd(),Ro=vd(),rv=Zi(),iv=xa(),ov=ho(),sv=_a(),Da=Ta(),av=[Qy.map,ev.seq,tv.string,Zy.nullTag,Rd.trueTag,Rd.falseTag,Ro.intBin,Ro.intOct,Ro.int,Ro.intHex,ja.floatNaN,ja.floatExp,ja.float,nv.binary,rv.merge,iv.omap,ov.pairs,sv.set,Da.intTime,Da.floatTime,Da.timestamp];Cd.schema=av});var jd=_($a=>{"use strict";var Pd=Hn(),cv=ao(),Od=Vn(),lv=Tr(),uv=ma(),La=ga(),qa=ya(),dv=rd(),fv=sd(),Id=Ra(),$r=Zi(),_d=xa(),Nd=ho(),Ed=Sd(),Td=_a(),Co=Ta(),xd=new Map([["core",dv.schema],["failsafe",[Pd.map,Od.seq,lv.string]],["json",fv.schema],["yaml11",Ed.schema],["yaml-1.1",Ed.schema]]),Ad={binary:Id.binary,bool:uv.boolTag,float:La.float,floatExp:La.floatExp,floatNaN:La.floatNaN,floatTime:Co.floatTime,int:qa.int,intHex:qa.intHex,intOct:qa.intOct,intTime:Co.intTime,map:Pd.map,merge:$r.merge,null:cv.nullTag,omap:_d.omap,pairs:Nd.pairs,seq:Od.seq,set:Td.set,timestamp:Co.timestamp},pv={"tag:yaml.org,2002:binary":Id.binary,"tag:yaml.org,2002:merge":$r.merge,"tag:yaml.org,2002:omap":_d.omap,"tag:yaml.org,2002:pairs":Nd.pairs,"tag:yaml.org,2002:set":Td.set,"tag:yaml.org,2002:timestamp":Co.timestamp};function mv(e,t,n){let r=xd.get(t);if(r&&!e)return n&&!r.includes($r.merge)?r.concat($r.merge):r.slice();let i=r;if(!i)if(Array.isArray(e))i=[];else{let o=Array.from(xd.keys()).filter(a=>a!=="yaml11").map(a=>JSON.stringify(a)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)i=i.concat(o);else typeof e=="function"&&(i=e(i.slice()));return n&&(i=i.concat($r.merge)),i.reduce((o,a)=>{let u=typeof a=="string"?Ad[a]:a;if(!u){let f=JSON.stringify(a),d=Object.keys(Ad).map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown custom tag ${f}; use one of ${d}`)}return o.includes(u)||o.push(u),o},[])}$a.coreKnownTags=pv;$a.getTags=mv});var Fa=_(Dd=>{"use strict";var Ma=H(),hv=Hn(),gv=Vn(),wv=Tr(),So=jd(),yv=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Wa=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:i,schema:o,sortMapEntries:a,toStringDefaults:u}){this.compat=Array.isArray(t)?So.getTags(t,"compat"):t?So.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?So.coreKnownTags:{},this.tags=So.getTags(n,this.name,r),this.toStringOptions=u??null,Object.defineProperty(this,Ma.MAP,{value:hv.map}),Object.defineProperty(this,Ma.SCALAR,{value:wv.string}),Object.defineProperty(this,Ma.SEQ,{value:gv.seq}),this.sortMapEntries=typeof a=="function"?a:a===!0?yv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Dd.Schema=Wa});var qd=_(Ld=>{"use strict";var vv=H(),Ba=Ir(),Mr=xr();function kv(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let f=e.directives.toString(e);f?(n.push(f),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let i=Ba.createStringifyContext(e,t),{commentString:o}=i.options;if(e.commentBefore){n.length!==1&&n.unshift("");let f=o(e.commentBefore);n.unshift(Mr.indentComment(f,""))}let a=!1,u=null;if(e.contents){if(vv.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let s=o(e.contents.commentBefore);n.push(Mr.indentComment(s,""))}i.forceBlockIndent=!!e.comment,u=e.contents.comment}let f=u?void 0:()=>a=!0,d=Ba.stringify(e.contents,i,()=>u=null,f);u&&(d+=Mr.lineComment(d,"",o(u))),(d[0]==="|"||d[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${d}`:n.push(d)}else n.push(Ba.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let f=o(e.comment);f.includes(`
|
|
58
|
+
`)?(n.push("..."),n.push(Mr.indentComment(f,""))):n.push(`... ${f}`)}else n.push("...");else{let f=e.comment;f&&a&&(f=f.replace(/^\n+/,"")),f&&((!a||u)&&n[n.length-1]!==""&&n.push(""),n.push(Mr.indentComment(o(f),"")))}return n.join(`
|
|
59
|
+
`)+`
|
|
60
|
+
`}Ld.stringifyDocument=kv});var Wr=_($d=>{"use strict";var bv=Sr(),Jn=Hi(),Ge=H(),Rv=Wt(),Cv=Lt(),Sv=Fa(),Ev=qd(),Ha=Mi(),xv=Ks(),Av=Er(),Va=Js(),Ua=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ge.NODE_TYPE,{value:Ge.DOC});let i=null;typeof n=="function"||Array.isArray(n)?i=n:r===void 0&&n&&(r=n,n=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:a}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new Va.Directives({version:a}),this.setSchema(a,r),this.contents=t===void 0?null:this.createNode(t,i,r)}clone(){let t=Object.create(e.prototype,{[Ge.NODE_TYPE]:{value:Ge.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=Ge.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Kn(this.contents)&&this.contents.add(t)}addIn(t,n){Kn(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Ha.anchorNames(this);t.anchor=!n||r.has(n)?Ha.findNewAnchor(n||"a",r):n}return new bv.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=v=>typeof v=="number"||v instanceof String||v 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:o,anchorPrefix:a,flow:u,keepUndefined:f,onTagObj:d,tag:s}=r??{},{onAnchor:l,setAnchors:m,sourceObjects:c}=Ha.createNodeAnchors(this,a||"a"),p={aliasDuplicateObjects:o??!0,keepUndefined:f??!1,onAnchor:l,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:c},h=Av.createNode(t,s,p);return u&&Ge.isCollection(h)&&(h.flow=!0),m(),h}createPair(t,n,r={}){let i=this.createNode(t,null,r),o=this.createNode(n,null,r);return new Rv.Pair(i,o)}delete(t){return Kn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Jn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Kn(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return Ge.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return Jn.isEmptyPath(t)?!n&&Ge.isScalar(this.contents)?this.contents.value:this.contents:Ge.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return Ge.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Jn.isEmptyPath(t)?this.contents!==void 0:Ge.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=Jn.collectionFromPath(this.schema,[t],n):Kn(this.contents)&&this.contents.set(t,n)}setIn(t,n){Jn.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=Jn.collectionFromPath(this.schema,Array.from(t),n):Kn(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 Va.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 Va.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 Sv.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:o,reviver:a}={}){let u={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},f=Cv.toJS(this.contents,n??"",u);if(typeof o=="function")for(let{count:d,res:s}of u.anchors.values())o(s,d);return typeof a=="function"?xv.applyReviver(a,{"":f},"",f):f}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 Ev.stringifyDocument(this,t)}};function Kn(e){if(Ge.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}$d.Document=Ua});var Hr=_(Br=>{"use strict";var Fr=class extends Error{constructor(t,n,r,i){super(),this.name=t,this.code=r,this.message=i,this.pos=n}},Ja=class extends Fr{constructor(t,n,r){super("YAMLParseError",t,n,r)}},Ka=class extends Fr{constructor(t,n,r){super("YAMLWarning",t,n,r)}},Pv=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(u=>t.linePos(u));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let o=i-1,a=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&a.length>80){let u=Math.min(o-39,a.length-79);a="…"+a.substring(u),o-=u-1}if(a.length>80&&(a=a.substring(0,79)+"…"),r>1&&/^ *$/.test(a.substring(0,o))){let u=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);u.length>80&&(u=u.substring(0,79)+`…
|
|
61
|
+
`),a=u+a}if(/[^ ]/.test(a)){let u=1,f=n.linePos[1];f?.line===r&&f.col>i&&(u=Math.max(1,Math.min(f.col-i,80-o)));let d=" ".repeat(o)+"^".repeat(u);n.message+=`:
|
|
62
|
+
|
|
63
|
+
${a}
|
|
64
|
+
${d}
|
|
65
|
+
`}};Br.YAMLError=Fr;Br.YAMLParseError=Ja;Br.YAMLWarning=Ka;Br.prettifyError=Pv});var Vr=_(Md=>{"use strict";function Ov(e,{flow:t,indicator:n,next:r,offset:i,onError:o,parentIndent:a,startOnNewline:u}){let f=!1,d=u,s=u,l="",m="",c=!1,p=!1,h=null,g=null,w=null,v=null,k=null,S=null,E=null;for(let O of e)switch(p&&(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma"&&o(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p=!1),h&&(d&&O.type!=="comment"&&O.type!=="newline"&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),O.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&O.source.includes(" ")&&(h=O),s=!0;break;case"comment":{s||o(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=O.source.substring(1)||" ";l?l+=m+L:l=L,m="",d=!1;break}case"newline":d?l?l+=O.source:(!S||n!=="seq-item-ind")&&(f=!0):m+=O.source,d=!0,c=!0,(g||w)&&(v=O),s=!0;break;case"anchor":g&&o(O,"MULTIPLE_ANCHORS","A node can have at most one anchor"),O.source.endsWith(":")&&o(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=O,E??(E=O.offset),d=!1,s=!1,p=!0;break;case"tag":{w&&o(O,"MULTIPLE_TAGS","A node can have at most one tag"),w=O,E??(E=O.offset),d=!1,s=!1,p=!0;break}case n:(g||w)&&o(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`),S&&o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${t??"collection"}`),S=O,d=n==="seq-item-ind"||n==="explicit-key-ind",s=!1;break;case"comma":if(t){k&&o(O,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=O,d=!1,s=!1;break}default:o(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),d=!1,s=!1}let A=e[e.length-1],M=A?A.offset+A.source.length:i;return p&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(d&&h.indent<=a||r?.type==="block-map"||r?.type==="block-seq")&&o(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:f,comment:l,hasNewline:c,anchor:g,tag:w,newlineAfterProp:v,end:M,start:E??M}}Md.resolveProps=Ov});var Eo=_(Wd=>{"use strict";function za(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(za(t.key)||za(t.value))return!0}return!1;default:return!0}}Wd.containsNewline=za});var Ga=_(Fd=>{"use strict";var Iv=Eo();function _v(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Iv.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Fd.flowIndentCheck=_v});var Ya=_(Hd=>{"use strict";var Bd=H();function Nv(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r=="function"?r:(o,a)=>o===a||Bd.isScalar(o)&&Bd.isScalar(a)&&o.value===a.value;return t.some(o=>i(o.key,n))}Hd.mapIncludes=Nv});var Gd=_(zd=>{"use strict";var Vd=Wt(),Tv=Bt(),Ud=Vr(),jv=Eo(),Jd=Ga(),Dv=Ya(),Kd="All mapping items must start at the same column";function Lv({composeNode:e,composeEmptyNode:t},n,r,i,o){let a=o?.nodeClass??Tv.YAMLMap,u=new a(n.schema);n.atRoot&&(n.atRoot=!1);let f=r.offset,d=null;for(let s of r.items){let{start:l,key:m,sep:c,value:p}=s,h=Ud.resolveProps(l,{indicator:"explicit-key-ind",next:m??c?.[0],offset:f,onError:i,parentIndent:r.indent,startOnNewline:!0}),g=!h.found;if(g){if(m&&(m.type==="block-seq"?i(f,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in m&&m.indent!==r.indent&&i(f,"BAD_INDENT",Kd)),!h.anchor&&!h.tag&&!c){d=h.end,h.comment&&(u.comment?u.comment+=`
|
|
67
|
+
`+h.comment:u.comment=h.comment);continue}(h.newlineAfterProp||jv.containsNewline(m))&&i(m??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&i(f,"BAD_INDENT",Kd);n.atKey=!0;let w=h.end,v=m?e(n,m,h,i):t(n,w,l,null,h,i);n.schema.compat&&Jd.flowIndentCheck(r.indent,m,i),n.atKey=!1,Dv.mapIncludes(n,u.items,v)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let k=Ud.resolveProps(c??[],{indicator:"map-value-ind",next:p,offset:v.range[2],onError:i,parentIndent:r.indent,startOnNewline:!m||m.type==="block-scalar"});if(f=k.end,k.found){g&&(p?.type==="block-map"&&!k.hasNewline&&i(f,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&h.start<k.found.offset-1024&&i(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=p?e(n,p,k,i):t(n,f,c,null,k,i);n.schema.compat&&Jd.flowIndentCheck(r.indent,p,i),f=S.range[2];let E=new Vd.Pair(v,S);n.options.keepSourceTokens&&(E.srcToken=s),u.items.push(E)}else{g&&i(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(v.comment?v.comment+=`
|
|
68
|
+
`+k.comment:v.comment=k.comment);let S=new Vd.Pair(v);n.options.keepSourceTokens&&(S.srcToken=s),u.items.push(S)}}return d&&d<f&&i(d,"IMPOSSIBLE","Map comment with trailing content"),u.range=[r.offset,f,d??f],u}zd.resolveBlockMap=Lv});var Xd=_(Yd=>{"use strict";var qv=Ht(),$v=Vr(),Mv=Ga();function Wv({composeNode:e,composeEmptyNode:t},n,r,i,o){let a=o?.nodeClass??qv.YAMLSeq,u=new a(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let f=r.offset,d=null;for(let{start:s,value:l}of r.items){let m=$v.resolveProps(s,{indicator:"seq-item-ind",next:l,offset:f,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!m.found)if(m.anchor||m.tag||l)l?.type==="block-seq"?i(m.end,"BAD_INDENT","All sequence items must start at the same column"):i(f,"MISSING_CHAR","Sequence item without - indicator");else{d=m.end,m.comment&&(u.comment=m.comment);continue}let c=l?e(n,l,m,i):t(n,m.end,s,null,m,i);n.schema.compat&&Mv.flowIndentCheck(r.indent,l,i),f=c.range[2],u.items.push(c)}return u.range=[r.offset,f,d??f],u}Yd.resolveBlockSeq=Wv});var zn=_(Qd=>{"use strict";function Fv(e,t,n,r){let i="";if(e){let o=!1,a="";for(let u of e){let{source:f,type:d}=u;switch(d){case"space":o=!0;break;case"comment":{n&&!o&&r(u,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let s=f.substring(1)||" ";i?i+=a+s:i=s,a="";break}case"newline":i&&(a+=f),o=!0;break;default:r(u,"UNEXPECTED_TOKEN",`Unexpected ${d} at node end`)}t+=f.length}}return{comment:i,offset:t}}Qd.resolveEnd=Fv});var nf=_(tf=>{"use strict";var Bv=H(),Hv=Wt(),Zd=Bt(),Vv=Ht(),Uv=zn(),ef=Vr(),Jv=Eo(),Kv=Ya(),Xa="Block collections are not allowed within flow collections",Qa=e=>e&&(e.type==="block-map"||e.type==="block-seq");function zv({composeNode:e,composeEmptyNode:t},n,r,i,o){let a=r.start.source==="{",u=a?"flow map":"flow sequence",f=o?.nodeClass??(a?Zd.YAMLMap:Vv.YAMLSeq),d=new f(n.schema);d.flow=!0;let s=n.atRoot;s&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let g=0;g<r.items.length;++g){let w=r.items[g],{start:v,key:k,sep:S,value:E}=w,A=ef.resolveProps(v,{flow:u,indicator:"explicit-key-ind",next:k??S?.[0],offset:l,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!A.found){if(!A.anchor&&!A.tag&&!S&&!E){g===0&&A.comma?i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${u}`):g<r.items.length-1&&i(A.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${u}`),A.comment&&(d.comment?d.comment+=`
|
|
69
|
+
`+A.comment:d.comment=A.comment),l=A.end;continue}!a&&n.options.strict&&Jv.containsNewline(k)&&i(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)A.comma&&i(A.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${u}`);else if(A.comma||i(A.start,"MISSING_CHAR",`Missing , between ${u} items`),A.comment){let M="";e:for(let O of v)switch(O.type){case"comma":case"space":break;case"comment":M=O.source.substring(1);break e;default:break e}if(M){let O=d.items[d.items.length-1];Bv.isPair(O)&&(O=O.value??O.key),O.comment?O.comment+=`
|
|
70
|
+
`+M:O.comment=M,A.comment=A.comment.substring(M.length+1)}}if(!a&&!S&&!A.found){let M=E?e(n,E,A,i):t(n,A.end,S,null,A,i);d.items.push(M),l=M.range[2],Qa(E)&&i(M.range,"BLOCK_IN_FLOW",Xa)}else{n.atKey=!0;let M=A.end,O=k?e(n,k,A,i):t(n,M,v,null,A,i);Qa(k)&&i(O.range,"BLOCK_IN_FLOW",Xa),n.atKey=!1;let L=ef.resolveProps(S??[],{flow:u,indicator:"map-value-ind",next:E,offset:O.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(L.found){if(!a&&!A.found&&n.options.strict){if(S)for(let F of S){if(F===L.found)break;if(F.type==="newline"){i(F,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}A.start<L.found.offset-1024&&i(L.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?i(E,"MISSING_CHAR",`Missing space after : in ${u}`):i(L.start,"MISSING_CHAR",`Missing , or : between ${u} items`));let $=E?e(n,E,L,i):L.found?t(n,L.end,S,null,L,i):null;$?Qa(E)&&i($.range,"BLOCK_IN_FLOW",Xa):L.comment&&(O.comment?O.comment+=`
|
|
71
|
+
`+L.comment:O.comment=L.comment);let J=new Hv.Pair(O,$);if(n.options.keepSourceTokens&&(J.srcToken=w),a){let F=d;Kv.mapIncludes(n,F.items,O)&&i(M,"DUPLICATE_KEY","Map keys must be unique"),F.items.push(J)}else{let F=new Zd.YAMLMap(n.schema);F.flow=!0,F.items.push(J);let re=($??O).range;F.range=[O.range[0],re[1],re[2]],d.items.push(F)}l=$?$.range[2]:L.end}}let m=a?"}":"]",[c,...p]=r.end,h=l;if(c?.source===m)h=c.offset+c.source.length;else{let g=u[0].toUpperCase()+u.substring(1),w=s?`${g} must end with a ${m}`:`${g} in block collection must be sufficiently indented and end with a ${m}`;i(l,s?"MISSING_CHAR":"BAD_INDENT",w),c&&c.source.length!==1&&p.unshift(c)}if(p.length>0){let g=Uv.resolveEnd(p,h,n.options.strict,i);g.comment&&(d.comment?d.comment+=`
|
|
72
|
+
`+g.comment:d.comment=g.comment),d.range=[r.offset,h,g.offset]}else d.range=[r.offset,h,h];return d}tf.resolveFlowCollection=zv});var of=_(rf=>{"use strict";var Gv=H(),Yv=de(),Xv=Bt(),Qv=Ht(),Zv=Gd(),ek=Xd(),tk=nf();function Za(e,t,n,r,i,o){let a=n.type==="block-map"?Zv.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?ek.resolveBlockSeq(e,t,n,r,o):tk.resolveFlowCollection(e,t,n,r,o),u=a.constructor;return i==="!"||i===u.tagName?(a.tag=u.tagName,a):(i&&(a.tag=i),a)}function nk(e,t,n,r,i){let o=r.tag,a=o?t.directives.tagName(o.source,m=>i(o,"TAG_RESOLVE_FAILED",m)):null;if(n.type==="block-seq"){let{anchor:m,newlineAfterProp:c}=r,p=m&&o?m.offset>o.offset?m:o:m??o;p&&(!c||c.offset<p.offset)&&i(p,"MISSING_CHAR","Missing newline after block sequence props")}let u=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!o||!a||a==="!"||a===Xv.YAMLMap.tagName&&u==="map"||a===Qv.YAMLSeq.tagName&&u==="seq")return Za(e,t,n,i,a);let f=t.schema.tags.find(m=>m.tag===a&&m.collection===u);if(!f){let m=t.schema.knownTags[a];if(m?.collection===u)t.schema.tags.push(Object.assign({},m,{default:!1})),f=m;else return m?i(o,"BAD_COLLECTION_TYPE",`${m.tag} used for ${u} collection, but expects ${m.collection??"scalar"}`,!0):i(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${a}`,!0),Za(e,t,n,i,a)}let d=Za(e,t,n,i,a,f),s=f.resolve?.(d,m=>i(o,"TAG_RESOLVE_FAILED",m),t.options)??d,l=Gv.isNode(s)?s:new Yv.Scalar(s);return l.range=d.range,l.tag=a,f?.format&&(l.format=f.format),l}rf.composeCollection=nk});var tc=_(sf=>{"use strict";var ec=de();function rk(e,t,n){let r=t.offset,i=ik(t,e.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let o=i.mode===">"?ec.Scalar.BLOCK_FOLDED:ec.Scalar.BLOCK_LITERAL,a=t.source?ok(t.source):[],u=a.length;for(let h=a.length-1;h>=0;--h){let g=a[h][1];if(g===""||g==="\r")u=h;else break}if(u===0){let h=i.chomp==="+"&&a.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,a.length-1)):"",g=r+i.length;return t.source&&(g+=t.source.length),{value:h,type:o,comment:i.comment,range:[r,g,g]}}let f=t.indent+i.indent,d=t.offset+i.length,s=0;for(let h=0;h<u;++h){let[g,w]=a[h];if(w===""||w==="\r")i.indent===0&&g.length>f&&(f=g.length);else{g.length<f&&n(d+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(f=g.length),s=h,f===0&&!e.atRoot&&n(d,"BAD_INDENT","Block scalar values in collections must be indented");break}d+=g.length+w.length+1}for(let h=a.length-1;h>=u;--h)a[h][0].length>f&&(u=h+1);let l="",m="",c=!1;for(let h=0;h<s;++h)l+=a[h][0].slice(f)+`
|
|
74
|
+
`;for(let h=s;h<u;++h){let[g,w]=a[h];d+=g.length+w.length+1;let v=w[w.length-1]==="\r";if(v&&(w=w.slice(0,-1)),w&&g.length<f){let S=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;n(d-w.length-(v?2:1),"BAD_INDENT",S),g=""}o===ec.Scalar.BLOCK_LITERAL?(l+=m+g.slice(f)+w,m=`
|
|
75
|
+
`):g.length>f||w[0]===" "?(m===" "?m=`
|
|
76
|
+
`:!c&&m===`
|
|
77
|
+
`&&(m=`
|
|
78
|
+
|
|
79
|
+
`),l+=m+g.slice(f)+w,m=`
|
|
80
|
+
`,c=!0):w===""?m===`
|
|
81
|
+
`?l+=`
|
|
82
|
+
`:m=`
|
|
83
|
+
`:(l+=m+w,m=" ",c=!1)}switch(i.chomp){case"-":break;case"+":for(let h=u;h<a.length;++h)l+=`
|
|
84
|
+
`+a[h][0].slice(f);l[l.length-1]!==`
|
|
85
|
+
`&&(l+=`
|
|
86
|
+
`);break;default:l+=`
|
|
87
|
+
`}let p=r+i.length+t.source.length;return{value:l,type:o,comment:i.comment,range:[r,p,p]}}function ik({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],o=i[0],a=0,u="",f=-1;for(let m=1;m<i.length;++m){let c=i[m];if(!u&&(c==="-"||c==="+"))u=c;else{let p=Number(c);!a&&p?a=p:f===-1&&(f=e+m)}}f!==-1&&r(f,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let d=!1,s="",l=i.length;for(let m=1;m<t.length;++m){let c=t[m];switch(c.type){case"space":d=!0;case"newline":l+=c.source.length;break;case"comment":n&&!d&&r(c,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=c.source.length,s=c.source.substring(1);break;case"error":r(c,"UNEXPECTED_TOKEN",c.message),l+=c.source.length;break;default:{let p=`Unexpected token in block scalar header: ${c.type}`;r(c,"UNEXPECTED_TOKEN",p);let h=c.source;h&&typeof h=="string"&&(l+=h.length)}}}return{mode:o,indent:a,chomp:u,comment:s,length:l}}function ok(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),o=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let a=1;a<t.length;a+=2)o.push([t[a],t[a+1]]);return o}sf.resolveBlockScalar=rk});var rc=_(cf=>{"use strict";var nc=de(),sk=zn();function ak(e,t,n){let{offset:r,type:i,source:o,end:a}=e,u,f,d=(m,c,p)=>n(r+m,c,p);switch(i){case"scalar":u=nc.Scalar.PLAIN,f=ck(o,d);break;case"single-quoted-scalar":u=nc.Scalar.QUOTE_SINGLE,f=lk(o,d);break;case"double-quoted-scalar":u=nc.Scalar.QUOTE_DOUBLE,f=uk(o,d);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let s=r+o.length,l=sk.resolveEnd(a,s,t,n);return{value:f,type:u,comment:l.comment,range:[r,s,l.offset]}}function ck(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}`),af(e)}function lk(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),af(e.slice(1,-1)).replace(/''/g,"'")}function af(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],o=" ",a=t.lastIndex;for(n.lastIndex=a;r=n.exec(e);)r[1]===""?o===`
|
|
90
|
+
`?i+=o:o=`
|
|
91
|
+
`:(i+=o+r[1],o=" "),a=n.lastIndex;let u=/[ \t]*(.*)/sy;return u.lastIndex=a,r=u.exec(e),i+o+(r?.[1]??"")}function uk(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:o,offset:a}=dk(e,r);n+=o,r=a}else if(i==="\\"){let o=e[++r],a=fk[o];if(a)n+=a;else if(o===`
|
|
94
|
+
`)for(o=e[r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="\r"&&e[r+1]===`
|
|
95
|
+
`)for(o=e[++r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="x"||o==="u"||o==="U"){let u=o==="x"?2:o==="u"?4:8;n+=pk(e,r+1,u,t),r+=u}else{let u=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${u}`),n+=u}}else if(i===" "||i===" "){let o=r,a=e[r+1];for(;a===" "||a===" ";)a=e[++r+1];a!==`
|
|
96
|
+
`&&!(a==="\r"&&e[r+2]===`
|
|
97
|
+
`)&&(n+=r>o?e.slice(o,r+1):i)}else n+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function dk(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 fk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function pk(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let u=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${u}`),u}}cf.resolveFlowScalar=ak});var df=_(uf=>{"use strict";var hn=H(),lf=de(),mk=tc(),hk=rc();function gk(e,t,n,r){let{value:i,type:o,comment:a,range:u}=t.type==="block-scalar"?mk.resolveBlockScalar(e,t,r):hk.resolveFlowScalar(t,e.options.strict,r),f=n?e.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,d;e.options.stringKeys&&e.atKey?d=e.schema[hn.SCALAR]:f?d=wk(e.schema,i,f,n,r):t.type==="scalar"?d=yk(e,i,t,r):d=e.schema[hn.SCALAR];let s;try{let l=d.resolve(i,m=>r(n??t,"TAG_RESOLVE_FAILED",m),e.options);s=hn.isScalar(l)?l:new lf.Scalar(l)}catch(l){let m=l instanceof Error?l.message:String(l);r(n??t,"TAG_RESOLVE_FAILED",m),s=new lf.Scalar(i)}return s.range=u,s.source=i,o&&(s.type=o),f&&(s.tag=f),d.format&&(s.format=d.format),a&&(s.comment=a),s}function wk(e,t,n,r,i){if(n==="!")return e[hn.SCALAR];let o=[];for(let u of e.tags)if(!u.collection&&u.tag===n)if(u.default&&u.test)o.push(u);else return u;for(let u of o)if(u.test?.test(t))return u;let a=e.knownTags[n];return a&&!a.collection?(e.tags.push(Object.assign({},a,{default:!1,test:void 0})),a):(i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[hn.SCALAR])}function yk({atKey:e,directives:t,schema:n},r,i,o){let a=n.tags.find(u=>(u.default===!0||e&&u.default==="key")&&u.test?.test(r))||n[hn.SCALAR];if(n.compat){let u=n.compat.find(f=>f.default&&f.test?.test(r))??n[hn.SCALAR];if(a.tag!==u.tag){let f=t.tagString(a.tag),d=t.tagString(u.tag),s=`Value may be parsed as either ${f} or ${d}`;o(i,"TAG_RESOLVE_FAILED",s,!0)}}return a}uf.composeScalar=gk});var pf=_(ff=>{"use strict";function vk(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}ff.emptyScalarPosition=vk});var gf=_(oc=>{"use strict";var kk=Sr(),bk=H(),Rk=of(),mf=df(),Ck=zn(),Sk=pf(),Ek={composeNode:hf,composeEmptyNode:ic};function hf(e,t,n,r){let i=e.atKey,{spaceBefore:o,comment:a,anchor:u,tag:f}=n,d,s=!0;switch(t.type){case"alias":d=xk(e,t,r),(u||f)&&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":d=mf.composeScalar(e,t,f,r),u&&(d.anchor=u.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{d=Rk.composeCollection(Ek,e,t,n,r),u&&(d.anchor=u.source.substring(1))}catch(l){let m=l instanceof Error?l.message:String(l);r(t,"RESOURCE_EXHAUSTION",m)}break;default:{let l=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",l),s=!1}}return d??(d=ic(e,t.offset,void 0,null,n,r)),u&&d.anchor===""&&r(u,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!bk.isScalar(d)||typeof d.value!="string"||d.tag&&d.tag!=="tag:yaml.org,2002:str")&&r(f??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(d.spaceBefore=!0),a&&(t.type==="scalar"&&t.source===""?d.comment=a:d.commentBefore=a),e.options.keepSourceTokens&&s&&(d.srcToken=t),d}function ic(e,t,n,r,{spaceBefore:i,comment:o,anchor:a,tag:u,end:f},d){let s={type:"scalar",offset:Sk.emptyScalarPosition(t,n,r),indent:-1,source:""},l=mf.composeScalar(e,s,u,d);return a&&(l.anchor=a.source.substring(1),l.anchor===""&&d(a,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(l.spaceBefore=!0),o&&(l.comment=o,l.range[2]=f),l}function xk({options:e},{offset:t,source:n,end:r},i){let o=new kk.Alias(n.substring(1));o.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&i(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let a=t+n.length,u=Ck.resolveEnd(r,a,e.strict,i);return o.range=[t,a,u.offset],u.comment&&(o.comment=u.comment),o}oc.composeEmptyNode=ic;oc.composeNode=hf});var vf=_(yf=>{"use strict";var Ak=Wr(),wf=gf(),Pk=zn(),Ok=Vr();function Ik(e,t,{offset:n,start:r,value:i,end:o},a){let u=Object.assign({_directives:t},e),f=new Ak.Document(void 0,u),d={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},s=Ok.resolveProps(r,{indicator:"doc-start",next:i??o?.[0],offset:n,onError:a,parentIndent:0,startOnNewline:!0});s.found&&(f.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!s.hasNewline&&a(s.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),f.contents=i?wf.composeNode(d,i,s,a):wf.composeEmptyNode(d,s.end,r,null,s,a);let l=f.contents.range[2],m=Pk.resolveEnd(o,l,!1,a);return m.comment&&(f.comment=m.comment),f.range=[n,l,m.offset],f}yf.composeDoc=Ik});var ac=_(Rf=>{"use strict";var _k=xi("process"),Nk=Js(),Tk=Wr(),Ur=Hr(),kf=H(),jk=vf(),Dk=zn();function Jr(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 bf(e){let t="",n=!1,r=!1;for(let i=0;i<e.length;++i){let o=e[i];switch(o[0]){case"#":t+=(t===""?"":r?`
|
|
103
|
+
|
|
104
|
+
`:`
|
|
105
|
+
`)+(o.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 sc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,i,o)=>{let a=Jr(n);o?this.warnings.push(new Ur.YAMLWarning(a,r,i)):this.errors.push(new Ur.YAMLParseError(a,r,i))},this.directives=new Nk.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:i}=bf(this.prelude);if(r){let o=t.contents;if(n)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(i||t.directives.docStart||!o)t.commentBefore=r;else if(kf.isCollection(o)&&!o.flow&&o.items.length>0){let a=o.items[0];kf.isPair(a)&&(a=a.key);let u=a.commentBefore;a.commentBefore=u?`${r}
|
|
107
|
+
${u}`:r}else{let a=o.commentBefore;o.commentBefore=a?`${r}
|
|
108
|
+
${a}`:r}}if(n){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:bf(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(_k.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,i)=>{let o=Jr(t);o[0]+=n,this.onError(o,"BAD_DIRECTIVE",r,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=jk.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 Ur.YAMLParseError(Jr(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 Ur.YAMLParseError(Jr(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Dk.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 Ur.YAMLParseError(Jr(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 Tk.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}}};Rf.Composer=sc});var Ef=_(xo=>{"use strict";var Lk=tc(),qk=rc(),$k=Hr(),Cf=Or();function Mk(e,t=!0,n){if(e){let r=(i,o,a)=>{let u=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(n)n(u,o,a);else throw new $k.YAMLParseError([u,u+1],o,a)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return qk.resolveFlowScalar(e,t,r);case"block-scalar":return Lk.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Wk(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:o=-1,type:a="PLAIN"}=t,u=Cf.stringifyString({type:a,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),f=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
|
+
`}];switch(u[0]){case"|":case">":{let d=u.indexOf(`
|
|
111
|
+
`),s=u.substring(0,d),l=u.substring(d+1)+`
|
|
112
|
+
`,m=[{type:"block-scalar-header",offset:o,indent:r,source:s}];return Sf(m,f)||m.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:o,indent:r,props:m,source:l}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:u,end:f};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:u,end:f};default:return{type:"scalar",offset:o,indent:r,source:u,end:f}}}function Fk(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:o=!1,type:a}=n,u="indent"in e?e.indent:null;if(r&&typeof u=="number"&&(u+=2),!a)switch(e.type){case"single-quoted-scalar":a="QUOTE_SINGLE";break;case"double-quoted-scalar":a="QUOTE_DOUBLE";break;case"block-scalar":{let d=e.props[0];if(d.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a=d.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:a="PLAIN"}let f=Cf.stringifyString({type:a,value:t},{implicitKey:i||u===null,indent:u!==null&&u>0?" ".repeat(u):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(f[0]){case"|":case">":Bk(e,f);break;case'"':cc(e,f,"double-quoted-scalar");break;case"'":cc(e,f,"single-quoted-scalar");break;default:cc(e,f,"scalar")}}function Bk(e,t){let n=t.indexOf(`
|
|
114
|
+
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,e.source=i}else{let{offset:o}=e,a="indent"in e?e.indent:-1,u=[{type:"block-scalar-header",offset:o,indent:a,source:r}];Sf(u,"end"in e?e.end:void 0)||u.push({type:"newline",offset:-1,indent:a,source:`
|
|
116
|
+
`});for(let f of Object.keys(e))f!=="type"&&f!=="offset"&&delete e[f];Object.assign(e,{type:"block-scalar",indent:a,props:u,source:i})}}function Sf(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 cc(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 o of r)o.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(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}xo.createScalarToken=Wk;xo.resolveAsScalar=Mk;xo.setScalarValue=Fk});var Af=_(xf=>{"use strict";var Hk=e=>"type"in e?Po(e):Ao(e);function Po(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=Po(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Ao(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Ao(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Ao(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 Ao({start:e,key:t,sep:n,value:r}){let i="";for(let o of e)i+=o.source;if(t&&(i+=Po(t)),n)for(let o of n)i+=o.source;return r&&(i+=Po(r)),i}xf.stringify=Hk});var _f=_(If=>{"use strict";var lc=Symbol("break visit"),Vk=Symbol("skip children"),Pf=Symbol("remove item");function gn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Of(Object.freeze([]),e,t)}gn.BREAK=lc;gn.SKIP=Vk;gn.REMOVE=Pf;gn.itemAtPath=(e,t)=>{let n=e;for(let[r,i]of t){let o=n?.[r];if(o&&"items"in o)n=o.items[i];else return}return n};gn.parentCollection=(e,t)=>{let n=gn.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 Of(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let i of["key","value"]){let o=t[i];if(o&&"items"in o){for(let a=0;a<o.items.length;++a){let u=Of(Object.freeze(e.concat([[i,a]])),o.items[a],n);if(typeof u=="number")a=u-1;else{if(u===lc)return lc;u===Pf&&(o.items.splice(a,1),a-=1)}}typeof r=="function"&&i==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}If.visit=gn});var Oo=_(Me=>{"use strict";var uc=Ef(),Uk=Af(),Jk=_f(),dc="\uFEFF",fc="",pc="",mc="",Kk=e=>!!e&&"items"in e,zk=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Gk(e){switch(e){case dc:return"<BOM>";case fc:return"<DOC>";case pc:return"<FLOW_END>";case mc:return"<SCALAR>";default:return JSON.stringify(e)}}function Yk(e){switch(e){case dc:return"byte-order-mark";case fc:return"doc-mode";case pc:return"flow-error-end";case mc: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}Me.createScalarToken=uc.createScalarToken;Me.resolveAsScalar=uc.resolveAsScalar;Me.setScalarValue=uc.setScalarValue;Me.stringify=Uk.stringify;Me.visit=Jk.visit;Me.BOM=dc;Me.DOCUMENT=fc;Me.FLOW_END=pc;Me.SCALAR=mc;Me.isCollection=Kk;Me.isScalar=zk;Me.prettyToken=Gk;Me.tokenType=Yk});var wc=_(Tf=>{"use strict";var Kr=Oo();function st(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Nf=new Set("0123456789ABCDEFabcdef"),Xk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Io=new Set(",[]{}"),Qk=new Set(` ,[]{}
|
|
121
|
+
\r `),hc=e=>!e||Qk.has(e),gc=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==="...")&&st(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]===Kr.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let o=t[r-1];if(o===" "||o===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let o=t[n-1];if(o===" "||o===" ")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 Kr.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==="...")&&st(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&&!st(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===":")&&st(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(hc),"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("..."))&&st(i[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Kr.FLOW_END,yield*this.parseLineStart();let o=0;for(;i[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),i[o]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(hc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let a=this.charAt(1);if(this.flowKey||st(a)||a===",")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 o=0;for(;this.buffer[n-1-o]==="\\";)o+=1;if(o%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 o=this.continueScalar(i+1);if(o===-1)break;i=r.indexOf(`
|
|
128
|
+
`,o)}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=>st(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let o=this.pos;r=this.buffer[o];++o)switch(r){case" ":n+=1;break;case`
|
|
129
|
+
`:t=o,n=0;break;case"\r":{let a=this.buffer[o+1];if(!a&&!this.atEnd)return this.setNext("block-scalar");if(a===`
|
|
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 o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(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 o=t-1,a=this.buffer[o];a==="\r"&&(a=this.buffer[--o]);let u=o;for(;a===" ";)a=this.buffer[--o];if(a===`
|
|
133
|
+
`&&o>=this.pos&&o+1+n>u)t=o;else break}while(!0);return yield Kr.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 o=this.buffer[r+1];if(st(o)||t&&Io.has(o))break;n=r}else if(st(i)){let o=this.buffer[r+1];if(i==="\r"&&(o===`
|
|
134
|
+
`?(r+=1,i=`
|
|
135
|
+
`,o=this.buffer[r+1]):n=r),o==="#"||t&&Io.has(o))break;if(i===`
|
|
136
|
+
`){let a=this.continueScalar(r+1);if(a===-1)break;r=Math.max(r,a-2)}}else{if(t&&Io.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Kr.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(hc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(st(r)||n&&Io.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(;!st(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(Xk.has(n))n=this.buffer[++t];else if(n==="%"&&Nf.has(this.buffer[t+1])&&Nf.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)}};Tf.Lexer=gc});var vc=_(jf=>{"use strict";var yc=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 o=n+r>>1;this.lineStarts[o]<t?n=o+1:r=o}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}}}};jf.LineCounter=yc});var bc=_(Mf=>{"use strict";var Zk=xi("process"),Df=Oo(),eb=wc();function Vt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Lf(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 $f(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 _o(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 Gn(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 No(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 qf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Vt(t.start,"explicit-key-ind")&&!Vt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,$f(t.value)?t.value.end?No(t.value.end,t.sep):t.value.end=t.sep:No(t.start,t.sep),delete t.sep)}var kc=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 eb.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,Zk.env.LOG_TOKENS&&console.log("|",Df.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=Df.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"&&qf(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&&Lf(i.start)===-1&&(n.indent===0||i.start.every(o=>o.type!=="comment"||o.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":{Lf(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=_o(this.peek(2)),r=Gn(n),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let 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)){No(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",o=[];if(i&&n.sep&&!n.value){let a=[];for(let u=0;u<n.sep.length;++u){let f=n.sep[u];switch(f.type){case"newline":a.push(u);break;case"space":break;case"comment":f.indent>t.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=n.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":i||n.value?(o.push(this.sourceToken),t.items.push({start:o}),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?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Vt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if($f(n.key)&&!Vt(n.sep,"newline")){let a=Gn(n.start),u=n.key,f=n.sep;f.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:u,sep:f}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(Vt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let a=Gn(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||i?t.items.push({start:o,key:null,sep:[this.sourceToken]}):Vt(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 a=this.flowScalar(this.type);i||n.value?(t.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(a):(Object.assign(n,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(t);if(a){if(a.type==="block-seq"){if(!n.explicitKey&&n.sep&&!Vt(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:o});this.stack.push(a);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)){No(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||Vt(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=_o(r),o=Gn(i);qf(t);let a=t.end.splice(1,t.end.length);a.push(this.sourceToken);let u={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:a}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=u}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=_o(t),r=Gn(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=_o(t),r=Gn(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())}}};Mf.Parser=kc});var Vf=_(Gr=>{"use strict";var Wf=ac(),tb=Wr(),zr=Hr(),nb=oa(),rb=H(),ib=vc(),Ff=bc();function Bf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new ib.LineCounter||null,prettyErrors:t}}function ob(e,t={}){let{lineCounter:n,prettyErrors:r}=Bf(t),i=new Ff.Parser(n?.addNewLine),o=new Wf.Composer(t),a=Array.from(o.compose(i.parse(e)));if(r&&n)for(let u of a)u.errors.forEach(zr.prettifyError(e,n)),u.warnings.forEach(zr.prettifyError(e,n));return a.length>0?a:Object.assign([],{empty:!0},o.streamInfo())}function Hf(e,t={}){let{lineCounter:n,prettyErrors:r}=Bf(t),i=new Ff.Parser(n?.addNewLine),o=new Wf.Composer(t),a=null;for(let u of o.compose(i.parse(e),!0,e.length))if(!a)a=u;else if(a.options.logLevel!=="silent"){a.errors.push(new zr.YAMLParseError(u.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(a.errors.forEach(zr.prettifyError(e,n)),a.warnings.forEach(zr.prettifyError(e,n))),a}function sb(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let i=Hf(e,n);if(!i)return null;if(i.warnings.forEach(o=>nb.warn(i.options.logLevel,o)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function ab(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 rb.isDocument(e)&&!r?e.toString(n):new tb.Document(e,r,n).toString(n)}Gr.parse=sb;Gr.parseAllDocuments=ob;Gr.parseDocument=Hf;Gr.stringify=ab});var We=_(G=>{"use strict";var cb=ac(),lb=Wr(),ub=Fa(),Rc=Hr(),db=Sr(),Ut=H(),fb=Wt(),pb=de(),mb=Bt(),hb=Ht(),gb=Oo(),wb=wc(),yb=vc(),vb=bc(),To=Vf(),Uf=kr();G.Composer=cb.Composer;G.Document=lb.Document;G.Schema=ub.Schema;G.YAMLError=Rc.YAMLError;G.YAMLParseError=Rc.YAMLParseError;G.YAMLWarning=Rc.YAMLWarning;G.Alias=db.Alias;G.isAlias=Ut.isAlias;G.isCollection=Ut.isCollection;G.isDocument=Ut.isDocument;G.isMap=Ut.isMap;G.isNode=Ut.isNode;G.isPair=Ut.isPair;G.isScalar=Ut.isScalar;G.isSeq=Ut.isSeq;G.Pair=fb.Pair;G.Scalar=pb.Scalar;G.YAMLMap=mb.YAMLMap;G.YAMLSeq=hb.YAMLSeq;G.CST=gb;G.Lexer=wb.Lexer;G.LineCounter=yb.LineCounter;G.Parser=vb.Parser;G.parse=To.parse;G.parseAllDocuments=To.parseAllDocuments;G.parseDocument=To.parseDocument;G.stringify=To.stringify;G.visit=Uf.visit;G.visitAsync=Uf.visitAsync});import Jt from"path";function Sb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim();if(n.length===0||Jt.posix.isAbsolute(n)||Jt.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 jo(e){let t=Sb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Qf(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 _e(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||Jt.posix.isAbsolute(r)||Jt.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(o=>o===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(o=>o===""||o==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function Kt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Zf(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 Eb(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 Xf(e,t,n){let r=Eb(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 xb(e){if(e===void 0)return;let t=Kt(e,"native.pending_root_move"),n=t.id,r=t.from_artifact_root,i=t.to_artifact_root,o=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(o!=="copying"&&o!=="ready"&&o!=="switched")throw new Error("native.pending_root_move.stage is invalid");let a;if(t.cleanup!==void 0){let u=Kt(t.cleanup,"native.pending_root_move.cleanup"),f=u.kind,d=u.state,s=u.manifest_hash;if(f!=="forward-source"&&f!=="restart-staging"&&f!=="rollback-destination"&&f!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(d!=="prepared"&&d!=="quarantined"&&d!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof s!="string"||!/^[a-f0-9]{64}$/u.test(s))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");a={kind:f,state:d,manifestHash:s}}return{id:n,fromArtifactRoot:jo(r),toArtifactRoot:jo(i),stage:o,...a?{cleanup:a}:{}}}function Ab(e){if(e===void 0)return;let t=Kt(e,"native.finish");if(t.pull_request===void 0)return{};let n=Kt(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((o,a)=>{if(typeof o!="string"||o.trim().length===0||o.length>4096||/[\0\r\n]/u.test(o))throw new Error(`native.finish.pull_request.command[${a}] must be a non-empty single-line string of at most 4096 characters`);return o});if(Jt.posix.isAbsolute(r[0])||Jt.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??Cb;if(!Number.isSafeInteger(i)||i<1||i>Yf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Yf}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:i}}}function Pb(e,t={}){let n=Kt(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 o=n.archive_confirmation??"automatic";if(o!=="automatic"&&o!=="required")throw new Error("native.archive_confirmation must be automatic or required");let a=n.max_verify_failures??kb;if(!Number.isSafeInteger(a)||a<1)throw new Error("native.max_verify_failures must be a positive integer");let u=n.max_parallel_children===void 0?bb:n.max_parallel_children;if(!Number.isSafeInteger(u)||u<1)throw new Error("native.max_parallel_children must be a positive integer");let f=n.document_writes??"allow";if(f!=="allow"&&f!=="revert")throw new Error("native.document_writes must be allow or revert");let d=xb(n.pending_root_move),s=Ab(n.finish);return{artifact_root:jo(r),language:Zf(n.language,"en","native.language"),clarification_mode:i,archive_confirmation:o,max_verify_failures:a,max_parallel_children:u,...f==="revert"?{document_writes:f}:{},...s?{finish:s}:{},...d?{pending_root_move:d}:{}}}function Ob(e,t){if(!Number.isSafeInteger(e)||Number(e)<1||Number(e)>Gf)throw new Error(`${t} must be an integer between 1 and ${Gf} milliseconds`);return e}function Ib(e){let t=Kt(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&&Ob(t.check_timeout_ms,"classic.check_timeout_ms");let o=t.document_evidence??"neutral";if(o!=="neutral"&&o!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Qf(t.artifact_layout),language:Zf(t.language,"zh-CN","classic.language"),context_compression:n,review_mode:r,auto_transition:i,...o==="strict"?{document_evidence:o}:{},...t.check_timeout_ms!==void 0?{check_timeout_ms:t.check_timeout_ms}:{}}}function _b(e){let n=Kt(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)=>_e(r,`hook.allow_paths[${i}]`)))]}}function Nb(e){if(e===void 0)return{...Cc};let t=Kt(e,"memory"),n=t.learning??Cc.learning,r=t.retrieval??Cc.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 Sc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Tb(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")||Jt.posix.isAbsolute(n)||Jt.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>Jf)throw new Error(`${t} exceeds ${Jf} 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>Kf)throw new Error(`${t} contains more than ${Kf} wildcard tokens`);return n}function jb(e){let t=Sc(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,o)=>Tb(i,`knowledge.local.include[${o}]`)))],max_file_mb:Xf(t.max_file_mb,zf.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Xf(t.max_total_mb,zf.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 Db(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 Lb(e){let t=Sc(e,"knowledge.remote"),n=Db(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 o=t.timeout_ms??5e3;if(typeof o!="number"||!Number.isSafeInteger(o)||o<100||o>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:n,...r===void 0?{}:{token_env:r},...i===void 0?{}:{scope:i},timeout_ms:o}}function qb(e){if(e===void 0)return{...Rb};let t=Sc(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:jb(t.local);if(n==="local")return{provider:n,...r?{local:r}:{}};let i=t.remote===void 0?void 0:Lb(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 ep(e){if(e===void 0)return!0;if(typeof e!="boolean")throw new Error("change_walkthrough must be true or false");return e}function $b(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Mb(e,t,n,r,i,o,a,u){let f=e.schema!==void 0;if(!(f||e.default_workflow!==void 0||e.workflows!==void 0||!u.allowPartialProject&&e.native!==void 0)||u.allowPartialProject&&!f)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 s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(m=>m!=="native"&&m!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(s)];if(!l.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:l,ambient_resume:a,change_walkthrough:ep(e.change_walkthrough),...t?{hook:t}:{},memory:n,knowledge:r,...i?{native:i}:{},...o?{classic:o}:{}}}function tp(e){let t=(0,Ye.parseDocument)(e),n=r=>{let i=(0,Ye.isAlias)(r)?r.resolve(t):r;return(0,Ye.isScalar)(i)?i.value:void 0};return(0,Ye.isMap)(t.contents)&&t.contents.items.some(({key:r,value:i})=>n(r)==="schema"&&n(i)==="comet.project.v1")}function yn(e,t={}){let n=(0,Ye.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,o=$b(i.ambient_resume),a=ep(i.change_walkthrough),u=i.hook===void 0?void 0:_b(i.hook),f=Nb(i.memory),d=qb(i.knowledge),s=i.native===void 0?void 0:Pb(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),l=i.classic===void 0?void 0:Ib(i.classic),m=Mb(i,u,f,d,s,l,o,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:m,ambient_resume:o,change_walkthrough:a,memory:f,knowledge:d,...u?{hook:u}:{},...s?{native:s}:{},...l?{classic:l}:{}}}var Ye,wn,Jf,Kf,kb,bb,Cc,zf,Rb,Gf,Cb,Yf,Ue=ne(()=>{"use strict";Ye=De(We(),1),wn=Number.MAX_SAFE_INTEGER,Jf=1024,Kf=64,kb=5,bb=2,Cc={learning:!0,retrieval:!0},zf={include:[],max_file_mb:1,max_total_mb:32},Rb={provider:"local"},Gf=36e5,Cb=12e4,Yf=6e5});import{promises as Fe}from"fs";import Y from"path";import{AsyncLocalStorage as Wb}from"node:async_hooks";async function Yr(e,t,n={}){let r=Y.resolve(e),i=await xc(r,t),o=new Map,a=!1,u=m=>[m.dev,m.ino,m.mode,m.birthtimeNs,m.mtimeNs,m.ctimeNs].join(":"),f=m=>[m.dev,m.ino,m.mode,m.birthtimeNs].join(":"),d=async(m,c)=>JSON.stringify((await Fe.readdir(m,{withFileTypes:!0})).filter(p=>!c(p)).map(p=>[p.name,p.isDirectory(),p.isSymbolicLink()]).sort((p,h)=>String(p[0]).localeCompare(String(h[0]),"en"))),s=m=>{let c=o.get(m);return c||(c=(async()=>{let p=await Fe.lstat(m,{bigint:!0});if(!p.isDirectory()||p.isSymbolicLink())throw new Error(`${t} crosses a symbolic link, junction or invalid directory at ${Y.relative(r,m)||"."}`);let h=await Fe.realpath(m);if(!Yn(i,h))throw new Error(`${t} resolves outside the project root`);let g=n.ignoredDirectoryEntries?.(Y.relative(r,m).replaceAll("\\","/")||".");return{stat:p,real:h,...g?{ignoreEntry:g,namespace:await d(m,g)}:{}}})(),c=c.catch(p=>{throw o.delete(m),p}),o.set(m,c)),c};await s(r);let l=async m=>{if(a)throw new Error(`${t} read session is already finished`);let c=_e(m,t),p=r;for(let h of c.split("/").slice(0,-1))p=Y.join(p,h),await s(p);return Y.resolve(r,...c.split("/"))};return{observePath:l,async observeDirectory(m){let c=await l(m);return await s(c),c},async stat(m){let c=await l(m),p=await Fe.lstat(c,{bigint:!0});if(!p.isFile()||p.isSymbolicLink())throw new Error(`${t} must be a real file: ${m}`);return{target:c,stat:p}},async hash(m){let c=await l(m);return Kl(c,{bigint:!0,label:`${t} ${m}`,verify:async(p,h)=>{if(!Yn(i,h.realPath))throw new Error(`${t} resolves outside the project root`);let g=r,w=[r];for(let v of Y.relative(r,Y.dirname(c)).split(Y.sep).filter(Boolean))g=Y.join(g,v),w.push(g);for(let v of w){let k=await o.get(v),S=await Fe.lstat(v,{bigint:!0});if(!S.isDirectory()||S.isSymbolicLink()||f(S)!==f(k.stat))throw new Error(`${t} directory changed while reading: ${Y.relative(r,v)||"."}`)}}})},async read(m,c,p={}){let h=await l(m);return an(h,c,{...p,label:`${t} ${m}`,verify:async(g,w)=>{if(!Yn(i,w.realPath))throw new Error(`${t} resolves outside the project root`);if(n.deferDirectoryChecks)return;let v=r,k=[r];for(let S of Y.relative(r,Y.dirname(h)).split(Y.sep).filter(Boolean))v=Y.join(v,S),k.push(v);for(let S of k){let E=await o.get(S),A=await Fe.lstat(S,{bigint:!0});if(!A.isDirectory()||A.isSymbolicLink()||f(A)!==f(E.stat))throw new Error(`${t} directory changed while reading: ${Y.relative(r,S)||"."}`)}}})},async finish(m={}){if(a)throw new Error(`${t} read session is already finished`);a=!0;let c=[];for(let[p,h]of o){let g=await h,w=await Fe.lstat(p,{bigint:!0});if(!w.isDirectory()||w.isSymbolicLink()||f(g.stat)!==f(w)||!m.allowDirectoryContentChanges&&u(g.stat)!==u(w)&&(!g.ignoreEntry||await d(p,g.ignoreEntry)!==g.namespace)||await Fe.realpath(p)!==g.real)throw new Error(`${t} directory changed while observing: ${Y.relative(r,p)||"."}`);u(g.stat)!==u(w)&&c.push(Y.relative(r,p).replaceAll("\\","/")||".")}return{changedDirectories:c}}}}function np(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Yn(e,t){let n=Y.relative(e,t);return n===""||!Y.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Y.sep}`)}async function xc(e,t){let n=Y.resolve(e),r=await rp(n);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ip(n)}async function op(e,t,n,r){let i=e;for(let o=0;o<n.length;o++){i=Y.join(i,n[o]);let a;try{a=await rp(i)}catch(d){if(np(d))return{exists:!1,kind:"missing"};throw d}if(a.isSymbolicLink()){let d=Y.relative(e,i).replaceAll("\\","/");throw new Error(`${r.label} crosses a symbolic link or junction at ${d}`)}let u=o===n.length-1;if(!u&&!a.isDirectory()){let d=Y.relative(e,i).replaceAll("\\","/");throw new Error(`${r.label} ancestor ${d} must be a real directory`)}if(u&&(r.expected==="file"&&!a.isFile()||r.expected==="directory"&&!a.isDirectory()||r.expected==="any"&&!a.isFile()&&!a.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let f=await ip(i);if(!Bb(t,f))throw new Error(`${r.label} resolves outside the project root`);if(u)return{exists:!0,kind:a.isFile()?"file":a.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function sp(e,t,n){let r=_e(t,n.label),i=Y.resolve(e),o=await xc(i,n.label),a=r.split("/"),u=Y.resolve(i,...a);if(!Yn(i,u))throw new Error(`${n.label} must stay inside the project root`);let f=await op(i,o,a,n);return{projectRoot:i,target:u,relative:r,exists:f.exists,kind:f.kind}}async function D(e,t,n){if(n.expected===void 0)return sp(e,t,n);try{return await Hb(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 Xe(e,t,n){let r=_e(t,n.label),i=Y.resolve(e),o=await xc(i,n.label),a=r.split("/"),u=i;for(let f of a){u=Y.join(u,f);let d;try{d=await Fe.lstat(u)}catch(m){if(!np(m))throw m;try{await Fe.mkdir(u)}catch(c){if(c.code!=="EEXIST")throw c}d=await Fe.lstat(u)}let s=Y.relative(i,u).replaceAll("\\","/");if(d.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);if(!d.isDirectory())throw new Error(`${n.label} directory ${s} must be a real directory`);let l=await Fe.realpath(u);if(!Yn(o,l))throw new Error(`${n.label} resolves outside the project root`)}return await op(i,o,a,{label:n.label,expected:"directory"}),u}async function Ac(e,t,n){return(await D(e,t,{...n,expected:"file"})).exists}async function ap(e,t,n,r){let i=!r.hooks&&!r.bigint?Fb.getStore():void 0;if(i){let u=Y.resolve(e),f=i.get(u);return f||(f=Yr(u,r.label,{deferDirectoryChecks:!0}).catch(d=>{throw i.delete(u),d}),i.set(u,f)),(await f).read(t,n,r)}let o=await Yr(e,r.label),a=await o.read(t,n,r);return await o.finish({allowDirectoryContentChanges:!0}),a}async function V(e,t,n,r){if(r.hooks||r.bigint)return ap(e,t,n,r);try{return await Vb(e,t,n)}catch(i){throw i instanceof Error&&i.message.includes(Ec)&&(i.message=i.message.replaceAll(Ec,r.label)),i}}var Fb,rp,ip,Bb,Hb,Ec,Vb,Q=ne(()=>{"use strict";cn();Ue();Ke();Fb=new Wb;rp=Re("protectedChainLstat",e=>Fe.lstat(e)),ip=Re("protectedChainRealpath",e=>Fe.realpath(e)),Bb=dt("protectedChainInside",Yn);Hb=Re("protectedInspectPath",(e,t,n)=>sp(e,t,{label:"Protected project path",expected:n}));Ec="Cached protected project read",Vb=Re("protectedReadFile",(e,t,n)=>ap(e,t,n,{label:Ec}))});import{createHash as Ub}from"crypto";function Jb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Qr(e,t={}){return(await Do(e,t)).document}async function Kb(e){try{return(await V(e,Xr,wn,{label:Xr})).bytes}catch(t){if(Jb(t))return null;throw t}}function zb(e){return e?{exists:!0,sha256:Ub("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Do(e,t={}){let n=await Kb(e);return{source:n?.toString("utf8")??null,document:n?yn(n.toString("utf8"),t):null,identity:zb(n)}}async function Pc(e){return(await Qr(e))?.config??null}var Xr,vn=ne(()=>{"use strict";Ue();Q();Xr=".comet/config.yaml"});import{promises as Ic}from"node:fs";async function _c(e,t){let n;for(let r=0;r<=Oc.length;r+=1)try{return await e()}catch(i){n=i;let o=i.code;if(r===Oc.length||!Gb.has(o??""))throw i;await new Promise(a=>setTimeout(a,Oc[r]))}throw n}async function cp(e,t){await _c(()=>Ic.rename(e,t),`rename ${t}`)}async function lp(e){await _c(()=>Ic.unlink(e),`unlink ${e}`)}async function Nc(e,t){await _c(()=>Ic.link(e,t),`link ${t}`)}var Gb,Oc,up=ne(()=>{"use strict";Gb=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Oc=[50,100,200]});import{randomUUID as Yb}from"crypto";import{constants as Xb,promises as ge}from"fs";import Ee from"path";async function Tc(e,t){try{return await Nc(e,t),{linked:!0}}catch(n){let r=n.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw n}return await ge.copyFile(e,t,Xb.COPYFILE_EXCL),{linked:!1}}function kn(e,t){let n=Ee.relative(e,t);return n===""||!Ee.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ee.sep}`)}function Lo(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function Qb(e,t){return ze(e,Lo(t))}function qo(e,t){return ze(Lo(e),Lo(t))}function dp(e,t){return qo(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function $o(e){let t=await ge.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 ge.realpath(e),...Lo(t)}}async function St(e){for(let t of e){let n=await ge.lstat(t.path);if(!n.isDirectory()||n.isSymbolicLink()||!Qb(t,n)||await ge.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function Zb(e,t,n){let[r,i]=await Promise.all([ge.lstat(e),ge.realpath(e),St(n)]);if(!r.isFile()||r.isSymbolicLink()||!qo(r,t)||!kn(n[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return r}async function eR(e,t){let n=await fp(e,t);if(n)return n;let r=Ee.resolve(e),i=Ee.resolve(t);if(!kn(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let o=[await $o(r)],a=Ee.relative(r,i).split(Ee.sep).filter(Boolean),u=r;for(let f of a){await St(o),u=Ee.join(u,f);try{await ge.mkdir(u)}catch(s){if(s.code!=="EEXIST")throw s}let d=await $o(u);if(!kn(o[0].realPath,d.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${u}`);o.push(d)}return await St(o),o}async function fp(e,t){let n=Ee.resolve(e),r=Ee.resolve(t);if(!kn(n,r))throw new Error(`Contained file parent is outside its managed root: ${t}`);let i=[await $o(n)],o=Ee.relative(n,r).split(Ee.sep).filter(Boolean),a=n;for(let u of o){a=Ee.join(a,u);try{let f=await $o(a);if(!kn(i[0].realPath,f.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${a}`);i.push(f)}catch(f){if(f.code==="ENOENT")return null;throw f}}return await St(i),i}async function pp(e){let t;try{t=await ge.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 tR(e,t,n){let r=Ee.dirname(e),i=await eR(n.containedRoot,r),o=Ee.join(r,`.${Ee.basename(e)}.${Yb()}.tmp`),a,u,f;try{await n.beforeTemporaryOpen?.(),a=await ge.open(o,"wx"),u=await a.stat();let[d,s]=await Promise.all([ge.lstat(o),ge.realpath(o)]);if(await St(i),!d.isFile()||d.isSymbolicLink()||!qo(u,d)||!kn(i[0].realPath,s))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await a.writeFile(t,"utf8"):await a.writeFile(t),await a.sync(),f=await a.stat(),!qo(u,f))throw new Error("Contained atomic write temporary file changed while writing");if(await a.close(),a=void 0,await n.afterTemporaryClose?.(),!f)throw new Error("Contained atomic write temporary file was not written");f=await Zb(o,f,i),await n.beforeCommit?.(),await St(i);let l=await ge.lstat(o);if(!l.isFile()||l.isSymbolicLink()||!f||!dp(l,f))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(n.requireAtomicPublication?await Nc(o,e):await Tc(o,e),await ge.unlink(o)):await cp(o,e),await pp(r)}catch(d){await a?.close();try{await St(i),await ge.rm(o,{force:!0})}catch{}throw d}}async function se(e,t,n){await tR(e,t,n)}async function mt(e,t){let n=Ee.dirname(e),r=await fp(t.containedRoot,n);if(!r)return!1;let i,o;try{i=await ge.lstat(e),o=await ge.realpath(e)}catch(f){if(f.code==="ENOENT")return!1;throw f}if(!i.isFile()||i.isSymbolicLink()||!kn(r[0].realPath,o))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await St(r);let[a,u]=await Promise.all([ge.lstat(e),ge.realpath(e)]);if(!a.isFile()||a.isSymbolicLink()||!dp(i,a)||u!==o)throw new Error("Contained file removal target changed before removal");return await lp(e),await St(r),await pp(n),!0}var Qe=ne(()=>{"use strict";up();yr()});var HP,jc=ne(()=>{"use strict";Qe();vn();Q();HP=Number.MAX_SAFE_INTEGER});var Lc=ne(()=>{"use strict";Qe();Ue();vn();Q();jc()});var Wo=ne(()=>{"use strict"});var yp=ne(()=>{"use strict"});var $c=ne(()=>{"use strict";Wo()});var vp=ne(()=>{"use strict";Wo();$c()});var wR,kp=ne(()=>{"use strict";wR=De(We(),1);Qe();Ue();Q()});var kO,bp=ne(()=>{"use strict";Qe();Q();kO=Number.MAX_SAFE_INTEGER});var Rp=ne(()=>{"use strict"});var Cp=ne(()=>{"use strict";_s();Rp()});var Sp=ne(()=>{"use strict";Cp()});var DO,Ep=ne(()=>{"use strict";Ke();vn();Sp();DO=Re("hookWritePolicy",async e=>(await Pc(e))?.hook??{allow_paths:[]})});import yR from"node:path";function Pp(e){return yR.join(e,".comet","current-change.json")}function vR(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function xp(e){return e===null||typeof e=="string"}function kR(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(!vR(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&&!xp(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Fo,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Fo)throw new Error(`current change selection schema must be ${Fo}`);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(!xp(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 Op(e){let t;try{let r=Pp(e),{bytes:i}=await an(r,Ap,{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",...kR(t)}}var Fo,Ap,WO,Mc=ne(()=>{"use strict";Ke();cn();Fo="comet.selection.v2",Ap=Number.MAX_SAFE_INTEGER;WO=Re("readCometCurrentSelection",e=>Op(e))});var Ip=ne(()=>{"use strict";Wo();Qe();yp();vp();Ue();kp();Q();vn();Lc();bp();Ep();Mc();jc();$c()});import{TextDecoder as RR}from"util";function _p(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function CR(e,t){try{return new RR("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t} is not valid UTF-8`,{cause:n})}}async function Wc(e,t,n,r,i={}){try{let o=await V(e,t,n,{label:r,hooks:i.hooks});return{result:o,text:CR(o,r)}}catch(o){let a=o.code;if(a==="ENOENT"||a==="ENOTDIR")return null;throw o}}async function Rn(e,t,n,r,i={}){return(await Wc(e,t,n,r,i))?.text??null}async function Cn(e,t,n,r,i,o={}){if(Buffer.byteLength(n,"utf8")>r)throw new Error(`${i} exceeds ${r} bytes`);let a=await Wc(e,t,r,i),u=await D(e,t,{label:i,expected:"file"});await se(u.target,n,{containedRoot:u.projectRoot,beforeCommit:async()=>{await o.beforeCommit?.();let f=await Wc(e,t,r,i);if(!(!a&&!f)){if(!a||!f)throw new Error(`${i} changed before commit`);if(a.result.realPath!==f.result.realPath||!ze(_p(a.result.stat),_p(f.result.stat))||a.text!==f.text)throw new Error(`${i} changed before commit`)}}})}async function Np(e,t,n,r,i,o={}){let a=await Rn(e,t,r,i);await Cn(e,t,`${a??""}${n}`,r,i,o)}async function Bo(e,t,n,r={}){let i=await D(e,t,{label:n,expected:"file"});return i.exists?mt(i.target,{containedRoot:i.projectRoot,beforeRemove:r.beforeRemove}):!1}var Fc=ne(()=>{"use strict";Ip();yr()});var Dp={};Og(Dp,{RUN_STATE_FILE:()=>Ho,applyRunStateToDocument:()=>Bc,readRunState:()=>ii,removeRunState:()=>oi,runStateFromDocument:()=>Sn,writeRunState:()=>En});import SR from"path";function ri(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 ni(e,t){let n=ri(e,t);if(SR.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 ER(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 Sn(e){if(!e.run_id)return null;let t=ri(e,"run_id"),n=ri(e,"skill"),r=ri(e,"skill_version"),i=ri(e,"skill_hash"),o=ni(e,"pending_ref"),a=ni(e,"trajectory_ref"),u=ni(e,"context_ref"),f=ni(e,"artifacts_ref"),d=ni(e,"checkpoint_ref"),s=Number(e.iteration);if(!Number.isInteger(s)||s<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:Tp(e,"current_step"),iteration:s,pending:Tp(e,"pending"),pendingRef:o,trajectoryRef:a,contextRef:u,artifactsRef:f,checkpointRef:d,status:e.run_status,retries:ER(e)}}function Bc(e,t){t?e.run_id=t.runId:delete e.run_id}function xR(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 AR(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 Sn(t)}async function ii(e,t={}){let n=await Rn(e,Ho,jp,"Run state",t);if(n===null)return null;let r=JSON.parse(n);return AR(r)}async function En(e,t,n={}){await Cn(e,Ho,JSON.stringify(xR(t),null,2),jp,"Run state",n)}async function oi(e,t={}){await Bo(e,Ho,"Run state",t)}var Tp,Ho,jp,Vo=ne(()=>{"use strict";Fc();Tp=(e,t)=>{let n=e[t];return n==null?null:String(n)};Ho=".comet/run-state.json",jp=Number.MAX_SAFE_INTEGER});var pm=_(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});function fm(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}il.default=fm;fm.code='require("ajv/dist/runtime/ucs2length").default'});_s();Ke();import{promises as Ng}from"node:fs";import js from"node:path";var Vl="comet-state.yaml",Pi=".comet.yaml",$n=[Vl,Pi],Ds=class extends Error{};function Oi(e){return $n.some(t=>t===e)}async function Tg(e,t={}){let n=[],r=[];for(let i of $n)try{let o=await Ng.lstat(js.join(e,i));n.push(i),(!o.isFile()||o.isSymbolicLink())&&r.push(i)}catch(o){if(o.code!=="ENOENT")throw o}if(n.length>1)throw new Ds(`Classic state files are ambiguous in ${e}: ${$n.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: ${js.join(e,r[0])}`);return js.join(e,n[0]??t.defaultFileName??Vl)}var jg=Re("classicStateFile",(e,t)=>Tg(e,t));async function ee(e,t={}){return jg(e,t)}import{promises as vr}from"node:fs";import zl from"node:path";Ke();import{createHash as Dg}from"node:crypto";import{lstatSync as wr,readFileSync as Lg,realpathSync as Ul}from"node:fs";import qg from"node:os";import Ie from"node:path";function Ls(e){return`${e.dev}:${e.ino}:${e.birthtimeNs}`}function Ii(e){return process.platform==="win32"?Ul.native(e):Ul(e)}var $g=dt("workspaceIdentity",Wg);function Mg(e){return $g(e)}function Wg(e){let t=Ii(Ie.resolve(e)),n=wr(t,{bigint:!0});if(!n.isDirectory())throw new Error(`工作区必须是目录:${e}`);let r=Ls(n),i=(f,d)=>({projectRoot:t,workspaceId:Dg("sha256").update(JSON.stringify(["comet.workspace.v2",t,r,f,d])).digest("hex")}),o=Ie.join(t,".git"),a,u;try{let f=wr(o);if(f.isSymbolicLink())throw new Error(`工作区 .git 不能是符号链接:${o}`);if(f.isDirectory())a=Ii(o),u=Ls(wr(a,{bigint:!0}));else if(f.isFile()){let d=/^gitdir: (.+)\r?\n?$/u.exec(Lg(o,"utf8"));if(!d)throw new Error(`工作区 .git 文件格式无效:${o}`);a=Ii(Ie.resolve(t,d[1].trim()));let s=wr(a,{bigint:!0});if(!s.isDirectory())throw new Error(`工作区 Git 元数据必须是目录:${a}`);u=Ls(s)}else throw new Error(`工作区 .git 类型无效:${o}`)}catch(f){if(f.code!=="ENOENT")throw f;try{wr(o)}catch(d){if(d.code==="ENOENT")return i(o,null);throw d}throw f}return i(a,u)}function Jl(e){let t=Ie.dirname(e);if(t===e)return e;try{return Ie.join(Ii(t),Ie.basename(e))}catch(n){if(n.code!=="ENOENT")throw n;return Ie.join(Jl(t),Ie.basename(e))}}var Fg=dt("workspaceRuntimeParent",Jl);function qs(e){let t=Mg(e),n=process.env.COMET_DATA_DIR;if(n!==void 0&&(!n.trim()||!Ie.isAbsolute(n)))throw new Error("COMET_DATA_DIR 必须是非空绝对路径");let r=Fg(n??Ie.join(qg.homedir(),".comet")),i=Ie.relative(t.projectRoot,r);if(i===""||!Ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ie.sep}`))throw new Error(`用户级 Runtime 数据根不能位于当前工作区内:${r};工作区:${t.projectRoot}`);let o=Ie.join(r,"workspaces",t.workspaceId);return{...t,dataRoot:r,workspaceRoot:o,runtimeRoot:Ie.join(o,"runtime")}}function Le(e){return qs(e).runtimeRoot}cn();async function Dt(e){return Le(e)}async function Ms(e){return[Le(e)]}async function Gl(e){let t=zl.dirname(e);if(t!==e){await Gl(t);try{await vr.mkdir(e,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r}}let n=await vr.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Runtime 路径必须是真实目录:"+e)}async function ln(e){let t=Le(e);return await Gl(t),t}async function Yl(e,t,n){try{let r=await vr.lstat(e);if(r.isSymbolicLink())throw new Error("旧 Runtime 路径不能是符号链接:"+e);let i=r.isDirectory()?zl.join(e,".comet-runtime-migration.json"):e,o=await vr.lstat(i);if(!o.isFile()||o.isSymbolicLink())return!1;let a;try{a=JSON.parse((await an(i,Number.MAX_SAFE_INTEGER,{label:"旧 Runtime 标记"})).bytes.toString("utf8"))}catch(u){if(u instanceof SyntaxError)return!1;throw u}return a?.schema!=="comet.workspace-runtime-migration.v1"||typeof a.workspaceId!="string"||typeof a.source!="string"||typeof a.target!="string"||!["file","directory"].includes(a.kind)?!1:!r.isDirectory()||(await vr.readdir(e)).every(u=>u===".comet-runtime-migration.json")}catch(r){if(r.code==="ENOENT")return!1;throw r}}import{AsyncLocalStorage as Ql}from"node:async_hooks";import{performance as Ti}from"node:perf_hooks";var Vg=0,Ug=0,Ws=new Ql,Xl=new Ql;async function Zl(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)} 秒
|
|
143
|
+
`)}){if(Xl.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 Xl.run(n,e)}finally{clearInterval(i)}}function eu(e=0){Vg+=1,Ug+=e;for(let t of Ws.getStore()??[])t.gitCommands+=1,t.gitDurationMs+=e}async function tu(e){let t={gitCommands:0,gitDurationMs:0};return{result:await Ws.run([...Ws.getStore()??[],t],e),metrics:t}}function un(e){let t=Ti.now();try{return e()}finally{eu(Ti.now()-t)}}async function Fs(e){let t=Ti.now();try{return await e()}finally{eu(Ti.now()-t)}}import ql from"node:path";import{promises as wp}from"fs";import ae from"path";import sR from"os";import{promises as nu}from"fs";async function ji(e){try{return await nu.access(e),!0}catch(t){if(Jg(t))return!1;throw t}}async function Bs(e){try{return await nu.readdir(e)}catch(t){let n=t?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw t}}function Jg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}Ue();vn();Lc();Q();var Zr=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},bn=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="ClassicProjectConfigError"}},gp=".comet/config.yaml";function qc(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Mo(e,t){let n=ae.resolve(e),r=t==="docs"?ae.join(n,"docs"):n,i=ae.join(r,"openspec"),o=ae.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:t,openSpecBase:r,openSpecRoot:i,changesDir:ae.join(i,"changes"),archiveDir:ae.join(i,"changes","archive"),specsDir:ae.join(i,"specs"),superpowersRoot:o,superpowersSpecsDir:ae.join(o,"specs"),superpowersPlansDir:ae.join(o,"plans"),superpowersReportsDir:ae.join(o,"reports")}}async function aR(e){let t=await Qr(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new Zr;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new Zr("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function ei(e,t){return Mo(e,t??await aR(e))}async function cR(e){try{return await wp.lstat(e),!0}catch(t){if(qc(t))return!1;throw t}}async function lR(e,t){let n=await ei(e,t),r=n.artifactLayout==="legacy"?"docs":"legacy",i=Mo(e,r).openSpecRoot,[o,a]=await Promise.all([D(n.projectRoot,we(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),cR(i)]),u=o.exists;return{paths:n,configuredRootExists:u,alternateRoot:i,alternateRootExists:a,dualRoots:u&&a}}async function uR(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=we(e.projectRoot,n);await D(e.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Ne(e,t){let n=await lR(e,t);if(await uR(n.paths),!n.configuredRootExists){let r=we(n.paths.projectRoot,n.paths.openSpecRoot),i=we(n.paths.projectRoot,n.alternateRoot);throw new Zr(`Configured Classic OpenSpec root is missing: ${r} (alternate ${i} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function ti(e,t){let n=ae.join(ae.resolve(e),".comet","classic-root-move.json");if(await ji(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await Ne(e,t);if(!await ji(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${we(r.projectRoot,r.openSpecRoot)}`);return r}async function ye(e){let t=ae.resolve(e),n=null;try{(await wp.lstat(t)).isDirectory()||(t=ae.dirname(t))}catch(o){if(!qc(o))throw o}let r=t,i=ae.resolve(sR.homedir());for(;;){ae.basename(t)==="openspec"&&(n=ae.dirname(t));let o=!1,a=t===i&&t!==r,u=null;if(!a)try{let{bytes:d}=await V(t,gp,wn,{label:gp});u=d.toString("utf8")}catch(d){if(!qc(d))throw d}if(u!==null)try{let d=yn(u,{allowPartialProject:!0,allowMissingNativeFields:!0}).value;o=!!d&&typeof d=="object"&&!Array.isArray(d)&&(d.schema==="comet.project.v1"||d.default_workflow!==void 0||d.native!==void 0)}catch(d){if(t===r)throw new bn(d);if(tp(u))throw new bn(d)}if(o||await ji(ae.join(t,".git")))return t;let f=ae.dirname(t);if(f===t)return n??ae.resolve(e);t=f}}function we(e,t){return ae.relative(ae.resolve(e),t).replaceAll("\\","/")}import{execFile as ex}from"child_process";Ke();import{randomUUID as YR}from"node:crypto";Q();Vo();var Lp=["full","hotfix","tweak"],xn=1,Uc=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u;function ht(e){return/^# comet-execution: managed-run\r?\n/u.test(e)}var PR=["open","design","build","verify","archive"],OR=["en","zh-CN"],IR=["off","beta"],_R=["subagent-driven-development","executing-plans","direct","autonomous"],NR=["plan-ready"],TR=["confirmed"],jR=["tdd","direct"],DR=["off","standard","thorough"],LR=["current","branch","worktree"],qR=["light","full"],$R=["pending","pass","fail"],MR=["pending","handled"],WR=["pending","confirmed"],zt=["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"],si=["change_id","run_id","run_checkpoint","application_checkpoint"],FR=new Set([...zt,...si]),BR=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Hc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Xn(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 Te(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 Vc(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 qp(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 Uo(e,t){let n=Xn(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 HR(e,t){let n=Xn(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 VR(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==xn)throw new Error(`Invalid Classic state: classic_migration must be ${xn}`);return t}function UR(e){if(!zt.some(n=>Hc(e,n)))return null;for(let n of BR)if(!Hc(e,n))return null;return{workflow:Te(e,"workflow",Lp,!1),language:Te(e,"language",OR),phase:Te(e,"phase",PR,!1),contextCompression:Te(e,"context_compression",IR),buildMode:Te(e,"build_mode",_R),buildPause:Te(e,"build_pause",NR),subagentDispatch:Te(e,"subagent_dispatch",TR),tddMode:Te(e,"tdd_mode",jR),reviewMode:Te(e,"review_mode",DR),isolation:Te(e,"isolation",LR),boundBranch:Xn(e,"bound_branch"),verifyMode:Te(e,"verify_mode",qR),autoTransition:Vc(e,"auto_transition"),baseRef:Xn(e,"base_ref"),designDoc:Uo(e,"design_doc"),plan:Uo(e,"plan"),verifyResult:Te(e,"verify_result",$R,!1),verifyFailures:qp(e,"verify_failures"),...Hc(e,"check_epoch")?{checkEpoch:qp(e,"check_epoch")}:{},verificationReport:Uo(e,"verification_report"),branchStatus:Te(e,"branch_status",MR),createdAt:Xn(e,"created_at"),verifiedAt:Xn(e,"verified_at"),archiveConfirmation:Te(e,"archive_confirmation",WR),archived:Vc(e,"archived",!1),directOverride:Vc(e,"direct_override"),handoffContext:Uo(e,"handoff_context"),handoffHash:HR(e,"handoff_hash"),classicProfile:Te(e,"classic_profile",Lp),classicMigration:VR(e)}}function Ze(e,t){if(e.change_id!==void 0&&(typeof e.change_id!="string"||!Uc.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=Sn(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:UR(e),run:n,unknownKeys:Object.keys(e).filter(r=>!FR.has(r))}}function ai(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}}Q();var $p=De(We(),1);Qe();Q();import{createHash as JR,randomUUID as KR}from"node:crypto";import K from"node:path";var Jc=new Set(["run-state.json","pending-action.json","trajectory.jsonl","context.md","artifacts.json","checkpoint.json","coordination.json","subagent-progress.md"]);function Jo(e){let t=JR("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 Mp(e,t){let n=await ee(t),r=K.relative(e,n).replaceAll("\\","/"),i=null;try{i=(await V(e,r,Number.MAX_SAFE_INTEGER,{label:"Classic change identity"})).bytes.toString("utf8")}catch(u){if(u.code!=="ENOENT")throw u}if(i===null)throw Object.assign(new Error("Classic state file does not exist"),{code:"ENOENT"});let o=(0,$p.parseDocument)(i,{uniqueKeys:!0});if(o.errors.length)throw new Error(`Invalid Classic state document: ${o.errors[0].message}`);let a=o.get("change_id");if(a!==void 0&&(typeof a!="string"||!Uc.test(a)))throw new Error("Invalid Classic change_id: expected an immutable UUID");return{source:i,document:o,id:a}}async function zR(e,t){let n=await ee(t),r=K.relative(e,n).replaceAll("\\","/"),i=()=>Mp(e,t),o=await i();if(o.id)return o.id;let{source:a,document:u}=o,f=u.get("run_id"),d=typeof f=="string"&&f?Jo(`classic-run:${f}`):KR();return u.get("archived")===!0||K.basename(K.dirname(t))==="archive"?typeof f=="string"&&f?d:Jo(`classic-archive:${r}`):(u.set("change_id",d),await se(n,u.toString(),{containedRoot:e,exclusive:a===null,beforeCommit:async()=>{if((await i()).source!==a)throw new Error("Classic state changed while assigning its instance identity")}}),d)}async function Kc(e,t,n={}){let r=t??await ye(e),i;try{i=await Mp(r,e)}catch(p){if(p.code==="ENOENT")return null;throw p}let{document:o,id:a}=i,u=K.relative(r,e).replaceAll("\\","/"),f=o.get("run_id"),d=o.get("archived")===!0||K.basename(K.dirname(e))==="archive",s=a??(typeof f=="string"&&f?Jo(`classic-run:${f}`):d?Jo(`classic-archive:${u}`):null);if(!s)return e;let l=Le(r),m=K.parse(l).root;if(!(await D(m,K.relative(m,l).replaceAll("\\","/"),{label:"Classic read-only Runtime root",expected:"directory"})).exists)return n.includeMissing?K.join(l,"classic-changes",s):e;let c=await D(l,`classic-changes/${s}`,{label:"Classic read-only Run directory",expected:"directory"});return c.exists||n.includeMissing?c.target:e}async function U(e,t){return GR(e,t)}async function GR(e,t){let n=t??await ye(e),r=K.relative(n,e).replaceAll("\\","/");if(r&&!(await D(n,r,{label:"Classic change directory",expected:"directory"})).exists)throw Object.assign(new Error("Classic change directory does not exist"),{code:"ENOENT"});await ee(e);let i=await ln(n),o=await zR(n,e),a=K.join(i,"classic-changes",o);return await Xe(i,K.relative(i,a),{label:"Classic local Run directory"}),a}async function Ko(e,t,n={}){let r=Le(e),i=K.relative(r,t);if(i===""||!i.startsWith(`..${K.sep}`)&&i!==".."&&!K.isAbsolute(i))return n.readOnly?{root:K.dirname(r),target:t}:(await ln(e),{root:r,target:t});let o=K.relative(K.resolve(e),t).replaceAll("\\","/");if(o.startsWith(".comet/runtime/"))return{root:r,target:K.join(r,o.slice(15))};let a=/^(?:(.*)\/)?\.comet\/([^/]+)(\/.*)?$/u.exec(o);if(!a||!Jc.has(a[2]))return null;if(n.readOnly){let m=K.parse(r).root;if(!(await D(m,K.relative(m,K.join(r,"classic-changes")),{label:"Classic local records",expected:"directory"})).exists)return null}let u=a[1]??"";if(!(await D(e,K.relative(e,await ee(K.join(e,u))),{label:"Classic local change identity",expected:"file"})).exists)return null;let d=K.join(e,u),s=n.readOnly?await Kc(d,e,{includeMissing:!0}):await U(d,e);if(!s||n.readOnly&&s===d)return null;let l=K.relative(r,s);if(K.isAbsolute(l)||l===".."||l.startsWith(`..${K.sep}`))throw new Error("Classic Runtime workspace changed while resolving a change-local target");return{root:n.readOnly?K.dirname(r):r,target:K.join(s,".comet",a[2],a[3]??"")}}Q();var ui=De(We(),1);Qe();Q();import gt from"path";import{AsyncLocalStorage as XR}from"node:async_hooks";Vo();var Wp=new XR,ci=".comet-state-transaction.json";async function Et(e,t){let n=await U(e);return Wp.getStore()===n?t():Wp.run(n,async()=>(await Bp(e),t()))}async function li(e,t){let n=t===ci?await U(e):e;try{return(await V(n,t,Number.MAX_SAFE_INTEGER,{label:"Classic state transaction"})).bytes.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}function QR(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=Sn({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 Bp(e){let t=await li(e,ci);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 ee(e),i=n.stateFile??Pi;if(typeof i!="string"||!Oi(i)||gt.basename(r)!==i)throw new Error("Classic state transaction belongs to a different state filename; preserve files for recovery");let o=await li(e,i);if(o!==n.beforeYaml&&o!==n.afterYaml)throw new Error("Classic state transaction conflicts with current YAML; preserve files for recovery");let a=QR(o===n.afterYaml?n.afterRun:n.beforeRun);if(await ee(e)!==r)throw new Error("Classic state filename changed during transaction recovery");a?await En(await U(e),a):await oi(await U(e));let u=await U(e);await mt(gt.join(u,ci),{containedRoot:u})}function Hp(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 An(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 Fp(e,t,n){e.get(t)!==n&&e.set(t,n)}function Vp(e,t){if(t.classic)for(let[n,r]of Object.entries(ai(t.classic)))n==="auto_transition"&&r===null&&!e.has(n)||Fp(e,n,r);else for(let n of zt)e.delete(n);Bc(e.toJS(),t.run),t.run?Fp(e,"run_id",t.run.runId):e.delete("run_id")}function ZR(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 Up(e){let t=!1;for(let n of["build_command","verify_command"])e.has(n)&&(e.delete(n),t=!0);return t}async function zc(e){let t;try{t=(await V(gt.dirname(e),gt.basename(e),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new ui.Document({})}let n=(0,ui.parseDocument)(t);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return An(n),n}var eC=Re("classicStateProjection",e=>tC(e));async function xt(e,t={}){return t.migrate===!1?eC(e):Et(e,()=>nC(e,t))}async function tC(e){let t=await Kc(e);if(t===null)return Ze({});if((await D(t,ci,{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 zc(await ee(e));Up(n);let r=An(n),i=await ii(t);return!i&&r.run_id&&r.skill&&(i=Sn(r)),Hp(r,i),Ze(r,i)}async function nC(e,t){let n=t.migrate!==!1,r=await ee(e),i=await zc(r),o=An(i),a=Up(i);a&&(o=An(i));let u=await ii(await U(e));if(Hp(o,u),!u&&o.run_id&&o.skill){let{runStateFromDocument:f}=await Promise.resolve().then(()=>(Vo(),Dp));u=f(o),u&&n&&(await En(await U(e),u),ZR(i),a=!0)}return a&&n&&await se(r,i.toString(),{containedRoot:e}),Ze(An(i),u)}async function Qn(e,t,n={}){let r=await ee(e,{defaultFileName:Pi});if(await li(e,gt.basename(r))===null){let i=new ui.Document({change_id:YR()});Vp(i,{...t,unknownKeys:t.unknownKeys??[]}),Ze(An(i),t.run??null);let o=await ye(e),a=await ln(o),u=await Xe(a,`classic-changes/${i.get("change_id")}`,{label:"Classic initial Run"});t.run&&await En(u,t.run),await se(r,i.toString(),{containedRoot:e,exclusive:!0,beforeCommit:n.beforeCommit});return}return Et(e,()=>rC(e,t,n))}async function rC(e,t,n){let r=await ee(e),i=await li(e,gt.basename(r));if(i!==null&&ht(i))throw new Error("Classic managed Run state is owned by the SDK; compat writes are not allowed");let o=await zc(r);o.has("change_id")||o.set("change_id",gt.basename(await U(e)));let a=o.get("check_epoch")??0;if(typeof a=="number"&&a>(t.classic?.checkEpoch??0))throw new Error("Classic state changed during this operation; reload before retrying");Vp(o,{...t,unknownKeys:t.unknownKeys??[]}),Ze(An(o),t.run??null);let u=await li(e,gt.basename(r)),f=o.toString();if(u===f){await n.beforeCommit?.(),t.run?await En(await U(e),t.run):await oi(await U(e));return}let d=await U(e),s=gt.join(d,ci);await se(s,JSON.stringify({schema:"comet.classic.state-transaction.v1",stateFile:gt.basename(r),beforeYaml:u,afterYaml:f,beforeRun:await ii(await U(e)),afterRun:t.run}),{containedRoot:d});try{t.run?await En(await U(e),t.run):await oi(await U(e)),await se(r,f,{containedRoot:e,beforeCommit:n.beforeCommit})}catch(l){throw await Bp(e).catch(()=>{}),l}await mt(s,{containedRoot:d}).catch(()=>{})}import{AsyncLocalStorage as wS}from"node:async_hooks";import{types as iC}from"node:util";import{createHash as oC}from"node:crypto";var Jp=new WeakMap,Kp=new WeakMap;function zp(e,t){let n=e!==null&&typeof e=="object"&&t?.(e);if(n){let i=Kp.get(e);if(i!==void 0)return i}let r=JSON.stringify(e);return n&&r.length<=64*1024&&Kp.set(e,r),r}function sC(e,t,n){let r=new WeakMap,i=w=>{let v=r.get(w);if(v)return v;let k=Array.isArray(w)?[...w]:{...w};return r.set(w,k),k},o=i(e),a=[],u=[],f=[],d=new Map,s=new Map,l=new WeakMap,m=new Map,c=new Map,p=new Map,h=w=>{let v=w&&typeof w=="object"?l.get(w):void 0;if(v!==void 0)return v;let k=zp(w,n);return v=d.get(k),v===void 0&&(v=a.length,a.push(w),d.set(k,v)),w&&typeof w=="object"&&l.set(w,v),v},g=w=>{let v=p.get(w);if(v!==void 0)return v;let k=w.base===void 0?void 0:g(w.base),S=u.length;return u.push({...k===void 0?{}:{base:k},entries:w.entries.map(([E,A])=>[E,h(A)]),removed:[...w.removed]}),p.set(w,S),S};for(let w of t){let v=o,k=e;for(let L of w.path.slice(0,-1)){k=k[L];let $=i(k);Object.defineProperty(v,L,{value:$,enumerable:!0,writable:!0,configurable:!0}),v=$}let S=w.path.at(-1),E=v[S];if(!E||typeof E!="object"||Array.isArray(E))continue;if(n?.(E)){let L=Jp.get(E);if(!L){let $=E,J=c.get(w.group),F=Object.entries($),re=J?F.filter(([Ve,R])=>!Object.hasOwn(J.source,Ve)||h(J.source[Ve])!==h(R)):F,X=J?Object.keys(J.source).filter(Ve=>!Object.hasOwn($,Ve)):[],te=J&&re.length+X.length<F.length;L={...te?{base:J.node}:{},entries:te?re:F,removed:te?X:[]},Jp.set(E,L)}c.set(w.group,{source:E,node:L}),f.push({path:w.path,map:g(L)}),Object.defineProperty(v,S,{value:{},enumerable:!0,writable:!0,configurable:!0});continue}let A=new Map;for(let[L,$]of Object.entries(E)){let J=$&&typeof $=="object"?l.get($):void 0;if(J===void 0){let F=zp($,n);J=d.get(F),J===void 0&&(J=a.length,a.push($),d.set(F,J)),$&&typeof $=="object"&&l.set($,J)}A.set(L,J)}let M=JSON.stringify([...A]),O=s.get(M);if(O===void 0){let L=m.get(w.group),$=[...A].filter(([re,X])=>L?.entries.get(re)!==X),J=L?[...L.entries.keys()].filter(re=>!A.has(re)):[],F=L&&$.length+J.length<A.size;O=u.length,u.push({...F?{base:L.id}:{},entries:F?$:[...A],removed:F?J:[]}),s.set(M,O)}m.set(w.group,{id:O,entries:A}),f.push({path:w.path,map:O}),Object.defineProperty(v,S,{value:{},enumerable:!0,writable:!0,configurable:!0})}return f.length?{record:o,pool:{version:1,values:a,maps:u,bindings:f}}:{record:o}}function aC(){let e=[],t=o=>o===null?0:e[o].height,n=(o,a,u,f)=>{let d=e.length;return e.push({key:o,value:a,left:u,right:f,height:1+Math.max(t(u),t(f))}),d},r=(o,a,u,f)=>{if(t(u)>t(f)+1){let d=e[u];if(t(d.left)>=t(d.right))return n(d.key,d.value,d.left,n(o,a,d.right,f));let s=e[d.right];return n(s.key,s.value,n(d.key,d.value,d.left,s.left),n(o,a,s.right,f))}if(t(f)>t(u)+1){let d=e[f];if(t(d.right)>=t(d.left))return n(d.key,d.value,n(o,a,u,d.left),d.right);let s=e[d.left];return n(s.key,s.value,n(o,a,u,s.left),n(d.key,d.value,s.right,d.right))}return n(o,a,u,f)},i=(o,a,u)=>{if(o===null)return u===void 0?null:n(a,u,null,null);let f=e[o];if(a<f.key){let s=i(f.left,a,u);return s===f.left?o:r(f.key,f.value,s,f.right)}if(a>f.key){let s=i(f.right,a,u);return s===f.right?o:r(f.key,f.value,f.left,s)}if(u!==void 0)return u===f.value?o:n(a,u,f.left,f.right);if(f.left===null)return f.right;if(f.right===null)return f.left;let d=e[f.right];for(;d.left!==null;)d=e[d.left];return r(d.key,d.value,f.left,i(f.right,d.key,void 0))};return{nodes:e,set:i}}function Yp(e){let{nodes:t,set:n}=aC(),r=[];for(let f of e.maps){let d=f.base===void 0?null:r[f.base];for(let s of f.removed)d=n(d,s,void 0);for(let[s,l]of f.entries)d=n(d,s,l);r.push(d)}let i=[],o=new Map,a=f=>{if(f===null)return null;let d=o.get(f);if(d!==void 0)return d;let s=t[f],l=a(s.left),m=a(s.right),c=i.length;return i.push({...s,left:l,right:m}),o.set(f,c),c},u=r.map(a);return{version:3,values:e.values,nodes:i,maps:u,bindings:e.bindings}}function Xp(e,t,n){let r=sC(e,t,n);return{record:r.record,...r.pool?{pool:Yp(r.pool)}:{}}}var At=new WeakMap,di=new WeakMap;function*zo(e,t=e.root){if(t===null)return;let n=e.pool.nodes[t];yield*zo(e,n.left),yield[n.key,e.pool.values[n.value]],yield*zo(e,n.right)}function cC(e){let t=r=>{let i=e.root;for(;i!==null;){let o=e.pool.nodes[i];if(r===o.key)return o.value;i=r<o.key?o.left:o.right}},n=new Proxy({},{ownKeys:()=>[...zo(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 At.set(n,e),n}var ce=e=>{throw new Error(e)},Zn=(e,t)=>Number.isSafeInteger(e)&&Number(e)>=0&&Number(e)<t;function Qp(e){let t=e;if(!t||!Array.isArray(t.values)||!Array.isArray(t.maps)||!Array.isArray(t.bindings))return ce("JSON 引用池格式无效");if(e.version===1){let i=e;return Object.keys(i).some(o=>!["version","values","maps","bindings"].includes(o))&&ce("JSON 引用池字段无效"),i.maps.forEach((o,a)=>{(!o||!Array.isArray(o.entries)||!Array.isArray(o.removed)||o.base!==void 0&&!Zn(o.base,a)||Object.keys(o).some(f=>!["base","entries","removed"].includes(f)))&&ce("JSON 映射引用无效");let u=new Set;for(let f of o.removed)(typeof f!="string"||u.has(f))&&ce("JSON 删除键无效"),u.add(f);for(let f of o.entries)(!Array.isArray(f)||f.length!==2||typeof f[0]!="string"||!Zn(f[1],i.values.length)||u.has(f[0]))&&ce("JSON 值引用无效"),u.add(f[0])}),Qp(Yp(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 ce("JSON 引用池版本或字段无效");let r=[];return n.nodes.forEach((i,o)=>{(!i||typeof i.key!="string"||!Zn(i.value,n.values.length)||![i.left,i.right].every(f=>f===null||Zn(f,o))||Object.keys(i).some(f=>!["key","value","left","right","height"].includes(f)))&&ce("JSON 树引用无效");let a=i.left===null?void 0:n.nodes[i.left],u=i.right===null?void 0:n.nodes[i.right];(i.height!==1+Math.max(a?.height??0,u?.height??0)||Math.abs((a?.height??0)-(u?.height??0))>1||i.left!==null&&r[i.left].max>=i.key||i.right!==null&&r[i.right].min<=i.key)&&ce("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&&!Zn(i,n.nodes.length))&&ce("JSON 映射根无效"),n}function lC(e,t){let n=(p,h=0,g=new Set)=>{if(h>64&&ce("JSON 数据嵌套过深"),!(p===null||typeof p=="string"||typeof p=="boolean"||typeof p=="number"&&Number.isFinite(p))){if(typeof p!="object"||p===null||iC.isProxy(p)||g.has(p))return ce("JSON 数据无效");Object.getPrototypeOf(p)!==Object.prototype&&Object.getPrototypeOf(p)!==null&&!Array.isArray(p)&&ce("JSON 数据必须为普通对象"),g.add(p);for(let w of Reflect.ownKeys(p)){if(Array.isArray(p)&&w==="length")continue;let v=Object.getOwnPropertyDescriptor(p,w);(typeof w!="string"||!v.enumerable||!("value"in v))&&ce("JSON 数据不能包含访问器"),n(v.value,h+1,g)}Array.isArray(p)&&Object.keys(p).length!==p.length&&ce("JSON 数组不能稀疏"),g.delete(p)}};n(e),n(t);let r=Qp(structuredClone(t)),i=structuredClone(e),o={validatedNodes:r.nodes.length,validationActions:0,validationResultMaps:0,validationEntries:0,validationMaterializedEntries:0,materializedMaps:0,materializedEntries:0,hashBytes:0,logicalHashBytes:0},a=new Set,u=new Set,f=new Set,d=new Map;for(let p of r.bindings){(!p||!Array.isArray(p.path)||p.path.length<1||p.path.length>16||p.path.some(v=>typeof v!="string"||["__proto__","constructor","prototype"].includes(v))||!Zn(p.map,r.maps.length)||Object.keys(p).some(v=>!["path","map"].includes(v)))&&ce("JSON 池绑定无效");let h=JSON.stringify(p.path);(u.has(h)||p.path.some((v,k)=>a.has(JSON.stringify(p.path.slice(0,k+1)))))&&ce("JSON 池绑定重复或重叠"),a.add(h),p.path.forEach((v,k)=>u.add(JSON.stringify(p.path.slice(0,k+1))));let g=i;for(let v of p.path.slice(0,-1))(!g||typeof g!="object"||!Object.hasOwn(g,v))&&ce("JSON 池绑定缺失"),g=g[v];let w=p.path.at(-1);(!g||!Object.hasOwn(g,w)||!g[w]||typeof g[w]!="object"||Array.isArray(g[w])||Object.keys(g[w]).length)&&ce("JSON 池绑定必须替换空对象"),Object.defineProperty(g,w,{value:cC({pool:r,root:r.maps[p.map],stats:o,checked:f,origins:d}),enumerable:!0,writable:!0,configurable:!0})}let s=new WeakMap,l=new Map,m=p=>{if(!p||typeof p!="object")return 0;let h=s.get(p);if(h!==void 0)return h;let g=At.get(p),w=k=>{if(k===null)return 0;let S=l.get(k);if(S!==void 0)return S;let E=r.nodes[k],A=Math.max(1+m(r.values[E.value]),w(E.left),w(E.right));return l.set(k,A),A},v=g?w(g.root):Object.values(p).reduce((k,S)=>Math.max(k,1+m(S)),0);return s.set(p,v),v};m(i)>64&&ce("JSON 逻辑数据嵌套超过 64 层"),Gc(r),Gc(i);let c=p=>{if(!(!p||typeof p!="object"||At.has(p)||di.has(p))){di.set(p,o);for(let h of Object.values(p))c(h)}};return c(i),{value:i,stats:o,materialize:(p=[])=>Pn(p.reduce((h,g)=>h?.[g],i)),hash:()=>Pt(i)}}function Gc(e){let t=new WeakSet,n=r=>{if(!(!r||typeof r!="object"||At.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=At.get(e);if(t){t.stats.materializedMaps++;let n=[...zo(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 Yc(e,t){let n=At.get(e);if(!n){for(let[i,o]of Object.entries(e))t(i,o);return}n.stats.validationResultMaps++;let r=i=>{if(i===null||n.checked.has(i))return;let o=n.pool.nodes[i];r(o.left),t(o.key,n.pool.values[o.value]),n.stats.validationEntries++,r(o.right),n.checked.add(i)};r(n.root)}function Xc(e,t,n){let r=At.get(e),i=(u,f)=>{let d=f.sequence;return t.get(d)!==u&&ce("WorkflowRun 结果来源不一致"),d};if(!r){for(let[u,f]of Object.entries(e))i(u,f)>=n&&ce("WorkflowRun 结果序号无效");return}let o=r.origins.get(t);o||(o=new Map,r.origins.set(t,o));let a=u=>{if(u===null)return 0;let f=o.get(u);if(f!==void 0)return f;let d=r.pool.nodes[u],s=Math.max(i(d.key,r.pool.values[d.value]),a(d.left),a(d.right));return o.set(u,s),s};a(r.root)>=n&&ce("WorkflowRun 结果序号无效")}function uC(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 Gp=new WeakMap;function Pt(e,t={}){let n=oC("sha256"),r=e&&typeof e=="object"?di.get(e):void 0,i=d=>{if(!d||typeof d!="object")return;let s=At.get(d)?.stats??di.get(d);if(s)return s;for(let l of Object.values(d)){let m=i(l);if(m)return m}};r??=i(e);let o=r&&t.cachePrefixes!==!1?Gp.get(r):void 0;r&&!o&&t.cachePrefixes!==!1&&(o={root:{hash:n.copy(),next:new Map},size:0},Gp.set(r,o));let a=o?.root,u=d=>{let s=Buffer.byteLength(d);r&&(r.logicalHashBytes+=s);let l=a?.next.get(d);if(l){n=l.hash.copy(),a=l;return}if(n.update(d),r&&(r.hashBytes+=s),a&&o&&o.size<1e5){let m={hash:n.copy(),next:new Map};a.next.set(d,m),a=m,o.size++}else a=void 0},f=d=>{if(d===null||typeof d!="object"){u(JSON.stringify(d));return}if(Array.isArray(d)){u("["),d.forEach((s,l)=>{l&&u(","),f(s)}),u("]");return}u("{"),uC(d).forEach((s,l)=>{l&&u(","),u(JSON.stringify(s)+":"),f(d[s])}),u("}")};return f(e),n.digest("hex")}function Qc(e){return di.get(e)??At.get(e)?.stats}function Go(e,t,n=!0){let r=lC(e,t);return n?r.materialize():r.value}var Zp=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(Zp,n)?Zp[n]:"manual-review"}code;recovery};import{createHash as dC}from"node:crypto";import{types as fC}from"node:util";var Zc=new WeakMap,em=new WeakMap;function wt(e){return Zc.has(e)}function el(e,t=!0,n=!1,r=!1){let i=new Set,o=new WeakMap;function a(u,f){if(f>64)throw new b("INVALID_JSON","数据嵌套超过 64 层");if(u===null||typeof u=="string"||typeof u=="boolean")return n?JSON.stringify(u):u;if(typeof u=="number"&&Number.isFinite(u))return n?JSON.stringify(u):u===0?0:u;if(typeof u!="object"||u===null)throw new b("INVALID_JSON","数据必须能无损保存为 JSON");if(i.has(u))throw new b("INVALID_JSON","数据包含循环引用");if(fC.isProxy(u))throw new b("INVALID_JSON","仅接受无执行行为的 JSON 数据");let d=Zc.get(u);if(!t&&!n&&d!==void 0){if(f+d>64)throw new b("INVALID_JSON","数据嵌套超过 64 层");return o.set(u,{value:u,height:d}),u}let s=o.get(u);if(s){if(f+s.height>64)throw new b("INVALID_JSON","数据嵌套超过 64 层");return t?Yo(s.value):n?s.value:u}i.add(u);let l=0,m=p=>p&&typeof p=="object"?o.get(p)?.height??0:0,c=p=>(o.set(u,{value:p,height:l}),r&&(Object.freeze(u),Zc.set(u,l)),p);try{if(Array.isArray(u)){if(Reflect.ownKeys(u).length!==u.length+1)throw new b("INVALID_JSON","数组不能包含空洞或额外属性");let w=[];for(let v=0;v<u.length;v+=1){let k=Object.getOwnPropertyDescriptor(u,String(v));if(!k||!("value"in k))throw new b("INVALID_JSON","数组元素必须是普通数据");let S=a(k.value,f+1);l=Math.max(l,1+m(k.value)),(t||n)&&w.push(S)}return c(n?`[${w.join(",")}]`:t?w:u)}let p=Object.getPrototypeOf(u);if(p!==Object.prototype&&p!==null)throw new b("INVALID_JSON","仅接受普通 JSON 对象");let h=[],g=Reflect.ownKeys(u);(t||n)&&g.sort((w,v)=>{let k=String(w),S=String(v),E=String(Number(k))===k&&Number.isInteger(Number(k))&&Number(k)>=0&&Number(k)<4294967295,A=String(Number(S))===S&&Number.isInteger(Number(S))&&Number(S)>=0&&Number(S)<4294967295;return E||A?E&&A?Number(k)-Number(S):E?-1:1:k<S?-1:k>S?1:0});for(let w of g){let v=Object.getOwnPropertyDescriptor(u,w);if(typeof w!="string"||!v.enumerable||!("value"in v))throw new b("INVALID_JSON","对象属性必须是可枚举的字符串数据属性");let k=a(v.value,f+1);l=Math.max(l,1+m(v.value)),(t||n)&&h.push([w,k])}return c(n?`{${h.map(([w,v])=>`${JSON.stringify(w)}:${v}`).join(",")}}`:t?Object.fromEntries(h):u)}finally{i.delete(u)}}return a(e,0)}function On(e){return el(e,!1,!0)}function yt(e){return el(e)}function Yo(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(Yo(e[r]));return n}let t={};for(let n of Object.keys(e)){let r=Yo(e[n]);n==="__proto__"?Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0}):t[n]=r}return t}function Gt(e){el(e,!1)}function z(e){let t=e!==null&&typeof e=="object"&&wt(e),n=t?em.get(e):void 0;if(n!==void 0)return n;let r=dC("sha256").update(On(e)).digest("hex");return t&&em.set(e,r),r}function Be(e,t){if(typeof e!="string"||!e.trim()||e.length>4096)throw new b("INVALID_ACTION",`${t} 必须是非空字符串且不超过 4096 字符`)}function Xo(e){return wt(e)?{...e,reconciliations:[...e.reconciliations]}:structuredClone(e)}function tm(e,t,n){if(t!==e.attempt||n!==e.inputHash)throw new b("STALE_ACTION","执行尝试或输入版本与当前 Action 不一致")}function nm(e){return["succeeded","failed","cancelled"].includes(e.status)}function pC(e,t,n){for(let a of["id","runId","stepId","type"])Be(e[a],a);e.ref!==void 0&&Be(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 o=e.requiredCapabilities??[];for(let a of o)Be(a,"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??z(t),status:"pending",retry:i,requiredCapabilities:[...new Set(o)],receipts:[],reconciliations:[]}}function rm(e,t){if(t=tl(t),Be(t.outcomeId,"outcomeId"),!["succeeded","failed"].includes(t.status))throw new b("INVALID_OUTCOME","结果必须声明执行成功或失败");t.event!==void 0&&Be(t.event,"event");let n=z(t),r=e.rejectedOutcomes?.find(o=>o.outcome.outcomeId===t.outcomeId);if(r)throw z(r.outcome)!==n?new b("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken"):new b(r.code,r.reason);let i=e.receipts.find(o=>o.outcomeId===t.outcomeId);if(i){if(i.hash!==n)throw new b("OUTCOME_CONFLICT","同一结果标识不能提交不同内容;修正后请使用新的 outcomeId,并保留原 actionId、attempt、inputHash 和 claimToken");return{action:Xo(e),duplicate:!0}}if(tm(e,t.attempt,t.inputHash),t.actionId!==e.id)throw new b("STALE_ACTION","结果不属于当前 Action");if(nm(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 o of t.artifacts??[])if(Be(o.uri,"artifact.uri"),!/^[a-f0-9]{64}$/.test(o.sha256))throw new b("INVALID_OUTCOME","产物引用必须包含 SHA-256");return{action:{...Xo(e),status:t.status,outcome:structuredClone(t),receipts:[...e.receipts,{outcomeId:t.outcomeId,hash:n}]},duplicate:!1}}function im(e,t){at(t,["actionId","attempt","inputHash","claimToken","evidence"]);for(let n of["actionId","inputHash","claimToken","evidence"])Be(t[n],n);if(!Number.isSafeInteger(t.attempt)||t.attempt<1||/^<.*>$/su.test(t.evidence.trim()))throw new b("INVALID_ACTION","停止确认需要原执行尝试和实际停止证据");if(tm(e,t.attempt,t.inputHash),t.actionId!==e.id||!e.claim||t.claimToken!==e.claim.token)throw new b("STALE_ACTION","停止确认必须绑定原 Action 和领取身份")}function om(e,t){if(im(e,t),e.status!=="cancelled")throw new b("ACTION_TERMINAL","只能确认已取消 Action 的执行停止");if(e.cancellation&&z(e.cancellation)!==z(t))throw new b("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Xo(e),cancellation:structuredClone(t)}}function sm(e,t){if(im(e,t),!nm(e))throw new b("ACTION_TERMINAL","只能确认终态 Action 的执行停止");if(e.executionStop&&z(e.executionStop)!==z(t))throw new b("OUTCOME_CONFLICT","当前执行已有不同的停止确认");return{...Xo(e),executionStop:structuredClone(t)}}function at(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 tl(e){let t=yt(e),n=["actionId","attempt","inputHash","claimToken","outcomeId","status","output"];if(at(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(at(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 nl(e,t){if(at(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=pC(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&&Be(n.reason,"reason"),n.claim!==void 0&&(at(n.claim,["executorId","sessionId","token"]),Be(n.claim.executorId,"executorId"),Be(n.claim.token,"token"),n.claim.sessionId!==void 0&&Be(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&&(at(n.executionOrigin,["workflow"]),at(n.executionOrigin.workflow,["id","version","hash"]),Be(n.executionOrigin.workflow.id,"executionOrigin.workflow.id"),Be(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&&om({...n,input:null},n.cancellation),n.executionStop!==void 0&&sm({...n,input:null},n.executionStop);let i=new Set;for(let a of n.receipts){if(at(a,["outcomeId","hash"]),Be(a.outcomeId,"outcomeId"),!/^[a-f0-9]{64}$/.test(a.hash)||i.has(a.outcomeId))throw new b("INVALID_ACTION","结果记录的标识或摘要无效");i.add(a.outcomeId)}if(n.rejectedOutcomes!==void 0){if(!Array.isArray(n.rejectedOutcomes))throw new b("INVALID_ACTION","Action 的拒绝结果记录必须是数组");let a=new Set;for(let u of n.rejectedOutcomes){if(at(u,["outcome","code","reason"]),!["OUTPUT_INVALID","OUTCOME_REJECTED","OUTCOME_PROCESSING_ERROR"].includes(u.code))throw new b("INVALID_ACTION","Action 的拒绝结果代码无效");if(typeof u.reason!="string"||!u.reason.trim())throw new b("INVALID_ACTION","Action 的拒绝结果缺少原因");let f=tl(u.outcome),d=n.receipts.find(s=>s.outcomeId===f.outcomeId);if(a.has(f.outcomeId)||!d||d.hash!==z(f)||f.actionId!==n.id||f.inputHash!==n.inputHash||f.attempt>n.attempt||f.attempt===n.attempt&&n.claim?.token!==f.claimToken)throw new b("INVALID_ACTION","Action 的拒绝结果与当前执行记录不一致");a.add(f.outcomeId)}}let o=new Set;for(let a of n.reconciliations){if(at(a,["attempt","resolution","evidence"]),!Number.isSafeInteger(a.attempt)||a.attempt<1||a.attempt>=n.attempt||o.has(a.attempt)||a.resolution!=="not-executed"||a.evidence===null||a.evidence===void 0)throw new b("INVALID_ACTION","核对记录与执行尝试不一致");o.add(a.attempt)}if(n.status==="succeeded"||n.status==="failed"){if(at(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 a=n.receipts.find(u=>u.outcomeId===n.outcome.outcomeId);if(!a||a.hash!==z(n.outcome))throw new b("INVALID_ACTION","终态结果与已接受摘要不一致");rm({...n,input:null,status:"running",receipts:[]},n.outcome)}else if(n.outcome!==void 0)throw new b("INVALID_ACTION","非执行终态不能保存当前执行结果");return n}function um(e){return typeof e=="string"&&e.trim().length>0&&e.length<=4096}var hC=new WeakSet,gC=new WeakSet;var am=["protocolVersion","schemaVersion","runId","revision","workflow","definitionHashes","initialStateHash","input","state","status","sequence","actions","commands","actionContexts","waits","evidenceWaits","ready","joins","outputs","children","lineage","reason"];function T(e){throw new b("INVALID_RUN",e)}function Ce(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&T(`${t} 必须是 JSON 对象`),e}function et(e,t,n){for(let r of Object.keys(e))t.includes(r)||T(`${n} 包含不支持的字段:${r}`)}function Z(e,t){return(typeof e!="string"||!e.trim()||e.length>4096)&&T(`${t} 必须是非空字符串且不超过 4096 字符`),e}function er(e,t,n=0){return(!Number.isSafeInteger(e)||e<n)&&T(`${t} 必须是大于等于 ${n} 的安全整数`),e}function Yt(e,t){return(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&T(`${t} 必须是 SHA-256 摘要`),e}function cm(e,t,n=!1){let r=Ce(e,t);et(r,n?["id","version","hash"]:["id","version"],t);let i={id:Z(r.id,`${t}.id`),version:Z(r.version,`${t}.version`)};return n&&(i.hash=Yt(r.hash,`${t}.hash`)),i}function fi(e,t,n){let r=Ce(e,t);if(!n&&wt(r)&&gC.has(r))return r;let i=(o,a)=>{Z(o,`${t} step id`);let u=Ce(a,`${t}.${o}`);et(u,["sequence","value"],`${t}.${o}`),(!Object.hasOwn(u,"sequence")||!Object.hasOwn(u,"value"))&&T(`${t}.${o} 缺少 sequence 或 value`),er(u.sequence,`${t}.${o}.sequence`,1)};if(n)n.visitResults(r,i);else for(let[o,a]of Object.entries(r))i(o,a);return r}function lm(e,t,n){let r=Ce(e,t);return et(r,["from","to","results","activation"],t),(!Object.hasOwn(r,"from")||!Object.hasOwn(r,"to")||!Object.hasOwn(r,"results"))&&T(`${t} 缺少 from、to 或 results`),{from:r.from===null?null:Z(r.from,`${t}.from`),to:Z(r.to,`${t}.to`),results:fi(r.results,`${t}.results`,n),...Object.hasOwn(r,"activation")?{activation:r.activation}:{}}}function Qo(e,t,n,r){let i=`${t}:`;e.startsWith(i)||T(`${n} 不属于当前 Run`);let o=e.slice(i.length);/^[1-9][0-9]*$/.test(o)||T(`${n} 的步骤序号无效`);let a=Number(o);return(!Number.isSafeInteger(a)||a>r)&&T(`${n} 的步骤序号超出 Run 范围`),a}function wC(e,t,n,r){let i=Ce(e,"Wait");et(i,["id","stepId","sequence","status","proposal","proposalHash","choices","results","decision"],"Wait");for(let l of["id","stepId","sequence","status","proposal","proposalHash","choices","results"])Object.hasOwn(i,l)||T(`Wait 缺少 ${l}`);let o=Z(i.id,"Wait.id"),a=Z(i.stepId,"Wait.stepId"),u=er(i.sequence,"Wait.sequence",1);(u>n||Qo(o,t,"Wait.id",n)!==u)&&T("Wait 的 id 与 sequence 不一致"),["pending","resolved","cancelled"].includes(String(i.status))||T("Wait.status 无效"),(!Array.isArray(i.choices)||i.choices.length===0)&&T("Wait.choices 必须是非空数组");let f=i.choices.map(l=>Z(l,"Wait.choices"));new Set(f).size!==f.length&&T("Wait.choices 不能重复");let d=Yt(i.proposalHash,"Wait.proposalHash");z(i.proposal)!==d&&T("Wait.proposal 与 proposalHash 不一致");let s={id:o,stepId:a,sequence:u,status:i.status,proposal:i.proposal,proposalHash:d,choices:f,results:fi(i.results,"Wait.results",r)};if(i.decision!==void 0){let l=Ce(i.decision,"Wait.decision");et(l,["id","choice","proposalHash","reason"],"Wait.decision"),l.reason!==void 0&&!um(l.reason)&&T("Wait.decision.reason 必须是 1 到 4096 字符的非空文本");let m={id:Z(l.id,"Wait.decision.id"),choice:Z(l.choice,"Wait.decision.choice"),proposalHash:Yt(l.proposalHash,"Wait.decision.proposalHash"),...l.reason===void 0?{}:{reason:l.reason}};(i.status!=="resolved"||!f.includes(m.choice)||m.proposalHash!==d)&&T("Wait.decision 与 Wait 状态、选择或提案不一致"),s.decision=m}else i.status==="resolved"&&T("已解决的 Wait 必须保存对应 decision");return s}function yC(e,t,n,r){let i=Ce(e,"EvidenceWait");et(i,["id","stepId","sequence","kind","status","results","receipt","invalidation"],"EvidenceWait");let o=Z(i.id,"EvidenceWait.id"),a=er(i.sequence,"EvidenceWait.sequence",1);(a>n||Qo(o,t,"EvidenceWait.id",n)!==a)&&T("EvidenceWait 的 id 与 sequence 不一致"),["pending","resolved","invalidated","cancelled"].includes(String(i.status))||T("EvidenceWait.status 无效");let u={id:o,stepId:Z(i.stepId,"EvidenceWait.stepId"),sequence:a,kind:Z(i.kind,"EvidenceWait.kind"),status:i.status,results:fi(i.results,"EvidenceWait.results",r)};if(i.receipt!==void 0){let f=Ce(i.receipt,"EvidenceWait.receipt");et(f,["ref","contentHash","submissionId"],"EvidenceWait.receipt"),u.receipt={ref:Z(f.ref,"EvidenceWait.receipt.ref"),contentHash:Yt(f.contentHash,"EvidenceWait.receipt.contentHash"),submissionId:Z(f.submissionId,"EvidenceWait.receipt.submissionId")}}if(i.invalidation!==void 0){let f=Ce(i.invalidation,"EvidenceWait.invalidation");et(f,["ref","contentHash","submissionId","reason"],"EvidenceWait.invalidation"),u.invalidation={ref:Z(f.ref,"EvidenceWait.invalidation.ref"),contentHash:Yt(f.contentHash,"EvidenceWait.invalidation.contentHash"),submissionId:Z(f.submissionId,"EvidenceWait.invalidation.submissionId"),reason:Z(f.reason,"EvidenceWait.invalidation.reason")}}return(u.status==="resolved"!=!!u.receipt||u.status==="invalidated"!=!!u.invalidation)&&T("EvidenceWait.receipt 与状态不一致"),u}function Zo(e,t){let n=Ce(yt(e),"WorkflowRun");return dm(n,t)}function rl(e,t,n){return dm(Ce(e,"WorkflowRun"),t,void 0,n)}function dm(e,t,n,r){et(e,am,"WorkflowRun");for(let R of am.filter(N=>N!=="reason"&&N!=="state"&&N!=="evidenceWaits"&&N!=="initialStateHash"&&N!=="commands"))Object.hasOwn(e,R)||T(`WorkflowRun 缺少 ${R}`);if(e.protocolVersion!==1||e.schemaVersion!==1)throw new b("UNSUPPORTED_PROTOCOL","当前 Runtime 不支持此 Run 协议或状态版本");let i=Z(e.runId,"WorkflowRun.runId");t!==void 0&&i!==t&&T("WorkflowRun.runId 与存储键不一致");let o=er(e.revision,"WorkflowRun.revision",1),a=er(e.sequence,"WorkflowRun.sequence"),u=cm(e.workflow,"WorkflowRun.workflow",!0);["running","waiting","completed","failed","cancelled"].includes(String(e.status))||T("WorkflowRun.status 无效"),e.reason!==void 0&&Z(e.reason,"WorkflowRun.reason"),Object.hasOwn(e,"input")||T("WorkflowRun 缺少 input");let f=Ce(e.definitionHashes,"WorkflowRun.definitionHashes");Object.keys(f).length===0&&T("WorkflowRun.definitionHashes 不能为空");for(let[R,N]of Object.entries(f)){let q;try{q=JSON.parse(R)}catch{T("WorkflowRun.definitionHashes 包含无效的工作流引用")}(!Array.isArray(q)||q.length!==2||typeof q[0]!="string"||typeof q[1]!="string"||JSON.stringify(q)!==R)&&T("WorkflowRun.definitionHashes 包含非规范的工作流引用"),Yt(N,`WorkflowRun.definitionHashes.${R}`)}let d=JSON.stringify([u.id,u.version]);f[d]!==u.hash&&T("WorkflowRun.workflow 与固定定义摘要不一致"),(!Array.isArray(e.lineage)||e.lineage.length>32)&&T("WorkflowRun.lineage 必须是最多 32 层的数组");let s=e.lineage.map(R=>Z(R,"WorkflowRun.lineage"));(new Set(s).size!==s.length||s.includes(i))&&T("WorkflowRun.lineage 不能重复或包含当前 Run"),(!Array.isArray(e.actions)||!Array.isArray(e.waits))&&T("WorkflowRun.actions 和 waits 必须是数组");let l=e.actions.map(R=>{let N;try{N=R&&typeof R=="object"&&hC.has(R)&&wt(R)?R:nl(R,r?.hash(R.input))}catch(q){if(q instanceof b&&q.code==="UNSUPPORTED_PROTOCOL")throw q;T(`WorkflowRun.actions 包含无效 Action:${q.message}`)}return N.executionOrigin&&N.executionOrigin.workflow.id!==u.id&&T("Action 执行来源不属于当前工作流"),N.runId!==i&&T(`Action ${N.id} 不属于当前 Run`),new Set(N.requiredCapabilities).size!==N.requiredCapabilities.length&&T(`Action ${N.id} 的 requiredCapabilities 不能重复`),N}),m=new Map(l.map(R=>[R.id,R]));e.commands!==void 0&&!Array.isArray(e.commands)&&T("WorkflowRun.commands 必须是数组");let c=e.commands?.map(R=>{let N=Ce(R,"WorkflowRun.commands item");et(N,["id","name","inputHash","actionId"],"WorkflowRun.commands item");let q={id:Z(N.id,"WorkflowRun.commands.id"),name:Z(N.name,"WorkflowRun.commands.name"),inputHash:Yt(N.inputHash,"WorkflowRun.commands.inputHash"),actionId:Z(N.actionId,"WorkflowRun.commands.actionId")};return m.has(q.actionId)||T("WorkflowRun.commands 指向不存在的 Action"),q});c&&new Set(c.map(R=>R.id)).size!==c.length&&T("WorkflowRun.commands 标识不能重复");let p=e.waits.map(R=>wC(R,i,a,r));e.evidenceWaits!==void 0&&!Array.isArray(e.evidenceWaits)&&T("WorkflowRun.evidenceWaits 必须是数组");let h=e.evidenceWaits?.map(R=>yC(R,i,a,r))??[],g=new Map;for(let R of l){let N=Qo(R.id,i,"Action.id",a);g.has(N)&&T("WorkflowRun 的步骤序号不能重复"),g.set(N,R.stepId)}for(let R of p)g.has(R.sequence)&&T("WorkflowRun 的步骤序号不能重复"),g.set(R.sequence,R.stepId);for(let R of h)g.has(R.sequence)&&T("WorkflowRun 的步骤序号不能重复"),g.set(R.sequence,R.stepId);g.size!==a&&T("WorkflowRun.sequence 与已激活步骤数量不一致");let w=Ce(e.actionContexts,"WorkflowRun.actionContexts");Object.keys(w).length!==l.length&&T("WorkflowRun.actionContexts 必须与 actions 一一对应");let v=new Map,k=n?new Map([...n.actions.map(R=>[n.actionContexts[R.id].sequence,R.stepId]),...n.waits.map(R=>[R.sequence,R.stepId]),...(n.evidenceWaits??[]).map(R=>[R.sequence,R.stepId])]):void 0;if(n&&k&&n.runId===i&&[...k].every(([R,N])=>g.get(R)===N)){let R=(N,q)=>v.set(N,Math.min(v.get(N)??1/0,q));for(let N of Object.values(n.actionContexts))R(N.results,N.sequence);for(let N of n.waits)R(N.results,N.sequence);for(let N of n.evidenceWaits??[])R(N.results,N.sequence);for(let N of n.ready)R(N.results,n.sequence+1);for(let N of Object.values(n.joins))for(let q of Object.values(N))for(let me of q)R(me.results,n.sequence+1);R(n.outputs,n.sequence+1)}let S=new Map;function E(R,N){let q=N??a+1;if(r){r.validateOrigins(R,g,q);return}let me=v.get(R);if(!(me!==void 0&&q>=me&&wt(R))&&!((S.get(R)??1/0)<=q)){S.set(R,q);for(let[y,x]of Object.entries(R))(x.sequence>=(N??a+1)||g.get(x.sequence)!==y)&&T(`WorkflowRun 结果 ${y} 的序号或来源不一致`)}}for(let R of l){Object.hasOwn(w,R.id)||T(`Action ${R.id} 缺少上下文`);let N=Ce(w[R.id],`actionContexts.${R.id}`);et(N,["sequence","results"],`actionContexts.${R.id}`);let q=er(N.sequence,`actionContexts.${R.id}.sequence`,1);q!==Qo(R.id,i,"Action.id",a)&&T(`Action ${R.id} 的上下文序号不一致`);let me=fi(N.results,`actionContexts.${R.id}.results`,r);E(me,q)}for(let R of p)E(R.results,R.sequence);for(let R of h)E(R.results,R.sequence);Array.isArray(e.ready)||T("WorkflowRun.ready 必须是数组");let A=e.ready.map(R=>lm(R,"WorkflowRun.ready token",r));for(let R of A)E(R.results);let M=Ce(e.joins,"WorkflowRun.joins"),O=Object.fromEntries(Object.entries(M).map(([R,N])=>{Z(R,"WorkflowRun.joins step id");let q=Ce(N,`WorkflowRun.joins.${R}`),me=Object.fromEntries(Object.entries(q).map(([y,x])=>{Z(y,"WorkflowRun.joins parent id"),Array.isArray(x)||T(`WorkflowRun.joins.${R}.${y} 必须是数组`);let C=x.map(P=>{let I=lm(P,`WorkflowRun.joins.${R}.${y}`,r);return(I.to!==R||I.from!==y)&&T(`WorkflowRun.joins.${R}.${y} 包含错误来源的 token`),E(I.results),I});return[y,C]}));return[R,me]})),L=fi(e.outputs,"WorkflowRun.outputs",r);E(L),Array.isArray(e.children)||T("WorkflowRun.children 必须是数组");let $=e.children.map(R=>{let N=Ce(R,"WorkflowRun.children item");et(N,["actionId","runId","workflow"],"WorkflowRun.children item");let q=cm(N.workflow,"WorkflowRun.children.workflow"),me=Z(N.actionId,"WorkflowRun.children.actionId"),y=Z(N.runId,"WorkflowRun.children.runId"),x=m.get(me);return(!x||x.type!=="child_workflow"||x.ref!==`${q.id}@${q.version}`||y!==`child-${z(me)}`||!Object.hasOwn(f,JSON.stringify([q.id,q.version])))&&T("WorkflowRun.children 与子工作流 Action 或固定定义不一致"),{actionId:me,runId:y,workflow:q}});(new Set($.map(R=>R.actionId)).size!==$.length||l.filter(R=>R.type==="child_workflow").length!==$.length)&&T("每个子工作流 Action 必须恰好对应一个 Child Run");let F=l.some(R=>["pending","running","unknown"].includes(R.status)),re=p.some(R=>R.status==="pending"),X=h.some(R=>R.status==="pending"),te=Object.values(O).some(R=>Object.values(R).some(N=>N.length>0));return e.status==="running"&&!F&&A.length===0&&T("running Run 必须包含待调度步骤、待执行或已派发的 Action"),e.status==="waiting"&&(F||!re&&!X&&!te||A.length>0)&&T("waiting Run 必须只有未解决的 Wait 或不完整 join"),e.status==="completed"&&(F||re||X||te||A.length>0)&&T("completed Run 不能遗留待执行、等待或 join 工作"),(e.status==="failed"||e.status==="cancelled")&&e.reason===void 0&&T(`${String(e.status)} Run 必须记录停止原因`),{protocolVersion:1,schemaVersion:1,runId:i,revision:o,workflow:u,definitionHashes:f,...e.initialStateHash===void 0?{}:{initialStateHash:Yt(e.initialStateHash,"WorkflowRun.initialStateHash")},input:e.input,...e.state===void 0?{}:{state:e.state},status:e.status,sequence:a,actions:l,...c===void 0?{}:{commands:c},actionContexts:w,waits:p,...e.evidenceWaits===void 0?{}:{evidenceWaits:h},ready:A,joins:O,outputs:L,children:$,lineage:s,...e.reason===void 0?{}:{reason:e.reason}}}var ue=De(pm(),1),j_=(()=>{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=ue.default.default??ue.default;function i(o,{instancePath:a="",parentData:u,parentDataProperty:f,rootData:d=o}={}){let s=null,l=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.action===void 0){let m={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"action"},message:"must have required property 'action'"};s===null?s=[m]:s.push(m),l++}if(o.targetBranch===void 0){let m={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};s===null?s=[m]:s.push(m),l++}if(o.commit===void 0){let m={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"commit"},message:"must have required property 'commit'"};s===null?s=[m]:s.push(m),l++}for(let m in o)if(!(m==="action"||m==="commit"||m==="prUrl"||m==="remote"||m==="targetBranch")){let c={instancePath:a,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:m},message:"must NOT have additional properties"};s===null?s=[c]:s.push(c),l++}if(o.action!==void 0){let m=o.action;if(!(m==="local"||m==="push"||m==="pr")){let c={instancePath:a+"/action",schemaPath:"#/properties/action/enum",keyword:"enum",params:{allowedValues:t.properties.action.enum},message:"must be equal to one of the allowed values"};s===null?s=[c]:s.push(c),l++}}if(o.commit!==void 0){let m=o.commit;if(typeof m=="string"){if(!n.test(m)){let c={instancePath:a+"/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})?$"'};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/commit",schemaPath:"#/properties/commit/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}if(o.prUrl!==void 0){let m=o.prUrl;if(typeof m=="string"){if(r(m)<1){let c={instancePath:a+"/prUrl",schemaPath:"#/properties/prUrl/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/prUrl",schemaPath:"#/properties/prUrl/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}if(o.remote!==void 0){let m=o.remote;if(typeof m=="string"){if(r(m)<1){let c={instancePath:a+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}if(o.targetBranch!==void 0){let m=o.targetBranch;if(typeof m=="string"){if(r(m)<1){let c={instancePath:a+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}}else{let m={instancePath:a,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[m]:s.push(m),l++}return i.errors=s,l===0}return e.exports})(),D_=(()=>{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(o,{instancePath:a="",parentData:u,parentDataProperty:f,rootData:d=o}={}){let s=null,l=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.workflow===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};s===null?s=[c]:s.push(c),l++}if(o.language===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};s===null?s=[c]:s.push(c),l++}if(o.phase===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};s===null?s=[c]:s.push(c),l++}if(o.contextCompression===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};s===null?s=[c]:s.push(c),l++}if(o.buildMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};s===null?s=[c]:s.push(c),l++}if(o.buildPause===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};s===null?s=[c]:s.push(c),l++}if(o.subagentDispatch===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};s===null?s=[c]:s.push(c),l++}if(o.tddMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};s===null?s=[c]:s.push(c),l++}if(o.reviewMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};s===null?s=[c]:s.push(c),l++}if(o.isolation===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};s===null?s=[c]:s.push(c),l++}if(o.boundBranch===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};s===null?s=[c]:s.push(c),l++}if(o.verifyMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};s===null?s=[c]:s.push(c),l++}if(o.autoTransition===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};s===null?s=[c]:s.push(c),l++}if(o.baseRef===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};s===null?s=[c]:s.push(c),l++}if(o.designDoc===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};s===null?s=[c]:s.push(c),l++}if(o.plan===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};s===null?s=[c]:s.push(c),l++}if(o.verifyResult===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};s===null?s=[c]:s.push(c),l++}if(o.verifyFailures===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};s===null?s=[c]:s.push(c),l++}if(o.verificationReport===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};s===null?s=[c]:s.push(c),l++}if(o.branchStatus===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};s===null?s=[c]:s.push(c),l++}if(o.createdAt===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};s===null?s=[c]:s.push(c),l++}if(o.verifiedAt===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};s===null?s=[c]:s.push(c),l++}if(o.archiveConfirmation===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};s===null?s=[c]:s.push(c),l++}if(o.archived===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};s===null?s=[c]:s.push(c),l++}if(o.directOverride===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};s===null?s=[c]:s.push(c),l++}if(o.handoffContext===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};s===null?s=[c]:s.push(c),l++}if(o.handoffHash===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};s===null?s=[c]:s.push(c),l++}if(o.classicProfile===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};s===null?s=[c]:s.push(c),l++}if(o.classicMigration===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};s===null?s=[c]:s.push(c),l++}for(let c in o)if(!n.call(t.properties,c)){let p={instancePath:a,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};s===null?s=[p]:s.push(p),l++}if(o.archiveConfirmation!==void 0){let c=o.archiveConfirmation;if(!(c===null||c==="pending"||c==="confirmed")){let p={instancePath:a+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.archived!==void 0&&typeof o.archived!="boolean"){let c={instancePath:a+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};s===null?s=[c]:s.push(c),l++}if(o.autoTransition!==void 0){let c=o.autoTransition;if(typeof c!="boolean"&&c!==null){let p={instancePath:a+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};s===null?s=[p]:s.push(p),l++}}if(o.baseRef!==void 0){let c=o.baseRef;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.boundBranch!==void 0){let c=o.boundBranch;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.branchStatus!==void 0){let c=o.branchStatus;if(!(c===null||c==="pending"||c==="handled")){let p={instancePath:a+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.buildMode!==void 0){let c=o.buildMode;if(!(c===null||c==="subagent-driven-development"||c==="executing-plans"||c==="direct"||c==="autonomous")){let p={instancePath:a+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.buildPause!==void 0){let c=o.buildPause;if(!(c===null||c==="plan-ready")){let p={instancePath:a+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.checkEpoch!==void 0){let c=o.checkEpoch;if(!(typeof c=="number"&&!(c%1)&&!isNaN(c)&&isFinite(c))){let p={instancePath:a+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};s===null?s=[p]:s.push(p),l++}if(typeof c=="number"&&isFinite(c)&&(c<0||isNaN(c))){let p={instancePath:a+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};s===null?s=[p]:s.push(p),l++}}if(o.classicMigration!==void 0){let c=o.classicMigration;if(!(c===null||c===1)){let p={instancePath:a+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.classicProfile!==void 0){let c=o.classicProfile;if(!(c===null||c==="full"||c==="hotfix"||c==="tweak")){let p={instancePath:a+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.contextCompression!==void 0){let c=o.contextCompression;if(!(c===null||c==="off"||c==="beta")){let p={instancePath:a+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.createdAt!==void 0){let c=o.createdAt;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.designDoc!==void 0){let c=o.designDoc;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.directOverride!==void 0){let c=o.directOverride;if(typeof c!="boolean"&&c!==null){let p={instancePath:a+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};s===null?s=[p]:s.push(p),l++}}if(o.handoffContext!==void 0){let c=o.handoffContext;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.handoffHash!==void 0){let c=o.handoffHash,p=l,h=!1,g=l;if(c!==null){let w={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};s===null?s=[w]:s.push(w),l++}var m=g===l;if(h=h||m,!h){let w=l;if(typeof c=="string"){if(!r.test(c)){let k={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};s===null?s=[k]:s.push(k),l++}}else{let k={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[k]:s.push(k),l++}var m=w===l;h=h||m}if(h)l=p,s!==null&&(p?s.length=p:s=null);else{let w={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};s===null?s=[w]:s.push(w),l++}}if(o.isolation!==void 0){let c=o.isolation;if(!(c===null||c==="current"||c==="branch"||c==="worktree")){let p={instancePath:a+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.language!==void 0){let c=o.language;if(!(c===null||c==="en"||c==="zh-CN")){let p={instancePath:a+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.phase!==void 0){let c=o.phase;if(!(c==="open"||c==="design"||c==="build"||c==="verify"||c==="archive")){let p={instancePath:a+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.plan!==void 0){let c=o.plan;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.reviewMode!==void 0){let c=o.reviewMode;if(!(c===null||c==="off"||c==="standard"||c==="thorough")){let p={instancePath:a+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.subagentDispatch!==void 0){let c=o.subagentDispatch;if(!(c===null||c==="confirmed")){let p={instancePath:a+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.tddMode!==void 0){let c=o.tddMode;if(!(c===null||c==="tdd"||c==="direct")){let p={instancePath:a+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.verificationReport!==void 0){let c=o.verificationReport;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.verifiedAt!==void 0){let c=o.verifiedAt;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.verifyFailures!==void 0){let c=o.verifyFailures;if(!(typeof c=="number"&&!(c%1)&&!isNaN(c)&&isFinite(c))){let p={instancePath:a+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};s===null?s=[p]:s.push(p),l++}if(typeof c=="number"&&isFinite(c)&&(c<0||isNaN(c))){let p={instancePath:a+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};s===null?s=[p]:s.push(p),l++}}if(o.verifyMode!==void 0){let c=o.verifyMode;if(!(c===null||c==="light"||c==="full")){let p={instancePath:a+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.verifyResult!==void 0){let c=o.verifyResult;if(!(c==="pending"||c==="pass"||c==="fail")){let p={instancePath:a+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.workflow!==void 0&&o.workflow!=="full"){let c={instancePath:a+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[c]:s.push(c),l++}return i.errors=s,l===0}return e.exports})(),L_=(()=>{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(o,{instancePath:a="",parentData:u,parentDataProperty:f,rootData:d=o}={}){let s=null,l=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.workflow===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};s===null?s=[c]:s.push(c),l++}if(o.language===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};s===null?s=[c]:s.push(c),l++}if(o.phase===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};s===null?s=[c]:s.push(c),l++}if(o.contextCompression===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};s===null?s=[c]:s.push(c),l++}if(o.buildMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};s===null?s=[c]:s.push(c),l++}if(o.buildPause===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};s===null?s=[c]:s.push(c),l++}if(o.subagentDispatch===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};s===null?s=[c]:s.push(c),l++}if(o.tddMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};s===null?s=[c]:s.push(c),l++}if(o.reviewMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};s===null?s=[c]:s.push(c),l++}if(o.isolation===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};s===null?s=[c]:s.push(c),l++}if(o.boundBranch===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};s===null?s=[c]:s.push(c),l++}if(o.verifyMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};s===null?s=[c]:s.push(c),l++}if(o.autoTransition===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};s===null?s=[c]:s.push(c),l++}if(o.baseRef===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};s===null?s=[c]:s.push(c),l++}if(o.designDoc===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};s===null?s=[c]:s.push(c),l++}if(o.plan===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};s===null?s=[c]:s.push(c),l++}if(o.verifyResult===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};s===null?s=[c]:s.push(c),l++}if(o.verifyFailures===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};s===null?s=[c]:s.push(c),l++}if(o.verificationReport===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};s===null?s=[c]:s.push(c),l++}if(o.branchStatus===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};s===null?s=[c]:s.push(c),l++}if(o.createdAt===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};s===null?s=[c]:s.push(c),l++}if(o.verifiedAt===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};s===null?s=[c]:s.push(c),l++}if(o.archiveConfirmation===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};s===null?s=[c]:s.push(c),l++}if(o.archived===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};s===null?s=[c]:s.push(c),l++}if(o.directOverride===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};s===null?s=[c]:s.push(c),l++}if(o.handoffContext===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};s===null?s=[c]:s.push(c),l++}if(o.handoffHash===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};s===null?s=[c]:s.push(c),l++}if(o.classicProfile===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};s===null?s=[c]:s.push(c),l++}if(o.classicMigration===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};s===null?s=[c]:s.push(c),l++}for(let c in o)if(!n.call(t.properties,c)){let p={instancePath:a,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};s===null?s=[p]:s.push(p),l++}if(o.archiveConfirmation!==void 0){let c=o.archiveConfirmation;if(!(c===null||c==="pending"||c==="confirmed")){let p={instancePath:a+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.archived!==void 0&&typeof o.archived!="boolean"){let c={instancePath:a+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};s===null?s=[c]:s.push(c),l++}if(o.autoTransition!==void 0){let c=o.autoTransition;if(typeof c!="boolean"&&c!==null){let p={instancePath:a+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};s===null?s=[p]:s.push(p),l++}}if(o.baseRef!==void 0){let c=o.baseRef;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.boundBranch!==void 0){let c=o.boundBranch;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.branchStatus!==void 0){let c=o.branchStatus;if(!(c===null||c==="pending"||c==="handled")){let p={instancePath:a+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.buildMode!==void 0){let c=o.buildMode;if(!(c===null||c==="subagent-driven-development"||c==="executing-plans"||c==="direct"||c==="autonomous")){let p={instancePath:a+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.buildPause!==void 0){let c=o.buildPause;if(!(c===null||c==="plan-ready")){let p={instancePath:a+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.checkEpoch!==void 0){let c=o.checkEpoch;if(!(typeof c=="number"&&!(c%1)&&!isNaN(c)&&isFinite(c))){let p={instancePath:a+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};s===null?s=[p]:s.push(p),l++}if(typeof c=="number"&&isFinite(c)&&(c<0||isNaN(c))){let p={instancePath:a+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};s===null?s=[p]:s.push(p),l++}}if(o.classicMigration!==void 0){let c=o.classicMigration;if(!(c===null||c===1)){let p={instancePath:a+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.classicProfile!==void 0){let c=o.classicProfile;if(!(c===null||c==="full"||c==="hotfix"||c==="tweak")){let p={instancePath:a+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.contextCompression!==void 0){let c=o.contextCompression;if(!(c===null||c==="off"||c==="beta")){let p={instancePath:a+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.createdAt!==void 0){let c=o.createdAt;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.designDoc!==void 0){let c=o.designDoc;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.directOverride!==void 0){let c=o.directOverride;if(typeof c!="boolean"&&c!==null){let p={instancePath:a+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};s===null?s=[p]:s.push(p),l++}}if(o.handoffContext!==void 0){let c=o.handoffContext;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.handoffHash!==void 0){let c=o.handoffHash,p=l,h=!1,g=l;if(c!==null){let w={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};s===null?s=[w]:s.push(w),l++}var m=g===l;if(h=h||m,!h){let w=l;if(typeof c=="string"){if(!r.test(c)){let k={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};s===null?s=[k]:s.push(k),l++}}else{let k={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[k]:s.push(k),l++}var m=w===l;h=h||m}if(h)l=p,s!==null&&(p?s.length=p:s=null);else{let w={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};s===null?s=[w]:s.push(w),l++}}if(o.isolation!==void 0){let c=o.isolation;if(!(c===null||c==="current"||c==="branch"||c==="worktree")){let p={instancePath:a+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.language!==void 0){let c=o.language;if(!(c===null||c==="en"||c==="zh-CN")){let p={instancePath:a+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.phase!==void 0){let c=o.phase;if(!(c==="open"||c==="design"||c==="build"||c==="verify"||c==="archive")){let p={instancePath:a+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.plan!==void 0){let c=o.plan;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.reviewMode!==void 0){let c=o.reviewMode;if(!(c===null||c==="off"||c==="standard"||c==="thorough")){let p={instancePath:a+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.subagentDispatch!==void 0){let c=o.subagentDispatch;if(!(c===null||c==="confirmed")){let p={instancePath:a+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.tddMode!==void 0){let c=o.tddMode;if(!(c===null||c==="tdd"||c==="direct")){let p={instancePath:a+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.verificationReport!==void 0){let c=o.verificationReport;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.verifiedAt!==void 0){let c=o.verifiedAt;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.verifyFailures!==void 0){let c=o.verifyFailures;if(!(typeof c=="number"&&!(c%1)&&!isNaN(c)&&isFinite(c))){let p={instancePath:a+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};s===null?s=[p]:s.push(p),l++}if(typeof c=="number"&&isFinite(c)&&(c<0||isNaN(c))){let p={instancePath:a+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};s===null?s=[p]:s.push(p),l++}}if(o.verifyMode!==void 0){let c=o.verifyMode;if(!(c===null||c==="light"||c==="full")){let p={instancePath:a+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.verifyResult!==void 0){let c=o.verifyResult;if(!(c==="pending"||c==="pass"||c==="fail")){let p={instancePath:a+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.workflow!==void 0){let c=o.workflow;if(!(c==="hotfix"||c==="full")){let p={instancePath:a+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}}else{let c={instancePath:a,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[c]:s.push(c),l++}return i.errors=s,l===0}return e.exports})(),q_=(()=>{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(o,{instancePath:a="",parentData:u,parentDataProperty:f,rootData:d=o}={}){let s=null,l=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.workflow===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"workflow"},message:"must have required property 'workflow'"};s===null?s=[c]:s.push(c),l++}if(o.language===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"language"},message:"must have required property 'language'"};s===null?s=[c]:s.push(c),l++}if(o.phase===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"phase"},message:"must have required property 'phase'"};s===null?s=[c]:s.push(c),l++}if(o.contextCompression===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contextCompression"},message:"must have required property 'contextCompression'"};s===null?s=[c]:s.push(c),l++}if(o.buildMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};s===null?s=[c]:s.push(c),l++}if(o.buildPause===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildPause"},message:"must have required property 'buildPause'"};s===null?s=[c]:s.push(c),l++}if(o.subagentDispatch===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"subagentDispatch"},message:"must have required property 'subagentDispatch'"};s===null?s=[c]:s.push(c),l++}if(o.tddMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};s===null?s=[c]:s.push(c),l++}if(o.reviewMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};s===null?s=[c]:s.push(c),l++}if(o.isolation===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};s===null?s=[c]:s.push(c),l++}if(o.boundBranch===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"boundBranch"},message:"must have required property 'boundBranch'"};s===null?s=[c]:s.push(c),l++}if(o.verifyMode===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyMode"},message:"must have required property 'verifyMode'"};s===null?s=[c]:s.push(c),l++}if(o.autoTransition===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"autoTransition"},message:"must have required property 'autoTransition'"};s===null?s=[c]:s.push(c),l++}if(o.baseRef===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseRef"},message:"must have required property 'baseRef'"};s===null?s=[c]:s.push(c),l++}if(o.designDoc===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};s===null?s=[c]:s.push(c),l++}if(o.plan===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};s===null?s=[c]:s.push(c),l++}if(o.verifyResult===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyResult"},message:"must have required property 'verifyResult'"};s===null?s=[c]:s.push(c),l++}if(o.verifyFailures===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifyFailures"},message:"must have required property 'verifyFailures'"};s===null?s=[c]:s.push(c),l++}if(o.verificationReport===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verificationReport"},message:"must have required property 'verificationReport'"};s===null?s=[c]:s.push(c),l++}if(o.branchStatus===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"branchStatus"},message:"must have required property 'branchStatus'"};s===null?s=[c]:s.push(c),l++}if(o.createdAt===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"createdAt"},message:"must have required property 'createdAt'"};s===null?s=[c]:s.push(c),l++}if(o.verifiedAt===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedAt"},message:"must have required property 'verifiedAt'"};s===null?s=[c]:s.push(c),l++}if(o.archiveConfirmation===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveConfirmation"},message:"must have required property 'archiveConfirmation'"};s===null?s=[c]:s.push(c),l++}if(o.archived===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archived"},message:"must have required property 'archived'"};s===null?s=[c]:s.push(c),l++}if(o.directOverride===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"directOverride"},message:"must have required property 'directOverride'"};s===null?s=[c]:s.push(c),l++}if(o.handoffContext===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffContext"},message:"must have required property 'handoffContext'"};s===null?s=[c]:s.push(c),l++}if(o.handoffHash===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"handoffHash"},message:"must have required property 'handoffHash'"};s===null?s=[c]:s.push(c),l++}if(o.classicProfile===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicProfile"},message:"must have required property 'classicProfile'"};s===null?s=[c]:s.push(c),l++}if(o.classicMigration===void 0){let c={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"classicMigration"},message:"must have required property 'classicMigration'"};s===null?s=[c]:s.push(c),l++}for(let c in o)if(!n.call(t.properties,c)){let p={instancePath:a,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};s===null?s=[p]:s.push(p),l++}if(o.archiveConfirmation!==void 0){let c=o.archiveConfirmation;if(!(c===null||c==="pending"||c==="confirmed")){let p={instancePath:a+"/archiveConfirmation",schemaPath:"#/properties/archiveConfirmation/enum",keyword:"enum",params:{allowedValues:t.properties.archiveConfirmation.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.archived!==void 0&&typeof o.archived!="boolean"){let c={instancePath:a+"/archived",schemaPath:"#/properties/archived/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};s===null?s=[c]:s.push(c),l++}if(o.autoTransition!==void 0){let c=o.autoTransition;if(typeof c!="boolean"&&c!==null){let p={instancePath:a+"/autoTransition",schemaPath:"#/properties/autoTransition/type",keyword:"type",params:{type:t.properties.autoTransition.type},message:"must be boolean,null"};s===null?s=[p]:s.push(p),l++}}if(o.baseRef!==void 0){let c=o.baseRef;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/baseRef",schemaPath:"#/properties/baseRef/type",keyword:"type",params:{type:t.properties.baseRef.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.boundBranch!==void 0){let c=o.boundBranch;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.branchStatus!==void 0){let c=o.branchStatus;if(!(c===null||c==="pending"||c==="handled")){let p={instancePath:a+"/branchStatus",schemaPath:"#/properties/branchStatus/enum",keyword:"enum",params:{allowedValues:t.properties.branchStatus.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.buildMode!==void 0){let c=o.buildMode;if(!(c===null||c==="subagent-driven-development"||c==="executing-plans"||c==="direct"||c==="autonomous")){let p={instancePath:a+"/buildMode",schemaPath:"#/properties/buildMode/enum",keyword:"enum",params:{allowedValues:t.properties.buildMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.buildPause!==void 0){let c=o.buildPause;if(!(c===null||c==="plan-ready")){let p={instancePath:a+"/buildPause",schemaPath:"#/properties/buildPause/enum",keyword:"enum",params:{allowedValues:t.properties.buildPause.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.checkEpoch!==void 0){let c=o.checkEpoch;if(!(typeof c=="number"&&!(c%1)&&!isNaN(c)&&isFinite(c))){let p={instancePath:a+"/checkEpoch",schemaPath:"#/properties/checkEpoch/type",keyword:"type",params:{type:"integer"},message:"must be integer"};s===null?s=[p]:s.push(p),l++}if(typeof c=="number"&&isFinite(c)&&(c<0||isNaN(c))){let p={instancePath:a+"/checkEpoch",schemaPath:"#/properties/checkEpoch/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};s===null?s=[p]:s.push(p),l++}}if(o.classicMigration!==void 0){let c=o.classicMigration;if(!(c===null||c===1)){let p={instancePath:a+"/classicMigration",schemaPath:"#/properties/classicMigration/enum",keyword:"enum",params:{allowedValues:t.properties.classicMigration.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.classicProfile!==void 0){let c=o.classicProfile;if(!(c===null||c==="full"||c==="hotfix"||c==="tweak")){let p={instancePath:a+"/classicProfile",schemaPath:"#/properties/classicProfile/enum",keyword:"enum",params:{allowedValues:t.properties.classicProfile.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.contextCompression!==void 0){let c=o.contextCompression;if(!(c===null||c==="off"||c==="beta")){let p={instancePath:a+"/contextCompression",schemaPath:"#/properties/contextCompression/enum",keyword:"enum",params:{allowedValues:t.properties.contextCompression.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.createdAt!==void 0){let c=o.createdAt;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/createdAt",schemaPath:"#/properties/createdAt/type",keyword:"type",params:{type:t.properties.createdAt.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.designDoc!==void 0){let c=o.designDoc;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:t.properties.designDoc.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.directOverride!==void 0){let c=o.directOverride;if(typeof c!="boolean"&&c!==null){let p={instancePath:a+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:t.properties.directOverride.type},message:"must be boolean,null"};s===null?s=[p]:s.push(p),l++}}if(o.handoffContext!==void 0){let c=o.handoffContext;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:t.properties.handoffContext.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.handoffHash!==void 0){let c=o.handoffHash,p=l,h=!1,g=l;if(c!==null){let w={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/0/type",keyword:"type",params:{type:"null"},message:"must be null"};s===null?s=[w]:s.push(w),l++}var m=g===l;if(h=h||m,!h){let w=l;if(typeof c=="string"){if(!r.test(c)){let k={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};s===null?s=[k]:s.push(k),l++}}else{let k={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf/1/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[k]:s.push(k),l++}var m=w===l;h=h||m}if(h)l=p,s!==null&&(p?s.length=p:s=null);else{let w={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};s===null?s=[w]:s.push(w),l++}}if(o.isolation!==void 0){let c=o.isolation;if(!(c===null||c==="current"||c==="branch"||c==="worktree")){let p={instancePath:a+"/isolation",schemaPath:"#/properties/isolation/enum",keyword:"enum",params:{allowedValues:t.properties.isolation.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.language!==void 0){let c=o.language;if(!(c===null||c==="en"||c==="zh-CN")){let p={instancePath:a+"/language",schemaPath:"#/properties/language/enum",keyword:"enum",params:{allowedValues:t.properties.language.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.phase!==void 0){let c=o.phase;if(!(c==="open"||c==="design"||c==="build"||c==="verify"||c==="archive")){let p={instancePath:a+"/phase",schemaPath:"#/properties/phase/enum",keyword:"enum",params:{allowedValues:t.properties.phase.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.plan!==void 0){let c=o.plan;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:t.properties.plan.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.reviewMode!==void 0){let c=o.reviewMode;if(!(c===null||c==="off"||c==="standard"||c==="thorough")){let p={instancePath:a+"/reviewMode",schemaPath:"#/properties/reviewMode/enum",keyword:"enum",params:{allowedValues:t.properties.reviewMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.subagentDispatch!==void 0){let c=o.subagentDispatch;if(!(c===null||c==="confirmed")){let p={instancePath:a+"/subagentDispatch",schemaPath:"#/properties/subagentDispatch/enum",keyword:"enum",params:{allowedValues:t.properties.subagentDispatch.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.tddMode!==void 0){let c=o.tddMode;if(!(c===null||c==="tdd"||c==="direct")){let p={instancePath:a+"/tddMode",schemaPath:"#/properties/tddMode/enum",keyword:"enum",params:{allowedValues:t.properties.tddMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.verificationReport!==void 0){let c=o.verificationReport;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:t.properties.verificationReport.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.verifiedAt!==void 0){let c=o.verifiedAt;if(typeof c!="string"&&c!==null){let p={instancePath:a+"/verifiedAt",schemaPath:"#/properties/verifiedAt/type",keyword:"type",params:{type:t.properties.verifiedAt.type},message:"must be string,null"};s===null?s=[p]:s.push(p),l++}}if(o.verifyFailures!==void 0){let c=o.verifyFailures;if(!(typeof c=="number"&&!(c%1)&&!isNaN(c)&&isFinite(c))){let p={instancePath:a+"/verifyFailures",schemaPath:"#/properties/verifyFailures/type",keyword:"type",params:{type:"integer"},message:"must be integer"};s===null?s=[p]:s.push(p),l++}if(typeof c=="number"&&isFinite(c)&&(c<0||isNaN(c))){let p={instancePath:a+"/verifyFailures",schemaPath:"#/properties/verifyFailures/minimum",keyword:"minimum",params:{comparison:">=",limit:0},message:"must be >= 0"};s===null?s=[p]:s.push(p),l++}}if(o.verifyMode!==void 0){let c=o.verifyMode;if(!(c===null||c==="light"||c==="full")){let p={instancePath:a+"/verifyMode",schemaPath:"#/properties/verifyMode/enum",keyword:"enum",params:{allowedValues:t.properties.verifyMode.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.verifyResult!==void 0){let c=o.verifyResult;if(!(c==="pending"||c==="pass"||c==="fail")){let p={instancePath:a+"/verifyResult",schemaPath:"#/properties/verifyResult/enum",keyword:"enum",params:{allowedValues:t.properties.verifyResult.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}if(o.workflow!==void 0){let c=o.workflow;if(!(c==="tweak"||c==="full")){let p={instancePath:a+"/workflow",schemaPath:"#/properties/workflow/enum",keyword:"enum",params:{allowedValues:t.properties.workflow.enum},message:"must be equal to one of the allowed values"};s===null?s=[p]:s.push(p),l++}}}else{let c={instancePath:a,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[c]:s.push(c),l++}return i.errors=s,l===0}return e.exports})(),$_=(()=>{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=ue.default.default??ue.default;function r(i,{instancePath:o="",parentData:a,parentDataProperty:u,rootData:f=i}={}){let d=null,s=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.archiveDirectory===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"archiveDirectory"},message:"must have required property 'archiveDirectory'"};d===null?d=[l]:d.push(l),s++}for(let l in i)if(l!=="archiveDirectory"){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};d===null?d=[m]:d.push(m),s++}if(i.archiveDirectory!==void 0){let l=i.archiveDirectory;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/archiveDirectory",schemaPath:"#/properties/archiveDirectory/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/archiveDirectory",schemaPath:"#/properties/archiveDirectory/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}}else{let l={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),s++}return r.errors=d,s===0}return e.exports})(),M_=(()=>{let e={exports:{}};e.exports=o,e.exports.default=o;let t={additionalProperties:!1,properties:{baseCommit:{pattern:"^[0-9a-f]{40}(?:[0-9a-f]{24})?$",type:"string"},deliveryAction:{enum:["local","push","pr"]},deliveryPaths:{items:{minLength:1,type:"string"},type:"array"},prBaseBranch:{minLength:1,type:"string"},remote:{minLength:1,type:"string"},remoteIdentity:{pattern:"^[0-9a-f]{64}$",type:"string"},targetBranch:{minLength:1,type:"string"},verifiedBranch:{minLength:1,type:"string"}},required:["deliveryAction","targetBranch","verifiedBranch","baseCommit"],type:"object"},n=new RegExp("^[0-9a-f]{40}(?:[0-9a-f]{24})?$","u"),r=new RegExp("^[0-9a-f]{64}$","u"),i=ue.default.default??ue.default;function o(a,{instancePath:u="",parentData:f,parentDataProperty:d,rootData:s=a}={}){let l=null,m=0;if(a&&typeof a=="object"&&!Array.isArray(a)){if(a.deliveryAction===void 0){let c={instancePath:u,schemaPath:"#/required",keyword:"required",params:{missingProperty:"deliveryAction"},message:"must have required property 'deliveryAction'"};l===null?l=[c]:l.push(c),m++}if(a.targetBranch===void 0){let c={instancePath:u,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};l===null?l=[c]:l.push(c),m++}if(a.verifiedBranch===void 0){let c={instancePath:u,schemaPath:"#/required",keyword:"required",params:{missingProperty:"verifiedBranch"},message:"must have required property 'verifiedBranch'"};l===null?l=[c]:l.push(c),m++}if(a.baseCommit===void 0){let c={instancePath:u,schemaPath:"#/required",keyword:"required",params:{missingProperty:"baseCommit"},message:"must have required property 'baseCommit'"};l===null?l=[c]:l.push(c),m++}for(let c in a)if(!(c==="baseCommit"||c==="deliveryAction"||c==="deliveryPaths"||c==="prBaseBranch"||c==="remote"||c==="remoteIdentity"||c==="targetBranch"||c==="verifiedBranch")){let p={instancePath:u,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};l===null?l=[p]:l.push(p),m++}if(a.baseCommit!==void 0){let c=a.baseCommit;if(typeof c=="string"){if(!n.test(c)){let p={instancePath:u+"/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})?$"'};l===null?l=[p]:l.push(p),m++}}else{let p={instancePath:u+"/baseCommit",schemaPath:"#/properties/baseCommit/type",keyword:"type",params:{type:"string"},message:"must be string"};l===null?l=[p]:l.push(p),m++}}if(a.deliveryAction!==void 0){let c=a.deliveryAction;if(!(c==="local"||c==="push"||c==="pr")){let p={instancePath:u+"/deliveryAction",schemaPath:"#/properties/deliveryAction/enum",keyword:"enum",params:{allowedValues:t.properties.deliveryAction.enum},message:"must be equal to one of the allowed values"};l===null?l=[p]:l.push(p),m++}}if(a.deliveryPaths!==void 0){let c=a.deliveryPaths;if(Array.isArray(c)){let p=c.length;for(let h=0;h<p;h++){let g=c[h];if(typeof g=="string"){if(i(g)<1){let w={instancePath:u+"/deliveryPaths/"+h,schemaPath:"#/properties/deliveryPaths/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};l===null?l=[w]:l.push(w),m++}}else{let w={instancePath:u+"/deliveryPaths/"+h,schemaPath:"#/properties/deliveryPaths/items/type",keyword:"type",params:{type:"string"},message:"must be string"};l===null?l=[w]:l.push(w),m++}}}else{let p={instancePath:u+"/deliveryPaths",schemaPath:"#/properties/deliveryPaths/type",keyword:"type",params:{type:"array"},message:"must be array"};l===null?l=[p]:l.push(p),m++}}if(a.prBaseBranch!==void 0){let c=a.prBaseBranch;if(typeof c=="string"){if(i(c)<1){let p={instancePath:u+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};l===null?l=[p]:l.push(p),m++}}else{let p={instancePath:u+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};l===null?l=[p]:l.push(p),m++}}if(a.remote!==void 0){let c=a.remote;if(typeof c=="string"){if(i(c)<1){let p={instancePath:u+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};l===null?l=[p]:l.push(p),m++}}else{let p={instancePath:u+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};l===null?l=[p]:l.push(p),m++}}if(a.remoteIdentity!==void 0){let c=a.remoteIdentity;if(typeof c=="string"){if(!r.test(c)){let p={instancePath:u+"/remoteIdentity",schemaPath:"#/properties/remoteIdentity/pattern",keyword:"pattern",params:{pattern:"^[0-9a-f]{64}$"},message:'must match pattern "^[0-9a-f]{64}$"'};l===null?l=[p]:l.push(p),m++}}else{let p={instancePath:u+"/remoteIdentity",schemaPath:"#/properties/remoteIdentity/type",keyword:"type",params:{type:"string"},message:"must be string"};l===null?l=[p]:l.push(p),m++}}if(a.targetBranch!==void 0){let c=a.targetBranch;if(typeof c=="string"){if(i(c)<1){let p={instancePath:u+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};l===null?l=[p]:l.push(p),m++}}else{let p={instancePath:u+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};l===null?l=[p]:l.push(p),m++}}if(a.verifiedBranch!==void 0){let c=a.verifiedBranch;if(typeof c=="string"){if(i(c)<1){let p={instancePath:u+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};l===null?l=[p]:l.push(p),m++}}else{let p={instancePath:u+"/verifiedBranch",schemaPath:"#/properties/verifiedBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};l===null?l=[p]:l.push(p),m++}}}else{let c={instancePath:u,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};l===null?l=[c]:l.push(c),m++}return o.errors=l,m===0}return e.exports})(),W_=(()=>{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:o,parentDataProperty:a,rootData:u=r}={}){let f=null,d=0;if(r&&typeof r=="object"&&!Array.isArray(r)){if(r.buildMode===void 0){let s={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"buildMode"},message:"must have required property 'buildMode'"};f===null?f=[s]:f.push(s),d++}if(r.tddMode===void 0){let s={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"tddMode"},message:"must have required property 'tddMode'"};f===null?f=[s]:f.push(s),d++}if(r.reviewMode===void 0){let s={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"reviewMode"},message:"must have required property 'reviewMode'"};f===null?f=[s]:f.push(s),d++}if(r.isolation===void 0){let s={instancePath:i,schemaPath:"#/required",keyword:"required",params:{missingProperty:"isolation"},message:"must have required property 'isolation'"};f===null?f=[s]:f.push(s),d++}for(let s in r)if(!(s==="boundBranch"||s==="buildMode"||s==="directOverride"||s==="isolation"||s==="reviewMode"||s==="subagentDispatch"||s==="tddMode")){let l={instancePath:i,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:s},message:"must NOT have additional properties"};f===null?f=[l]:f.push(l),d++}if(r.boundBranch!==void 0){let s=r.boundBranch;if(typeof s!="string"&&s!==null){let l={instancePath:i+"/boundBranch",schemaPath:"#/properties/boundBranch/type",keyword:"type",params:{type:t.properties.boundBranch.type},message:"must be string,null"};f===null?f=[l]:f.push(l),d++}}if(r.buildMode!==void 0){let s=r.buildMode;if(!(s==="subagent-driven-development"||s==="executing-plans"||s==="direct"||s==="autonomous")){let l={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"};f===null?f=[l]:f.push(l),d++}}if(r.directOverride!==void 0&&typeof r.directOverride!="boolean"){let s={instancePath:i+"/directOverride",schemaPath:"#/properties/directOverride/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};f===null?f=[s]:f.push(s),d++}if(r.isolation!==void 0){let s=r.isolation;if(!(s==="current"||s==="branch"||s==="worktree")){let l={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"};f===null?f=[l]:f.push(l),d++}}if(r.reviewMode!==void 0){let s=r.reviewMode;if(!(s==="off"||s==="standard"||s==="thorough")){let l={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"};f===null?f=[l]:f.push(l),d++}}if(r.subagentDispatch!==void 0){let s=r.subagentDispatch;if(!(s==="confirmed"||s===null)){let l={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"};f===null?f=[l]:f.push(l),d++}}if(r.tddMode!==void 0){let s=r.tddMode;if(!(s==="tdd"||s==="direct")){let l={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"};f===null?f=[l]:f.push(l),d++}}}else{let s={instancePath:i,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};f===null?f=[s]:f.push(s),d++}return n.errors=f,d===0}return e.exports})(),F_=(()=>{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=ue.default.default??ue.default,r=new RegExp("^[a-f0-9]{64}$","u");function i(o,{instancePath:a="",parentData:u,parentDataProperty:f,rootData:d=o}={}){let s=null,l=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.event===void 0){let m={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};s===null?s=[m]:s.push(m),l++}for(let m in o)if(!(m==="checks"||m==="checksReason"||m==="event"||m==="proposal"||m==="requirementsEvidence")){let c={instancePath:a,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:m},message:"must NOT have additional properties"};s===null?s=[c]:s.push(c),l++}if(o.checks!==void 0){let m=o.checks;if(Array.isArray(m)){let c=m.length;for(let p=0;p<c;p++){let h=m[p];if(h&&typeof h=="object"&&!Array.isArray(h)){if(h.name===void 0){let g={instancePath:a+"/checks/"+p,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};s===null?s=[g]:s.push(g),l++}if(h.result===void 0){let g={instancePath:a+"/checks/"+p,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};s===null?s=[g]:s.push(g),l++}for(let g in h)if(!(g==="name"||g==="note"||g==="result")){let w={instancePath:a+"/checks/"+p,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};s===null?s=[w]:s.push(w),l++}if(h.name!==void 0){let g=h.name;if(typeof g=="string"){if(n(g)<1){let w={instancePath:a+"/checks/"+p+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[w]:s.push(w),l++}}else{let w={instancePath:a+"/checks/"+p+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[w]:s.push(w),l++}}if(h.note!==void 0){let g=h.note;if(typeof g=="string"){if(n(g)<1){let w={instancePath:a+"/checks/"+p+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[w]:s.push(w),l++}}else{let w={instancePath:a+"/checks/"+p+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[w]:s.push(w),l++}}if(h.result!==void 0){let g=h.result;if(!(g==="passed"||g==="failed"||g==="not-run")){let w={instancePath:a+"/checks/"+p+"/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"};s===null?s=[w]:s.push(w),l++}}}else{let g={instancePath:a+"/checks/"+p,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[g]:s.push(g),l++}}}else{let c={instancePath:a+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};s===null?s=[c]:s.push(c),l++}}if(o.checksReason!==void 0){let m=o.checksReason;if(typeof m=="string"){if(n(m)<1){let c={instancePath:a+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}if(o.event!==void 0){let m=o.event;if(!(m==="build-complete"||m==="escalation-requested")){let c={instancePath:a+"/event",schemaPath:"#/properties/event/enum",keyword:"enum",params:{allowedValues:t.properties.event.enum},message:"must be equal to one of the allowed values"};s===null?s=[c]:s.push(c),l++}}if(o.proposal!==void 0){let m=o.proposal;if(typeof m=="string"){if(n(m)<1){let c={instancePath:a+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}if(o.requirementsEvidence!==void 0){let m=o.requirementsEvidence;if(m&&typeof m=="object"&&!Array.isArray(m)){if(m.ref===void 0){let c={instancePath:a+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"ref"},message:"must have required property 'ref'"};s===null?s=[c]:s.push(c),l++}if(m.contentHash===void 0){let c={instancePath:a+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};s===null?s=[c]:s.push(c),l++}for(let c in m)if(!(c==="contentHash"||c==="ref")){let p={instancePath:a+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};s===null?s=[p]:s.push(p),l++}if(m.contentHash!==void 0){let c=m.contentHash;if(typeof c=="string"){if(!r.test(c)){let p={instancePath:a+"/requirementsEvidence/contentHash",schemaPath:"#/properties/requirementsEvidence/properties/contentHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};s===null?s=[p]:s.push(p),l++}}else{let p={instancePath:a+"/requirementsEvidence/contentHash",schemaPath:"#/properties/requirementsEvidence/properties/contentHash/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[p]:s.push(p),l++}}if(m.ref!==void 0){let c=m.ref;if(typeof c=="string"){if(n(c)<1){let p={instancePath:a+"/requirementsEvidence/ref",schemaPath:"#/properties/requirementsEvidence/properties/ref/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[p]:s.push(p),l++}}else{let p={instancePath:a+"/requirementsEvidence/ref",schemaPath:"#/properties/requirementsEvidence/properties/ref/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[p]:s.push(p),l++}}}else{let c={instancePath:a+"/requirementsEvidence",schemaPath:"#/properties/requirementsEvidence/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[c]:s.push(c),l++}}}else{let m={instancePath:a,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[m]:s.push(m),l++}return i.errors=s,l===0}return e.exports})(),B_=(()=>{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=ue.default.default??ue.default;function r(i,{instancePath:o="",parentData:a,parentDataProperty:u,rootData:f=i}={}){let d=null,s=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};d===null?d=[l]:d.push(l),s++}for(let l in i)if(!(l==="checks"||l==="checksReason"||l==="event"||l==="reason"||l==="verificationReport")){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};d===null?d=[m]:d.push(m),s++}if(i.checks!==void 0){let l=i.checks;if(Array.isArray(l)){let m=l.length;for(let c=0;c<m;c++){let p=l[c];if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.name===void 0){let h={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};d===null?d=[h]:d.push(h),s++}if(p.result===void 0){let h={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};d===null?d=[h]:d.push(h),s++}for(let h in p)if(!(h==="name"||h==="note"||h==="result")){let g={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:h},message:"must NOT have additional properties"};d===null?d=[g]:d.push(g),s++}if(p.name!==void 0){let h=p.name;if(typeof h=="string"){if(n(h)<1){let g={instancePath:o+"/checks/"+c+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[g]:d.push(g),s++}}else{let g={instancePath:o+"/checks/"+c+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[g]:d.push(g),s++}}if(p.note!==void 0){let h=p.note;if(typeof h=="string"){if(n(h)<1){let g={instancePath:o+"/checks/"+c+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[g]:d.push(g),s++}}else{let g={instancePath:o+"/checks/"+c+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[g]:d.push(g),s++}}if(p.result!==void 0){let h=p.result;if(!(h==="passed"||h==="failed"||h==="not-run")){let g={instancePath:o+"/checks/"+c+"/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"};d===null?d=[g]:d.push(g),s++}}}else{let h={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[h]:d.push(h),s++}}}else{let m={instancePath:o+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};d===null?d=[m]:d.push(m),s++}}if(i.checksReason!==void 0){let l=i.checksReason;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}if(i.event!==void 0){let l=i.event;if(!(l==="verification-ready"||l==="verify-fail")){let m={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"};d===null?d=[m]:d.push(m),s++}}if(i.reason!==void 0){let l=i.reason;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/reason",schemaPath:"#/properties/reason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/reason",schemaPath:"#/properties/reason/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}if(i.verificationReport!==void 0){let l=i.verificationReport;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/verificationReport",schemaPath:"#/properties/verificationReport/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/verificationReport",schemaPath:"#/properties/verificationReport/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}}else{let l={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),s++}return r.errors=d,s===0}return e.exports})(),H_=(()=>{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:o="",parentData:a,parentDataProperty:u,rootData:f=i}={}){let d=null,s=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.contentHash===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contentHash"},message:"must have required property 'contentHash'"};d===null?d=[l]:d.push(l),s++}for(let l in i)if(l!=="contentHash"){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};d===null?d=[m]:d.push(m),s++}if(i.contentHash!==void 0){let l=i.contentHash;if(typeof l=="string"){if(!n.test(l)){let m={instancePath:o+"/contentHash",schemaPath:"#/properties/contentHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/contentHash",schemaPath:"#/properties/contentHash/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}}else{let l={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),s++}return r.errors=d,s===0}return e.exports})(),V_=(()=>{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=ue.default.default??ue.default;function r(i,{instancePath:o="",parentData:a,parentDataProperty:u,rootData:f=i}={}){let d=null,s=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.targetBranch===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"targetBranch"},message:"must have required property 'targetBranch'"};d===null?d=[l]:d.push(l),s++}if(i.summary===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"summary"},message:"must have required property 'summary'"};d===null?d=[l]:d.push(l),s++}for(let l in i)if(!(l==="deliveryPaths"||l==="prBaseBranch"||l==="remote"||l==="summary"||l==="targetBranch")){let m={instancePath:o,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};d===null?d=[m]:d.push(m),s++}if(i.deliveryPaths!==void 0){let l=i.deliveryPaths;if(Array.isArray(l)){let m=l.length;for(let c=0;c<m;c++){let p=l[c];if(typeof p=="string"){if(n(p)<1){let h={instancePath:o+"/deliveryPaths/"+c,schemaPath:"#/properties/deliveryPaths/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[h]:d.push(h),s++}}else{let h={instancePath:o+"/deliveryPaths/"+c,schemaPath:"#/properties/deliveryPaths/items/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[h]:d.push(h),s++}}}else{let m={instancePath:o+"/deliveryPaths",schemaPath:"#/properties/deliveryPaths/type",keyword:"type",params:{type:"array"},message:"must be array"};d===null?d=[m]:d.push(m),s++}}if(i.prBaseBranch!==void 0){let l=i.prBaseBranch;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/prBaseBranch",schemaPath:"#/properties/prBaseBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}if(i.remote!==void 0){let l=i.remote;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/remote",schemaPath:"#/properties/remote/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/remote",schemaPath:"#/properties/remote/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}if(i.summary!==void 0){let l=i.summary;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/summary",schemaPath:"#/properties/summary/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/summary",schemaPath:"#/properties/summary/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}if(i.targetBranch!==void 0){let l=i.targetBranch;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/targetBranch",schemaPath:"#/properties/targetBranch/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}}else{let l={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),s++}return r.errors=d,s===0}return e.exports})(),U_=(()=>{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=ue.default.default??ue.default;function r(i,{instancePath:o="",parentData:a,parentDataProperty:u,rootData:f=i}={}){let d=null,s=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.plan===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"plan"},message:"must have required property 'plan'"};d===null?d=[l]:d.push(l),s++}if(i.buildPause!==void 0&&i.buildPause!=="plan-ready"){let l={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"};d===null?d=[l]:d.push(l),s++}if(i.plan!==void 0){let l=i.plan;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/plan",schemaPath:"#/properties/plan/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/plan",schemaPath:"#/properties/plan/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}}else{let l={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),s++}return r.errors=d,s===0}return e.exports})(),J_=(()=>{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=ue.default.default??ue.default;function r(i,{instancePath:o="",parentData:a,parentDataProperty:u,rootData:f=i}={}){let d=null,s=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.event===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};d===null?d=[l]:d.push(l),s++}if(i.checks!==void 0){let l=i.checks;if(Array.isArray(l)){let m=l.length;for(let c=0;c<m;c++){let p=l[c];if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.name===void 0){let h={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};d===null?d=[h]:d.push(h),s++}if(p.result===void 0){let h={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/required",keyword:"required",params:{missingProperty:"result"},message:"must have required property 'result'"};d===null?d=[h]:d.push(h),s++}for(let h in p)if(!(h==="name"||h==="note"||h==="result")){let g={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:h},message:"must NOT have additional properties"};d===null?d=[g]:d.push(g),s++}if(p.name!==void 0){let h=p.name;if(typeof h=="string"){if(n(h)<1){let g={instancePath:o+"/checks/"+c+"/name",schemaPath:"#/properties/checks/items/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[g]:d.push(g),s++}}else{let g={instancePath:o+"/checks/"+c+"/name",schemaPath:"#/properties/checks/items/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[g]:d.push(g),s++}}if(p.note!==void 0){let h=p.note;if(typeof h=="string"){if(n(h)<1){let g={instancePath:o+"/checks/"+c+"/note",schemaPath:"#/properties/checks/items/properties/note/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[g]:d.push(g),s++}}else{let g={instancePath:o+"/checks/"+c+"/note",schemaPath:"#/properties/checks/items/properties/note/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[g]:d.push(g),s++}}if(p.result!==void 0){let h=p.result;if(!(h==="passed"||h==="failed"||h==="not-run")){let g={instancePath:o+"/checks/"+c+"/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"};d===null?d=[g]:d.push(g),s++}}}else{let h={instancePath:o+"/checks/"+c,schemaPath:"#/properties/checks/items/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[h]:d.push(h),s++}}}else{let m={instancePath:o+"/checks",schemaPath:"#/properties/checks/type",keyword:"type",params:{type:"array"},message:"must be array"};d===null?d=[m]:d.push(m),s++}}if(i.checksReason!==void 0){let l=i.checksReason;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/checksReason",schemaPath:"#/properties/checksReason/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}if(i.event!==void 0&&i.event!=="build-complete"){let l={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"};d===null?d=[l]:d.push(l),s++}}else{let l={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),s++}return r.errors=d,s===0}return e.exports})(),K_=(()=>{let e={exports:{}};e.exports=r,e.exports.default=r;let t={properties:{designDoc:{minLength:1,type:"string"}},required:["designDoc"],type:"object"},n=ue.default.default??ue.default;function r(i,{instancePath:o="",parentData:a,parentDataProperty:u,rootData:f=i}={}){let d=null,s=0;if(i&&typeof i=="object"&&!Array.isArray(i)){if(i.designDoc===void 0){let l={instancePath:o,schemaPath:"#/required",keyword:"required",params:{missingProperty:"designDoc"},message:"must have required property 'designDoc'"};d===null?d=[l]:d.push(l),s++}if(i.designDoc!==void 0){let l=i.designDoc;if(typeof l=="string"){if(n(l)<1){let m={instancePath:o+"/designDoc",schemaPath:"#/properties/designDoc/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};d===null?d=[m]:d.push(m),s++}}else{let m={instancePath:o+"/designDoc",schemaPath:"#/properties/designDoc/type",keyword:"type",params:{type:"string"},message:"must be string"};d===null?d=[m]:d.push(m),s++}}}else{let l={instancePath:o,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};d===null?d=[l]:d.push(l),s++}return r.errors=d,s===0}return e.exports})(),z_=(()=>{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=ue.default.default??ue.default,r=new RegExp("^[a-f0-9]{64}$","u");function i(o,{instancePath:a="",parentData:u,parentDataProperty:f,rootData:d=o}={}){let s=null,l=0;if(o&&typeof o=="object"&&!Array.isArray(o)){if(o.proposal===void 0){let m={instancePath:a,schemaPath:"#/required",keyword:"required",params:{missingProperty:"proposal"},message:"must have required property 'proposal'"};s===null?s=[m]:s.push(m),l++}if(o.handoffContext!==void 0){let m=o.handoffContext;if(typeof m=="string"){if(n(m)<1){let c={instancePath:a+"/handoffContext",schemaPath:"#/properties/handoffContext/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/handoffContext",schemaPath:"#/properties/handoffContext/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}if(o.handoffHash!==void 0){let m=o.handoffHash;if(typeof m=="string"){if(!r.test(m)){let c={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/pattern",keyword:"pattern",params:{pattern:"^[a-f0-9]{64}$"},message:'must match pattern "^[a-f0-9]{64}$"'};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/handoffHash",schemaPath:"#/properties/handoffHash/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}if(o.proposal!==void 0){let m=o.proposal;if(typeof m=="string"){if(n(m)<1){let c={instancePath:a+"/proposal",schemaPath:"#/properties/proposal/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};s===null?s=[c]:s.push(c),l++}}else{let c={instancePath:a+"/proposal",schemaPath:"#/properties/proposal/type",keyword:"type",params:{type:"string"},message:"must be string"};s===null?s=[c]:s.push(c),l++}}}else{let m={instancePath:a,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};s===null?s=[m]:s.push(m),l++}return i.errors=s,l===0}return e.exports})();var Z_=1024*1024;yr();cn();import{createHash as Em,randomUUID as GN}from"node:crypto";import{types as AC}from"node:util";import{promises as tt}from"node:fs";import fe from"node:path";import{randomUUID as SC}from"node:crypto";import{promises as Xt}from"node:fs";import pi from"node:path";import{performance as vm}from"node:perf_hooks";import{createRequire as bC}from"node:module";var RC=bC(import.meta.url??__filename),es;function tr(e,t){if(!es){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{es=RC("node:sqlite").DatabaseSync}finally{process.emitWarning=n}}return t===void 0?new es(e):new es(e,t)}import{AsyncLocalStorage as CC}from"node:async_hooks";var gm=new CC,ol=class extends Error{code="OPERATION_BUDGET_EXCEEDED";constructor(){super("Operation time budget exceeded; unfinished work can be resumed.")}};function wm(e){return Math.max(0,Math.min(e,(gm.getStore()?.deadline??1/0)-performance.now()))}function ym(){let e=gm.getStore();if(e&&(e.signal.aborted||performance.now()>=e.deadline))throw new ol}async function km(e){let t,n;try{let r=await Xt.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 Xt.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}try{let r=JSON.parse(t),i=r.nonce??r.id,o=typeof r.createdAt=="number"?r.createdAt:Date.parse(r.createdAt);if(typeof i=="string"&&i&&Number.isFinite(o))return{owner:{nonce:i,createdAt:o,...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 EC(e){let t=e+".sqlite";try{let r=await Xt.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=tr(pi.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 bm(e){try{e.exec("ROLLBACK;")}finally{e.close()}}async function xC(e,t={}){e=pi.resolve(e),await Xt.mkdir(pi.dirname(e),{recursive:!0});let n=await Xt.lstat(pi.dirname(e));if(!n.isDirectory()||n.isSymbolicLink())throw new Error("File lock parent must be a real directory: "+pi.dirname(e));let r=vm.now()+wm(t.timeoutMs??3e4),i;for(;ym(),i=await EC(e),!i;){if(vm.now()>=r)throw new Error("Timed out waiting for file lock: "+e);await new Promise(u=>setTimeout(u,t.retryMs??20))}let o={protocolVersion:2,nonce:SC(),createdAt:Date.now(),...t.operation?{operation:t.operation}:{}};try{let u=await km(e);if(u?.legacy)throw new Error("Legacy lock requires confirmation that its previous operation stopped: "+e+`
|
|
144
|
+
Inspect argv: `+JSON.stringify(["comet","doctor","--lock-file",e,"--json"]));u&&await Xt.unlink(e),await Xt.writeFile(e,JSON.stringify(o),{mode:384,flag:"wx"})}catch(u){throw bm(i),u}let a=!1;return{owner:o,async release(){if(a)return!0;a=!0;let u=!0;try{let f=await km(e);f?.token===o.nonce?f.owner?.createdAt===o.createdAt&&f.owner.operation===o.operation?await Xt.unlink(e):(u=!1,process.stderr.write("[comet] lock metadata changed while held; kept "+e+`
|
|
145
|
+
`)):f&&(u=!1,process.stderr.write("[comet] lock owned by another holder; kept "+e+`
|
|
146
|
+
`))}finally{bm(i)}return u}}}async function Rm(e,t,n={}){let r=await xC(e,n),i;try{i=await t()}catch(o){try{await r.release()}catch(a){process.stderr.write("[comet] lock cleanup failed; preserved the original operation error: "+String(a)+`
|
|
147
|
+
`)}throw o}return await r.release(),i}Qe();Q();Ke();var Cm=new WeakMap;function sl(e){let t=new WeakMap,n=new Map,r=s=>{if(typeof s=="string"){let p=n.get(s);return p===void 0&&(p=JSON.stringify(s).length,n.set(s,p)),p}if(s===null||typeof s!="object")return JSON.stringify(s).length;let l=Cm.get(s)??t.get(s);if(l!==void 0)return l;let m=Object.entries(s),c=2+Math.max(0,m.length-1)+m.reduce((p,[h,g])=>p+(Array.isArray(s)?0:r(h)+1)+r(g),0);return t.set(s,c),wt(s)&&Cm.set(s,c),c},i=r(e),o=()=>({encoded:{record:e},json:`{"record":${JSON.stringify(e)}}`});if(i<128*1024)return o();let a=[],u=(s,l)=>{if(!s||typeof s!="object")return;let m=s;if(!(m.protocolVersion!==1||!Array.isArray(m.actions)||!m.actionContexts)){for(let[c,p]of m.actions.entries())p.input&&typeof p.input=="object"&&Object.hasOwn(p.input,"outputs")&&a.push({path:[...l,"actions",String(c),"input","outputs"],group:"outputs"});for(let[c,p]of Object.entries(m.actionContexts))p?.results&&a.push({path:[...l,"actionContexts",c,"results"],group:"results"});m.outputs&&a.push({path:[...l,"outputs"],group:"results"});for(let c of["ready","waits","evidenceWaits"])for(let[p,h]of(m[c]??[]).entries())h.results&&a.push({path:[...l,c,String(p),"results"],group:"results"})}};if(u(e,[]),u(e.run,["run"]),!a.length)return o();let f=Xp(e,a,wt),d=JSON.stringify(f);return d.length<i*.9?{encoded:f,json:d}:o()}function In(e){if(typeof e!="string"||e.trim().length===0)throw new b("STORE_INVALID_RUN_ID","runId 必须是非空字符串")}function PC(e){return In(e),Em("sha256").update(JSON.stringify(e)).digest("hex")}function ts(e){if(!Number.isSafeInteger(e)||e<1)throw new b("STORE_INVALID_REVISION","revision 必须是正安全整数")}function OC(e,t,n,r=!0){if(In(e),AC.isProxy(n))throw new b("STORE_INVALID_RUN_ID","RuntimeStore records must be plain JSON data");t!==null&&ts(t),Gt(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(ts(i.revision),i.revision!==(t??0)+1)throw new b("STORE_INVALID_REVISION","next.revision 必须比预期 revision 增加 1");return i}var Sm="comet.runtime-store-checkpoint.v1";function IC(e,t,n){let r=yt(n);if(In(e),!r||r.runId!==e)throw new b("STORE_INVALID_RUN_ID","checkpoint.runId 必须与目标 runId 一致");if(ts(r.revision),t!==null&&t!==1||r.revision<=(t??0))throw new b("STORE_INVALID_REVISION","恢复仅允许缺失 Run 或相同的初始导入,且不能回退 revision");return JSON.stringify(r)}function xm(e,t,n){let r=yt(e);r.revision=t;for(let i of n){let o=r;for(let a of i.slice(0,-1))o=o[a];o[i.at(-1)]=t}return r}function _C(e,t,n,r=[]){return(e?.revision??null)===t&&(e===null||On(e)===On(xm(n,1,r)))}function Qt(e){if(typeof e.rootDir!="string"||e.rootDir.trim().length===0)throw new b("STORE_INVALID_ROOT","rootDir 必须是非空路径");let t=(e.mirroredRevisionPaths??[]).map(y=>{if(y!=="run.revision")throw new b("STORE_INVALID_REVISION","仅支持 run.revision 镜像字段");return["run","revision"]});function n(y){for(let x of t){let C=y;for(let P of x){if(!C||typeof C!="object"||Array.isArray(C)||!Object.hasOwn(C,P))throw new b("STORE_CORRUPT_RECORD","镜像 revision 字段缺失");C=C[P]}if(C!==y.revision)throw new b("STORE_CORRUPT_RECORD","镜像 revision 与记录版本不一致")}}let r=fe.resolve(e.rootDir),i=fe.parse(r).root,o=fe.relative(i,r).replaceAll("\\","/");if(!o)throw new b("STORE_INVALID_ROOT","rootDir 不能是文件系统根目录");let a={label:"RuntimeStore root",expected:"directory"},u=PC,f="checkpoint.json",d="comet.runtime-store-format.v2",s=".runtime-store-v2",l=y=>`${s}/${u(y)}`,m=y=>`.runtime-store-history/${u(y)}`,c="comet.runtime-store-format.v3",p="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 v(y,x){let C=await V(r,y?`${y}/${x}`:x,Number.MAX_SAFE_INTEGER,{label:"RuntimeStore record"});try{let P=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(C.bytes));return Gt(P),P}catch{throw new b("STORE_CORRUPT_RECORD","版本文件不是有效的 UTF-8 JSON 数据")}}function k(y,x,C){if(!y||typeof y!="object"||Array.isArray(y)||y.runId!==x||y.revision!==C||!Number.isSafeInteger(C)||C<1)throw new b("STORE_CORRUPT_RECORD","版本文件的 runId 或 revision 与目标不一致");n(y)}async function S(y,x=!1,C=u(y),P=!0){if(In(y),!(await D(i,o,a)).exists)return w();let I=await D(r,C,{label:"RuntimeStore run",expected:"directory"});if(!I.exists)return w();let W=await tt.lstat(I.target),B=await tt.readdir(I.target,{withFileTypes:!0}),le=await tt.lstat(I.target);if(await D(i,`${o}/${C}`,a),!W.isDirectory()||W.isSymbolicLink()||!le.isDirectory()||le.isSymbolicLink()||!ze({dev:W.dev,ino:W.ino,birthtime:W.birthtimeMs},{dev:le.dev,ino:le.ino,birthtime:le.birthtimeMs}))throw new b("STORE_CHANGED_DIRECTORY","读取版本列表时 Run 目录已变化");let ke=new Set,ut=[],Oe=0;for(let j of B){if((j.name===`${h}.contenders`||j.name==="legacy"&&C===l(y))&&j.isDirectory()&&!j.isSymbolicLink())continue;if(!j.isFile()||j.isSymbolicLink())throw new b("STORE_INVALID_ENTRY",`版本文件无效:${j.name}`);if(/^\..+\.tmp$/u.test(j.name)||j.name===h||[h+".sqlite",h+".sqlite-journal",h+".sqlite-wal",h+".sqlite-shm"].includes(j.name)||/^\.write\.lock\.[a-f0-9-]+\.removed$/u.test(j.name)||(ke.add(j.name),j.name===f))continue;if(!g.test(j.name))throw new b("STORE_INVALID_ENTRY",`版本文件无效:${j.name}`);let oe=Number(j.name.slice(0,-5));if(!Number.isSafeInteger(oe)||oe<1)throw new b("STORE_INVALID_ENTRY",`版本文件无效:${j.name}`);ut.push(j.name),Oe=Math.max(Oe,oe)}let hr=!1;if([l(y),m(y)].includes(C)&&ut.length>0)throw new b("STORE_INVALID_ENTRY","checkpoint 目录不能包含旧版本文件");if(ke.has(f)){if(![l(y),m(y)].includes(C))throw new b("STORE_INVALID_ENTRY","旧版本目录包含未知 checkpoint");let j=await v(C,f),oe=j?.record,be=j?.legacyRevision;if(!j||![p,"comet.runtime-store-snapshot.v3"].includes(String(j.schema))||!oe||Object.keys(j).some(bt=>!["schema","record","hash","legacyRevision",...j.schema==="comet.runtime-store-snapshot.v3"?["pool"]:[]].includes(bt))||be!==null&&(!Number.isSafeInteger(be)||be<1||be>oe.revision)||j.hash!==z({record:oe,legacyRevision:be,...j.schema==="comet.runtime-store-snapshot.v3"?{pool:j.pool}:{}}))throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 损坏或校验值不一致");let It;try{It=j.schema==="comet.runtime-store-snapshot.v3"?Go(oe,j.pool,P):oe}catch(bt){throw new b("STORE_CORRUPT_RECORD",`RuntimeStore history references are invalid: ${bt instanceof Error?bt.message:String(bt)}`)}return k(It,y,It.revision),{record:It,compacted:!0,legacyRevision:be,formatPresent:hr}}if(!Oe)return w();let As=new Map,Wl=j=>`${String(j).padStart(16,"0")}.json`,Ps=j=>ke.has(Wl(j));async function Ci(j){if(As.has(j))return As.get(j);let oe=await v(C,Wl(j));return(j<=2||j===Oe)&&As.set(j,oe),oe}async function Fl(j,oe=0,be=Oe){if(k(j,y,be),x)for(let It of ut){let bt=Number(It.slice(0,-5));bt!==oe&&k(await Ci(bt),y,bt)}return{record:j,compacted:!1,legacyRevision:j.revision,formatPresent:!1}}let Si=await Ci(Oe);if(Oe===ut.length&&(Si?.schema!==Sm||Si?.runId!==void 0))return Fl(Si);if(!Ps(1))throw new b("STORE_MISSING_REVISION","版本历史缺少 revision 1");let kt=null;for(let j of[1,2]){if(!Ps(j))break;let oe=await Ci(j);if(oe?.schema!==Sm||"runId"in oe)continue;let be=oe.record;if(be&&n(be),!be||be.runId!==y||!Number.isSafeInteger(be.revision)||be.revision<j||oe.hash!==z(be)||Object.keys(oe).some(It=>!["schema","record","hash"].includes(It))||j===2&&On(await Ci(1))!==On(xm(be,1,t)))throw new b("STORE_CORRUPT_RECORD","恢复 checkpoint 与版本基线不一致");kt={slot:j,record:be};break}let gr=kt?.record.revision??0,Ei=kt?.slot??0,Bl=Oe===Ei?gr:Oe;if(Bl<gr||ut.length!==Bl-gr+Ei||ut.some(j=>{let oe=Number(j.slice(0,-5));return oe>Ei&&oe<=gr})){let j=gr+1;for(;Ps(j);)j+=1;throw new b("STORE_MISSING_REVISION",`版本历史缺少 revision ${j}`)}return Fl(kt&&Oe===kt.slot?kt.record:Si,Ei,kt&&Oe===kt.slot?kt.record.revision:Oe)}async function E(y){let x=await D(r,u(y),{label:"RuntimeStore format",expected:"any"}),C=await D(r,`${l(y)}/legacy`,{label:"RuntimeStore legacy",expected:"directory"});if(x.kind==="directory"&&C.exists&&(x=await D(r,u(y),{label:"RuntimeStore format",expected:"any"})),x.kind==="directory"&&C.exists)throw new b("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 目录;请停止旧版本进程并检查两处版本历史");let P=null;if(x.kind==="file"){let I=await v("",u(y));if(!I||I.runId!==y||(I.schema===d?!["pending","ready"].includes(I.state)||Object.keys(I).some(W=>!["schema","runId","state","writerProtocol"].includes(W)):I.schema!==c||!["closing","closed","reopening"].includes(I.state)||!Number.isSafeInteger(I.revision)||I.revision<1||typeof I.recordHash!="string"||!/^[a-f0-9]{64}$/u.test(I.recordHash)||Object.keys(I).some(W=>!["schema","runId","state","revision","recordHash","writerProtocol"].includes(W))))throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记损坏");if(I.writerProtocol!==void 0&&I.writerProtocol!=="application-holder-v1")throw new b("STORE_WRITER_FENCED","存储协议版本不受支持");P=I}return{original:x,staged:C,marker:P}}function A(y){return Qc(y)?Pt(y,{cachePrefixes:!1}):z(y)}async function M(y,x){let C=await S(y,!1,l(y),!1),P=await S(y,!1,m(y),!1);if(!C.record&&!P.record||x.state==="closed"&&(C.record||!P.record))throw new b("STORE_HISTORY_CONFLICT","历史事务与 checkpoint 位置不一致");if(C.record&&P.record){let W=await tt.lstat(fe.join(r,l(y),f)),B=await tt.lstat(fe.join(r,m(y),f)),le={dev:W.dev,ino:W.ino,birthtime:W.birthtimeMs},ke={dev:B.dev,ino:B.ino,birthtime:B.birthtimeMs};if(!_i(le,ke)||!ze(le,ke))throw new b("STORE_HISTORY_CONFLICT","活动与历史分区含两份独立 checkpoint,已保留现场")}let I=P.record??C.record;if(I.revision!==x.revision||A(I)!==x.recordHash||C.record&&C.record!==I&&A(C.record)!==x.recordHash)throw new b("STORE_HISTORY_CONFLICT","历史事务的固定版本与 checkpoint 不一致");return{record:I,active:!!C.record,history:!!P.record}}async function O(y){if(In(y),!(await D(i,o,a)).exists)return"missing";let x=await E(y),C=await D(r,`${l(y)}/${f}`,{label:"RuntimeStore 活动 checkpoint",expected:"file"}),P=await D(r,`${m(y)}/${f}`,{label:"RuntimeStore 历史 checkpoint",expected:"file"});if(x.marker?.schema===c){if(!C.exists&&!P.exists||x.marker.state==="closed"&&(C.exists||!P.exists))throw new b("STORE_HISTORY_CONFLICT","历史分区与存储事务不一致");return x.marker.state}if(P.exists)throw new b("STORE_HISTORY_CONFLICT","历史分区缺少存储事务");return x.marker||C.exists||x.original.kind==="directory"||x.staged.exists?"active":"missing"}async function L(y,x,C){await se(fe.join(r,u(y)),JSON.stringify({schema:c,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:y,state:x,revision:C.revision,recordHash:A(C)})+`
|
|
148
|
+
`,{containedRoot:r,requireAtomicPublication:!0})}async function $(y){let x=(await E(y)).marker;if(!x||!["closing","reopening"].includes(x.state))return;let C=x.state==="closing",P=(await M(y,x)).record,I=await M(y,x),W=C?l(y):m(y),B=C?m(y):l(y);await Xe(r,B,{label:"RuntimeStore 历史目标"});let le=fe.join(r,W,f),ke=fe.join(r,B,f),ut=C?I.active:I.history;(C?I.history:I.active)||(await D(r,`${W}/${f}`,{label:"RuntimeStore 历史源",expected:"file"}),await D(r,B,{label:"RuntimeStore 历史目标",expected:"directory"}),await tt.link(le,ke),await M(y,x)),await te(fe.dirname(ke)),await te(fe.dirname(fe.dirname(ke))),await te(r),ut&&(await M(y,x),await mt(le,{containedRoot:r,beforeRemove:async()=>{await M(y,x)}}),await te(fe.dirname(le))),C?await L(y,"closed",P):await X(y,"ready",!1);let hr=await F(y,!1);if(!hr||hr.revision!==P.revision||A(hr)!==A(P))throw new b("STORE_HISTORY_CONFLICT","历史转换提交后固定版本发生变化")}async function J(y,x,C){return In(y),ts(x),Ve(y,async()=>{await $(y);let P=(await E(y)).marker,I;if(P?.schema===c){if(C&&P.state==="reopening")throw new b("STORE_HISTORY_CONFLICT","请先完成正在进行的恢复事务");if(!C&&P.state==="closing")throw new b("STORE_HISTORY_CONFLICT","请先完成正在进行的封存事务");if(I=(await M(y,P)).record,I.revision!==x)return!1;if(C&&P.state==="closed")return!0}else{if(I=(await q(y,!1)).record,!I||I.revision!==x)return!1;if(!C)return!0}return await L(y,C?"closing":"reopening",I),await $(y),!0})}async function F(y,x=!0){if(In(y),!(await D(i,o,a)).exists)return null;let C=await E(y);if(C.marker?.schema===c){let{record:W}=await M(y,C.marker);return x?Pn(W):W}if((await S(y,!1,m(y),!1)).record)throw new b("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let I=await S(y,!1,l(y),x);if(I.record){if(!C.marker&&!(await E(y)).marker)throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失");return I.record}if(C.original.kind==="directory"){let W=(await S(y)).record;if(!W&&(await E(y)).original.kind!=="directory")throw new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已迁移");return W}if(C.marker?.state==="ready")throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");if(C.staged.exists){let W;try{W=(await S(y,!1,`${l(y)}/legacy`)).record}catch(B){throw(await E(y)).marker?.state==="ready"?new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩"):B}if(!W){let B=await E(y);if(!B.staged.exists||B.marker?.state==="ready")throw new b("STORE_CHANGED_LAYOUT","读取期间旧 Run 已压缩")}return W}return null}async function re(y,x=!0){for(let C=0;;C+=1)try{return await F(y,x)}catch(P){let I=P instanceof Ae&&P.reason==="changed",W=["ENOENT","ENOTDIR"].includes(P.code??""),B=P instanceof Error&&/must be a real directory|STORE_CHANGED_DIRECTORY|STORE_CHANGED_LAYOUT/u.test(P.message);if(!I&&!W&&!B||C>=15)throw P}}async function X(y,x,C){await se(fe.join(r,u(y)),JSON.stringify({schema:d,...e.writerProtocol?{writerProtocol:e.writerProtocol}:{},runId:y,state:x})+`
|
|
149
|
+
`,{containedRoot:r,exclusive:C,requireAtomicPublication:!0})}async function te(y){let x;try{x=await tt.open(y,"r"),await x.sync()}catch(C){if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(C.code??""))throw C}finally{await x?.close()}}async function Ve(y,x){if(await Xe(i,o,a),(await D(r,".runtime-store-coordination",{label:"RuntimeStore 写入协议",expected:"directory"})).exists&&e.writerProtocol!=="application-holder-v1")throw new b("STORE_WRITER_FENCED","此 Store 已启用应用协调协议,请使用应用写入入口");await Xe(r,l(y),{label:"RuntimeStore run"}),await te(fe.join(r,s)),await te(r);try{return e.singleWriter?await x():await Rm(fe.join(r,l(y),h),x)}catch(P){throw["ENOTSUP","EOPNOTSUPP"].includes(P.code??"")?new b("STORE_ATOMIC_PUBLICATION_UNSUPPORTED","此文件系统不支持原子硬链接发布;请使用支持硬链接的本地目录或其他 RuntimeStore"):P}}async function R(y,x,C,P=sl(x)){let I=fe.join(r,l(y)),W=C.legacyRevision,{encoded:B,json:le}=P,ke=B.pool?{record:B.record,legacyRevision:W,pool:B.pool}:{record:x,legacyRevision:W},ut=B.pool?"comet.runtime-store-snapshot.v3":p,Oe=`{"schema":${JSON.stringify(ut)},${le.slice(1,-1)},"legacyRevision":${JSON.stringify(W)},"hash":${JSON.stringify(z(ke))}}
|
|
150
|
+
`;await se(fe.join(I,f),Oe,{containedRoot:r,exclusive:!C.compacted,requireAtomicPublication:!0}),C.formatPresent||await X(y,"ready",!1)}async function N(y,x){if(x===null)return;let C=`${l(y)}/legacy`,P=await D(r,C,{label:"RuntimeStore legacy",expected:"directory"});if(P.exists)try{for(let I of await tt.readdir(P.target,{withFileTypes:!0}))I.isFile()&&!I.isSymbolicLink()&&g.test(I.name)&&Number(I.name.slice(0,-5))<=x&&await mt(fe.join(P.target,I.name),{containedRoot:r});await D(r,C,{label:"RuntimeStore legacy",expected:"directory"}),await tt.rmdir(P.target).catch(I=>{if(I.code!=="ENOTEMPTY"&&I.code!=="EEXIST")throw I})}catch(I){process.stderr.write(`[comet] warning: RuntimeStore checkpoint 已提交,旧版本清理将在下次写入重试:${I instanceof Error?I.message:String(I)}
|
|
151
|
+
`)}}async function q(y,x=!0){let C=(await E(y)).marker;if(C?.writerProtocol&&C.writerProtocol!==e.writerProtocol)throw new b("STORE_WRITER_FENCED","此 Run 需要应用协调写入协议");await $(y);let P=await E(y);if(P.marker?.schema===c)throw new b("STORE_RUN_CLOSED","Run 已封存或正在转换历史分区;请显式恢复后再写入");if((await S(y,!1,m(y),!1)).record)throw new b("STORE_HISTORY_CONFLICT","历史 checkpoint 缺少对应存储事务");let W=await S(y,!1,l(y),x);if(W.record&&!P.marker)throw new b("STORE_CORRUPT_RECORD","RuntimeStore 格式标记缺失,不能恢复旧写入路径");if(P.original.kind==="directory"){await S(y,!0);let le=await tt.lstat(P.original.target);await D(i,`${o}/${u(y)}`,a),await D(r,l(y),a),await tt.rename(P.original.target,P.staged.target);let ke=await tt.lstat(P.staged.target);if(!ke.isDirectory()||ke.isSymbolicLink()||!ze({dev:le.dev,ino:le.ino,birthtime:le.birthtimeMs},{dev:ke.dev,ino:ke.ino,birthtime:ke.birthtimeMs}))throw new b("STORE_CHANGED_DIRECTORY","迁移时旧 Run 目录已变化");await te(fe.join(r,l(y))),await te(r),P=await E(y)}if(!P.marker){try{await X(y,"pending",!0)}catch(le){throw["EEXIST","EISDIR","ENOTDIR"].includes(le.code??"")?new b("STORE_MIGRATION_CONFLICT","旧写入者在迁移期间重新创建了 Run 路径;已保留迁移现场,未提交新 checkpoint"):le}P=await E(y)}let B=W;if(!B.record&&P.marker?.state==="ready")throw new b("STORE_CORRUPT_RECORD","RuntimeStore checkpoint 缺失,不能回退到旧版本");return!B.record&&P.staged.exists?(B=await S(y,!0,`${l(y)}/legacy`),B.record&&(await R(y,B.record,B),B={...B,compacted:!0,formatPresent:!0})):B.record&&P.marker?.state==="pending"&&await X(y,"ready",!1),B.record&&(B.formatPresent=!0,await N(y,B.legacyRevision)),B}return{queryScope:`file:${Em("sha256").update(r).digest("hex")}`,read:re,readProjection:y=>re(y,!1),readPartitionMetadata:O,settleRun:y=>sn(async()=>await O(y)==="missing"?"missing":Ve(y,async()=>{await $(y);let x=(await E(y)).marker;return x&&e.writerProtocol&&x.writerProtocol!==e.writerProtocol&&await se(fe.join(r,u(y)),JSON.stringify({...x,writerProtocol:e.writerProtocol})+`
|
|
152
|
+
`,{containedRoot:r,requireAtomicPublication:!0}),O(y)})),closeRun:(y,x)=>sn(()=>J(y,x,!0)),reopenRun:(y,x)=>sn(()=>J(y,x,!1)),async readDisposition(y){if(!await re(y,!1))return"missing";let C=(await E(y)).marker;return C?.schema===c?C.state:"active"},async restoreCheckpoint(y,x,C){let P=JSON.parse(IC(y,x,C));return n(P),Ve(y,async()=>{let I=await q(y);return _C(I.record,x,P,t)?(await R(y,P,I),!0):!1})},compareAndSwap:async(y,x,C)=>me(y,x,C)(),prepareCompareAndSwap:me};function me(y,x,C){OC(y,x,C,!1),n(C);let{json:P}=sl(C),I=JSON.parse(P);return()=>Ve(y,async()=>{let W=await q(y,!1);return(W.record?.revision??null)!==x?!1:(await R(y,I.record,W,{encoded:I,json:P}),!0)})}}Q();var nr="run_checkpoint",NC="comet.workflow-run-checkpoint.v1";var TC={hash:Pt,visitResults:Yc,validateOrigins:Xc};function jC(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`);Gt(e);let i=e;if(![NC,"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(u=>!["schema","hash","run","sourceRevision","sourceHash",...i.schema==="comet.workflow-run-checkpoint.v2"?["pool","storageHash"]:[]].includes(u))||i.schema==="comet.workflow-run-checkpoint.v2"&&z({record:i.run,pool:i.pool})!==i.storageHash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let o=i.schema==="comet.workflow-run-checkpoint.v2"?Go(i.run,i.pool,!r):i.run;if((r?Pt:z)(o)!==i.hash)throw new Error(`Portable Run checkpoint for ${t} is invalid or changed`);let a=r?rl(o,t,TC):Zo(o,t);if(i.sourceRevision!==void 0||i.sourceHash!==void 0){if(!Number.isSafeInteger(i.sourceRevision)||i.sourceRevision<1||i.sourceHash!==z({hash:i.hash,sourceRevision:i.sourceRevision}))throw new Error(`Portable Run checkpoint revision for ${t} is invalid or changed`);if(n.preserveSourceRevision)return{...a,revision:i.sourceRevision}}return a}function _n(e,t,n={}){return jC(e,t,n)}import{AsyncLocalStorage as BC}from"async_hooks";import{promises as Im}from"fs";import mi from"path";var al=new BC;function HC(e,t){let n=mi.relative(e,t);return n===""||!mi.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${mi.sep}`)}async function VC(e){let t=mi.resolve(e.invocationCwd??process.cwd()),n=mi.resolve(e.projectRoot??await ye(t)),[r,i]=await Promise.all([Im.realpath(t),Im.realpath(n)]);if(!HC(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 UC(e,t){let n=al.getStore();if(n)return t(n);let r=await VC(e);return al.run(r,()=>t(r))}function ns(){let e=al.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}function rs(e){return(t,n)=>UC(n,()=>e(t,n))}function _m(e){return e.ref==="classic-archive"&&(e.status==="running"||e.status==="unknown"||e.status==="cancelled"&&!!e.claim&&!e.outcome)}function cl(e){return e.status==="cancelled"&&e.children.length===0&&e.actions.every(t=>!["pending","running","unknown"].includes(t.status)&&!_m(t))&&e.waits.every(t=>t.status!=="pending")&&(e.evidenceWaits??[]).every(t=>t.status!=="pending")&&e.ready.length===0}Mc();import{AsyncLocalStorage as KC}from"node:async_hooks";import{createHash as zC,randomUUID as Tm}from"node:crypto";import ul from"node:path";import{promises as is}from"node:fs";import ll from"node:path";async function os(e,t){let n=qs(e),r=ll.join(n.workspaceRoot,"observability"),i=n.dataRoot;for(let a of["","workspaces",n.workspaceId,"observability"]){i=ll.join(i,a);let u;try{u=await is.lstat(i)}catch(f){if(!t||f.code!=="ENOENT")throw f;await is.mkdir(i,{recursive:a===""}).catch(d=>{if(d.code!=="EEXIST")throw d}),u=await is.lstat(i)}if(!u.isDirectory()||u.isSymbolicLink())throw new Error("Runtime 统计目录必须是普通目录")}let o=ll.join(r,"performance.sqlite");for(let a of["","-wal","-shm"])try{let u=await is.lstat(o+a);if(!u.isFile()||u.isSymbolicLink()||u.size>64*1024*1024)throw new Error("Runtime 统计文件无效")}catch(u){if(u.code!=="ENOENT")throw u}return o}import{stripVTControlCharacters as JC}from"node:util";function Nm(e,t=process.env){let n=JC(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 GC=864e5,YC=1e4,dl=new KC;function hi(e,t){return Nm(e).slice(0,t)}async function fl(e,t){if(!t.length)return;let n=dl.getStore();if(n){let i=o=>process.platform==="win32"?ul.resolve(o).toLowerCase():ul.resolve(o);if(i(e)===i(await n.projectRoot())){n.spans.push(...t);return}}let r=tr(await os(e,!0));try{r.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
153
|
+
CREATE TABLE IF NOT EXISTS trace_spans (
|
|
154
|
+
id TEXT PRIMARY KEY, trace_id TEXT NOT NULL, workflow TEXT NOT NULL,
|
|
155
|
+
change_name TEXT NOT NULL, run_id TEXT NOT NULL, span_id TEXT NOT NULL,
|
|
156
|
+
parent_span_id TEXT, kind TEXT NOT NULL, name TEXT NOT NULL, status TEXT NOT NULL,
|
|
157
|
+
started_at TEXT, ended_at TEXT, updated_at TEXT NOT NULL,
|
|
158
|
+
revision INTEGER NOT NULL, data TEXT NOT NULL);
|
|
159
|
+
CREATE INDEX IF NOT EXISTS trace_spans_time ON trace_spans(updated_at);
|
|
160
|
+
CREATE INDEX IF NOT EXISTS trace_spans_trace ON trace_spans(trace_id);
|
|
161
|
+
BEGIN IMMEDIATE;`);let i=r.prepare(`INSERT INTO trace_spans VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
162
|
+
ON CONFLICT(id) DO UPDATE SET status=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.status ELSE trace_spans.status END,
|
|
163
|
+
started_at=COALESCE(trace_spans.started_at,excluded.started_at),
|
|
164
|
+
ended_at=CASE WHEN excluded.revision < trace_spans.revision THEN trace_spans.ended_at
|
|
165
|
+
WHEN excluded.status IN ('running','pending','waiting','unknown') THEN NULL
|
|
166
|
+
ELSE COALESCE(trace_spans.ended_at,excluded.ended_at) END, updated_at=MAX(trace_spans.updated_at,excluded.updated_at),
|
|
167
|
+
revision=MAX(trace_spans.revision,excluded.revision),
|
|
168
|
+
data=CASE WHEN excluded.revision >= trace_spans.revision THEN excluded.data ELSE trace_spans.data END
|
|
169
|
+
WHERE excluded.revision >= trace_spans.revision OR (trace_spans.started_at IS NULL AND excluded.started_at IS NOT NULL)`),o=t.length>1e3?[...t.filter(a=>a.parentSpanId===null),...t.filter(a=>a.parentSpanId!==null).slice(-999)].slice(0,1e3):t;for(let a of o){if(!a.change||!a.runId||!a.traceId||!a.spanId||a.change.length>240||a.runId.length>240||a.traceId.length>512||a.spanId.length>512||(a.parentSpanId?.length??0)>512)continue;let u={...a,name:hi(a.name,240),summary:a.summary?hi(a.summary,1e3):void 0,attributes:Object.fromEntries(Object.entries(a.attributes??{}).slice(0,20).map(([s,l])=>[hi(s,80),Array.isArray(l)?l.slice(0,30).map(m=>hi(m,240)):typeof l=="string"?hi(l,2e3):l]))};t.length>1e3&&a.parentSpanId===null&&(u.attributes.truncated=!0);let f=JSON.stringify(u);for(;Buffer.byteLength(f,"utf8")>4096;){let s=Object.keys(u.attributes).reverse().find(l=>l!=="truncated");if(s)delete u.attributes[s];else if(u.summary)u.summary=u.summary.slice(0,Math.floor(u.summary.length*.75));else break;f=JSON.stringify(u)}if(Buffer.byteLength(f,"utf8")>4096)continue;let d=zC("sha256").update(JSON.stringify([a.traceId,a.spanId])).digest("hex");i.run(d,a.traceId,a.workflow,a.change,a.runId,a.spanId,a.parentSpanId,a.kind,u.name,a.status,a.startedAt,a.endedAt,a.updatedAt,a.revision,f)}r.prepare("DELETE FROM trace_spans WHERE updated_at < ?").run(new Date(Date.now()-7*GC).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(YC),r.exec("COMMIT")}finally{r.close()}}async function jm(e,t){let n=dl.getStore(),r=n?.binding.workflow===e.workflow?n:void 0;if(r)try{let m=(await Promise.all([e.projectRoot(),r.projectRoot()])).map(c=>{let p=ul.resolve(c);return process.platform==="win32"?p.toLowerCase():p});(m[0]!==m[1]||e.runId&&r.binding.runId&&e.runId!==r.binding.runId)&&(r=void 0)}catch{r=void 0}let i=new Date().toISOString(),o={traceId:r?.traceId??Tm(),spanId:Tm(),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(o.binding.change&&o.binding.runId){let l=[];for(let m=o;m;m=m.parent)l.push({traceId:m.traceId,spanId:m.spanId,parentSpanId:m.parent?.spanId??null,workflow:o.binding.workflow,change:o.binding.change,runId:o.binding.runId,kind:m.kind,name:m.name,status:"running",startedAt:m.startedAt,endedAt:null,updatedAt:i,revision:0});try{await fl(await e.projectRoot(),l)}catch{}}let a,u,f=!1;try{a=await dl.run(o,t)}catch(l){f=!0,u=l}let d=new Date().toISOString(),s=f?"failed":"succeeded";try{!f&&e.status&&(s=e.status(a))}catch{s="unknown"}if(o.binding.change&&o.binding.runId&&o.spans.push({traceId:o.traceId,spanId:o.spanId,parentSpanId:r?.spanId??null,workflow:o.binding.workflow,change:o.binding.change,runId:o.binding.runId,kind:e.kind,name:e.name,startedAt:i,endedAt:d,updatedAt:d,revision:1,status:s}),!r&&o.spans.length)try{await fl(await e.projectRoot(),o.spans)}catch{}if(f)throw u;return a}var zm=De(We(),1);Ke();Qe();cn();Q();import{promises as XC}from"node:fs";import{AsyncLocalStorage as QC}from"node:async_hooks";import rr from"node:path";var ss="comet.change-owner.v1",ZC=["native","classic-full","classic-hotfix","classic-tweak"],eS=Re("changeOwnerRuntimeRoots",e=>Ms(e)),qm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Nn(e,t,n="active"){if(e!=="native"&&e!=="classic")throw new Error(`Unsupported change workflow: ${e}`);if(!qm.test(t))throw new Error(`Invalid change name: ${t}`);return`${n==="active"?"change-owners":"change-owner-history"}/${e}/${t}.json`}function $m(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===ss&&r.workflow===t&&r.change===n,o=r.format==="compat"&&Object.keys(r).length===4,a=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)&&!ZC.includes(r.application)||(t==="native"?r.application==="native":r.application==="classic-full"||r.application==="classic-hotfix"||r.application==="classic-tweak"));if(!i||!o&&!a)throw new Error(`Invalid change runtime owner for ${t}/${n}`);return r}async function Dm(e,t,n,r){let i;try{({bytes:i}=await V(e,t,Number.MAX_SAFE_INTEGER,{label:"change runtime owner"}))}catch(a){if(a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new Error(`Invalid change runtime owner JSON for ${n}/${r}`)}return $m(o,n,r)}function Mm(e){return e.ino<=0n?null:[e.dev,e.ino,e.mode,e.nlink,e.size,e.birthtimeNs,e.mtimeNs,e.ctimeNs].join(":")}function tS(e,t){return Nn(e,t),`change-owner-records/${e}/${t}.json`}async function nS(e,t,n){let r;try{r=await V(e,tS(t,n),Number.MAX_SAFE_INTEGER,{label:"canonical change runtime owner",bigint:!0})}catch(o){if(o.code==="ENOENT")return null;throw o}let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r.bytes))}catch{throw new Error(`Invalid canonical Runtime owner for ${t}/${n}`)}return{owner:$m(i,t,n),identity:Mm(r.stat)}}async function rS(e,t,n){let r=await Yr(e,"change owner bindings"),i=async u=>{try{let{stat:f}=await r.stat(Nn(t,n,u));return Mm(f)}catch(f){if(f.code==="ENOENT")return null;throw f}},o=await i("active"),a=await i("history");return await r.finish({allowDirectoryContentChanges:!0}),{active:o,history:a}}async function iS(e,t,n){let r;try{r=await nS(e,t,n)}catch(o){if(o instanceof Ae&&o.reason==="changed")return null;throw o}if(!r?.identity)return null;let i=await rS(e,t,n);return i.active===r.identity&&i.history===null||i.history===r.identity&&i.active===null?r:null}var ir=new QC,Wm=dt("verifiedOwnerBatchResults",()=>new Map),Fm=(e,t,n)=>`${JSON.stringify([e,t])}\0${n}`;async function Bm(e){let t=ir.getStore();return(t?.active?t.runtimeRoots.get(e):void 0)??eS(e)}async function Hm(e,t,n=!1){let r=ir.getStore();if(r?.active&&e.every(o=>r.roots.has(o)))return t();let i={roots:new Set(e),runtimeRoots:new Map,owners:new Map,projects:new Set,active:!0};try{let o=await ir.run(i,()=>sn(()=>n?Ai(t):t())),a=Wm();for(let u of a.keys())[...i.projects].some(f=>u.startsWith(f+"\0"))&&a.delete(u);for(let[u,f]of i.owners)a.set(u,f);return o}finally{i.active=!1}}async function pl(e,t,n){let r=await iS(e,t,n);return r?r.owner:Hm([e],async()=>{let i=await Dm(e,Nn(t,n),t,n),o=await Dm(e,Nn(t,n,"history"),t,n);if(i&&o)throw new Error(`Conflicting active and history Runtime owners for ${t}/${n}`);return i??o})}async function Vm(e,t,n,r={}){if(Nn(t,n),!r.readOnly)return ir.run(null,()=>sn(async()=>pl(await Dt(e),t,n)));let[i,o]=await Bm(e),a=rr.parse(i).root,f=(await D(a,rr.relative(a,i).replaceAll("\\","/"),{label:"read-only workspace Runtime",expected:"directory"})).exists?await pl(i,t,n):null,d=o?await pl(o,t,n):null;if(f&&d&&JSON.stringify(Object.entries(f).sort())!==JSON.stringify(Object.entries(d).sort()))throw new Error(`Conflicting current and legacy Runtime owners for ${t}/${n}`);return f??d}async function Lm(e,t,n,r={}){let i=await Vm(e,t,n,r),o=i?.format==="sdk"?i:null,a=ir.getStore();return r.readOnly&&a?.active&&a.owners.set(Fm(e,t,n),o),o}async function ml(e,t,n,r={}){if(!r.readOnly||ir.getStore()?.active)return Lm(e,t,n,r);let i=Wm(),o=Fm(e,t,n);if(i.has(o))return i.get(o);let a=Lm(e,t,n,r).catch(u=>{throw i.get(o)===a&&i.delete(o),u});return i.set(o,a),a}async function oS(e,t,n,r=!1){Nn(t,"validate");let i=n.readOnly?await Bm(e):[await Dt(e)],o=async()=>{let a={active:new Set,history:new Set};for(let u of i)for(let f of["active","history"]){let d=rr.parse(u).root,s=rr.posix.dirname(Nn(t,"validate",f)),l=await D(d,rr.relative(d,rr.join(u,s)).replaceAll("\\","/"),{label:`${t} ${f} change runtime owners`,expected:"directory"});if(!l.exists)continue;let m=await XC.readdir(l.target,{withFileTypes:!0});for(let c of m){if(c.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(c.name))continue;if(t==="classic"&&f==="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(c.isFile()&&h.test(c.name)||c.isDirectory()&&/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\.lock\.contenders$/u.test(c.name))continue}if(!c.name.endsWith(".json"))throw new Error(`Invalid ${t} change runtime owner entry: ${c.name}`);let p=c.name.slice(0,-5);if(!c.isFile()||!qm.test(p))throw new Error(`Invalid ${t} change runtime owner entry: ${c.name}`);a[f].add(p)}}return a};return r?o():Hm(i,o)}var Dj=Re("changeOwnerPartitions",oS);import or from"path";import{AsyncLocalStorage as sS}from"node:async_hooks";Qe();Ue();Q();var as=Number.MAX_SAFE_INTEGER,aS=new sS;async function cS(e,t){let n=aS.getStore();if(!n||n.root!==or.resolve(e))return null;let r=_e(t,"Classic proposal source"),i=n.files.get(r);return i||(i=n.session.read(r,as),n.files.set(r,i)),i}async function cs(e,t,n,r=!1){let i=or.resolve(e),o=or.isAbsolute(t)?or.resolve(t):or.resolve(i,t),a=await Ko(i,o,{readOnly:!r});a&&(i=a.root,o=a.target);let u=or.relative(i,o).replaceAll("\\","/");return{root:i,relative:_e(u,n),target:o}}async function ct(e,t,n){let r=await cs(e,t,n.label,n.migrate);return D(r.root,r.relative,n)}async function xe(e,t,n){try{return(await ct(e,t,{label:n.label,expected:n.expected??"any"})).exists}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function gi(e,t,n,r){return await xe(e,t,{label:n,expected:"file"})?(await Um(e,t,{label:n,hooks:r})).byteLength>0:!1}async function ie(e,t,n){return(await Um(e,t,n)).toString("utf8")}async function Um(e,t,n){let r=await cs(e,t,n.label);if(!n.hooks){let i=await cS(r.root,r.relative);if(i){if(i.bytes.length>(n.maxBytes??as))throw new Error(`${n.label} exceeds the read limit`);return i.bytes}}return(await V(r.root,r.relative,n.maxBytes??as,{label:n.label,hooks:n.hooks})).bytes}async function ls(e,t,n){let r=await cs(e,t,n,!0);return Xe(r.root,r.relative,{label:n})}async function sr(e,t,n,r){let i=await cs(e,t,r.label,!0);await D(i.root,i.relative,{label:r.label,expected:"file"}),await se(i.target,n,{containedRoot:i.root,beforeTemporaryOpen:r.beforeTemporaryOpen,beforeCommit:r.beforeCommit,exclusive:r.exclusive})}Q();import{promises as Jm}from"fs";import lS from"path";async function ar(e,t){let n=[],r=new Set;async function i(o,a){let u=await ct(e,o,{label:"Classic capability directory",expected:"directory"});if(!u.exists)return;let f=await Jm.realpath(u.target);if(r.has(f))throw new Error(`Classic capability directory cycle: ${o}`);if(r.add(f),a){let s=`${o}/spec.md`;(await ct(e,s,{label:"Classic capability spec",expected:"file"})).exists&&n.push(s)}let d=(await Jm.readdir(u.target,{withFileTypes:!0})).sort((s,l)=>s.name.localeCompare(l.name));for(let s of d)if(s.isDirectory()||s.isSymbolicLink()){if(s.name==="spec.md")continue;await i(`${o}/${s.name}`,!0)}r.delete(f)}return await i(t.replaceAll("\\","/"),!1),n}function cr(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}'
|
|
170
|
+
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function hl(e){let t=cr(e);if(t)throw new Error(t)}function uS(e,t){return{label:we(e,t),directory:t}}async function dS(e,t,n){let r=uS(e,t);if(!(await ct(e,t,{label:n,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let o=await ct(e,await ee(t),{label:`${n} state`,expected:"file"});return{change:r,exists:!0,stateExists:o.exists}}async function us(e,t=process.cwd()){hl(e);let n=await Ne(t),r=await dS(n.projectRoot,lS.join(n.changesDir,e),`Classic active change ${e}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}import{execFileSync as gl}from"child_process";var fS=De(We(),1);Ke();Qe();Q();function ds(e){let t={cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0};try{let n=un(()=>gl("git",["rev-parse","--abbrev-ref","HEAD"],t).trim());if(n&&n!=="HEAD")return n}catch{}try{return un(()=>gl("git",["symbolic-ref","--quiet","--short","HEAD"],t).trim())||null}catch{return null}}var cD=dt("liveGitBranch",e=>ds(e));function wl(e){try{return un(()=>gl("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 lD=dt("isGitWorkTree",e=>wl(e));var ND=new wS;var dg=De(We(),1);import{promises as jE}from"node:fs";var Xh=De(We(),1);import DE from"node:path";Q();cn();var NE=De(We(),1);import{spawn as HD,execFileSync as CS}from"node:child_process";import vl from"node:path";import{existsSync as yl,readFileSync as yS}from"node:fs";import nt from"node:path";var vS=/[&|<>()^%"!\r\n]/u,$D=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function Gm(e,t){let n=t.toLowerCase();return Object.entries(e).find(([r,i])=>r.toLowerCase()===n&&i!==void 0)?.[1]}function kS(e){let t=(Gm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(n=>n.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function bS(e,t,n){let i=nt.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Gm(t,"PATH")??"").split(nt.delimiter).map(u=>u.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),a=nt.win32.extname(e)?[e]:kS(t).map(u=>`${e}${u}`);return i.flatMap(u=>a.map(f=>u?nt.join(u,f):nt.resolve(n,f)))}function wi(e,t,n){return bS(e,t,n).find(r=>yl(r))??e}function RS(e){let t=e.replaceAll(`\r
|
|
171
|
+
`,`
|
|
172
|
+
`).trim(),n=/^@"([^"%\r\n]+)" "%~dp0([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(t);if(n&&nt.win32.isAbsolute(n[1])&&nt.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 Ym(e,t,n,r=process.execPath){let i=RS(yS(e,"utf8"));if(!i)return null;let o=i.target.replace(/^[/\\]+/u,"");if(nt.win32.parse(o).root)return null;let a=nt.resolve(nt.dirname(e),o);if(!yl(a))throw new Error("Node CLI entry is missing: "+a);let u=nt.join(nt.dirname(e),"node.exe"),f={...n},d=Object.keys(f).find(l=>l.toUpperCase()==="NODE_PATH"),s=d?f[d]:void 0;return i.nodePath&&(d&&delete f[d],f.NODE_PATH=i.nodePath+(s?";"+s:"")),{command:i.nodeCommand??(yl(u)?u:r),args:[a,...t],...i.nodePath?{env:f}:{}}}function Xm(e){if(e.some(t=>vS.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var SS=6e4,ES=8*1024*1024;var Tn=class extends Error{constructor(n,r,i,o){super(`${n} ${r.join(" ")} failed${i?`: ${i}`:""}`,o);this.command=n;this.args=r;this.stderr=i;this.name="ExternalCommandError",this.timedOut=o?.timedOut===!0}command;args;stderr;timedOut};function xS(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Qm(e,t,n={}){let r=n.timeoutMs??SS,i=n.maxBufferBytes??ES;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 o=vl.resolve(n.cwd??process.cwd()),a=n.env??process.env,u=process.platform==="win32"?wi(e,a,o):e,f=vl.win32.extname(u).toLowerCase(),d=f===".bat"||f===".cmd";process.platform==="win32"&&d&&Xm(t);try{let s=()=>CS(u,[...t],{cwd:o,env:a,...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"&&d});return/^(?:git|git\.exe)$/iu.test(vl.win32.basename(e))?un(s):s()}catch(s){let l=typeof s.stderr=="string"?s.stderr.trim():Buffer.isBuffer(s.stderr)?s.stderr.toString("utf8").trim():"";throw new Tn(e,t,l,{cause:s,timedOut:xS(s)})}}var QD=8*1024*1024;Ue();Q();var oh=De(We(),1);import Zt from"node:path";import{spawnSync as PS}from"child_process";import{accessSync as Zm,constants as kl,statSync as eh,existsSync as n0,readFileSync as r0}from"node:fs";import lr from"node:path";function bl(e,t,n){if((n.platform??process.platform)!=="win32")return{command:e,args:[...t]};let r=wi(e,n.env??process.env,n.cwd),i=lr.extname(r).toLowerCase();if([".mjs",".cjs",".js"].includes(i))return{command:process.execPath,args:[lr.resolve(n.cwd,r),...t]};if(i===".cmd"){let o=Ym(r,t,n.env??process.env);if(o)return o}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 th(e,t,n){let r=bl(e,t,n),i=n.platform??process.platform,o=r.env??n.env??process.env,a=r.command;if(!(i==="win32"?[wi(a,o,n.cwd)]:a.includes("/")?[lr.resolve(n.cwd,a)]:(o.PATH??"/usr/bin:/bin").split(lr.delimiter).map(d=>lr.resolve(n.cwd,d,a))).some(d=>{try{let s=lr.resolve(n.cwd,d);return eh(s).isFile()?(Zm(s,i==="win32"?kl.F_OK:kl.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 d=r.args[0];if(!eh(d).isFile())throw new Error(`Node CLI entry is not a file: ${d}`);Zm(d,kl.R_OK)}}var nh=De(We(),1);Q();import AS from"path";async function rh(e,t){let n=t??await Ne(e),r=AS.join(n.openSpecRoot,"config.yaml"),i=we(n.projectRoot,r),o;try{o=(await V(n.projectRoot,i,Number.MAX_SAFE_INTEGER,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(d){throw d.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${i} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:d}):new Error(`Classic OpenSpec root is unhealthy: ${d instanceof Error?d.message:String(d)}`,{cause:d})}let a=(0,nh.parseDocument)(o,{uniqueKeys:!0});if(a.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${i} is invalid YAML (${a.errors[0].message})`);let u=a.toJS();if(!u||typeof u!="object"||Array.isArray(u))throw new Error(`Classic OpenSpec root is unhealthy: ${i} must contain a mapping`);let f=u.schema;if(typeof f!="string"||f.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${i} must declare a non-empty schema`);return{layout:n,configPath:i,schema:f}}async function ih(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 ye(t),i=await ti(r);await rh(r,i);let o=process.env.COMET_OPENSPEC||"openspec",a;try{th(o,n,{cwd:i.openSpecBase}),a=bl(o,n,{cwd:i.openSpecBase})}catch(f){return{exitCode:f.code==="ENOENT"?127:70,executionStarted:!1,stderr:f instanceof Error?f.message:String(f)}}let u=PS(a.command,a.args,{cwd:i.openSpecBase,encoding:"utf8",shell:!1,windowsHide:!0,timeout:12e4,...a.env?{env:a.env}:{}});if(u.error){let f=u.error.code;return{exitCode:f==="ENOENT"?127:70,...u.pid===0&&["ENOENT","EACCES","ENOTDIR","ENOEXEC"].includes(f??"")?{executionStarted:!1}:{},stdout:u.stdout||void 0,stderr:u.stderr||(f==="ENOENT"?`OpenSpec CLI not found: ${o}`:u.error.message)}}return{exitCode:u.status??1,executionCompleted:u.status!==null&&u.signal===null,stdout:u.stdout||void 0,stderr:u.stderr||void 0}}function OS(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 u of t.artifacts){if(!u||typeof u!="object"||typeof u.id!="string"||typeof u.outputPath!="string"||!["done","skipped","ready","blocked"].includes(u.status)||!Array.isArray(u.requires)||u.requires.some(f=>typeof f!="string"))throw new Error("OpenSpec must expose dependency edges for every artifact; upgrade to a supported version");if(n.has(u.id))throw new Error(`Duplicate OpenSpec artifact: ${u.id}`);n.set(u.id,u)}let r=[],i=new Set,o=new Set,a=u=>{if(typeof u!="string"||!n.has(u))throw new Error(`Missing OpenSpec dependency: ${String(u)}`);if(o.has(u))throw new Error(`Cyclic OpenSpec dependency: ${u}`);if(i.has(u))return;o.add(u);let f=n.get(u);for(let d of f.requires)a(d);o.delete(u),i.add(u),r.push(f)};for(let u of[...t.applyRequires,"proposal","tasks"])a(u);return r}async function Rl(e,t,n){let r=Zt.join(t,".openspec.yaml");if(!await xe(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(l=>Zt.join(t,l)),problems:[]}}let i=(0,oh.parseDocument)(await ie(e,r,{label:"OpenSpec change metadata"}));if(i.errors.length)throw new Error(`Invalid OpenSpec metadata: ${i.errors[0].message}`);let o=await ar(e,Zt.join(t,"specs")),a=n===void 0?await ih(["status","--change",Zt.basename(t),"--json"],e):void 0;if(a&&a.exitCode!==0)throw new Error(`Cannot inspect OpenSpec artifact requirements: ${a.stderr??a.exitCode}`);let u;try{u=a?JSON.parse(a.stdout??""):n}catch{throw new Error("Unsupported OpenSpec status: expected JSON")}if(!u||typeof u.changeRoot!="string"||Zt.resolve(u.changeRoot)!==Zt.resolve(t))throw new Error("OpenSpec status resolves outside the selected Classic change");let f=OS(u),d=o,s={source:"openspec",required:f.map(l=>l.id),skipped:[],designRequired:f.some(l=>l.id==="design"),files:[],problems:[]};for(let l of f){if(!["proposal","specs","design","tasks"].includes(l.id))throw new Error(`Unsupported Classic artifact: ${l.id}; use a schema with supported artifact roles`);if(l.id!=="specs"&&l.outputPath!==`${l.id}.md`)throw new Error(`Unsupported Classic artifact output: ${l.outputPath}`);if(l.status==="skipped"){if(l.id!=="specs"||i.get("skip_specs")!==!0||d.length)throw new Error("OpenSpec skipped specs require explicit skip_specs: true and no conflicting spec files");s.skipped.push(l.id);continue}let m=l.outputPath.replaceAll("\\","/");if(Zt.posix.isAbsolute(m)||/^[A-Za-z]:/u.test(m)||m.split("/").includes(".."))throw new Error(`Unsafe OpenSpec artifact path: ${m}`);let c;if(l.id==="specs"&&["specs/**/*.md","specs/**/spec.md","specs/*/spec.md"].includes(m))c=d;else{if(["?","*","[","]","{","}"].some(p=>m.includes(p)))throw new Error(`Unsupported OpenSpec artifact pattern: ${m}`);c=[Zt.join(t,m)]}(l.status!=="done"||!c.length)&&s.problems.push(`Required OpenSpec artifact is not complete: ${l.id}`);for(let p of c)await gi(e,p,`OpenSpec required artifact ${l.id}`)||s.problems.push(`Required OpenSpec file is missing or empty: ${p}`),s.files.push(p)}return s}function Cl(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 sh(e){let t=Cl(e);return t.missingFields.length===0&&t.invalidFields.length===0}import{randomUUID as xE}from"node:crypto";function ah(e){return e==="zh-CN"?"zh-CN":"en"}function IS(e,t,n){return e==="zh-CN"?n:t}function ch(e){let{name:t,locale:n}=e;return{summary:IS(n,`Handoff context for ${t} was written and recorded; the Build phase can resume from it.`,`需求 ${t} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}Fc();import fs from"path";var jn={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 en(e,t){if(fs.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let n=fs.resolve(e),r=fs.resolve(n,t);if(r!==n&&!r.startsWith(n+fs.sep))throw new Error("Run path must stay inside the change directory")}async function lh(e,t,n,r={}){en(e,t),await Np(e,t,`${JSON.stringify(n)}
|
|
173
|
+
`,jn.trajectory,"Run trajectory",r)}async function uh(e,t,n={}){en(e,t);let r=await Rn(e,t,jn.trajectory,"Run trajectory",n);return r===null?[]:r.split(/\r?\n/).map((i,o)=>({line:i,number:o+1})).filter(({line:i})=>i.length>0).map(({line:i,number:o})=>{try{return JSON.parse(i)}catch(a){throw new Error(`Invalid Trajectory event at line ${o}`,{cause:a})}})}async function dh(e,t,n={}){en(e,t);let r=await Rn(e,t,jn.artifacts,"Run artifacts",n);return r===null?{}:JSON.parse(r)}async function fh(e,t,n,r={}){en(e,t),await Cn(e,t,JSON.stringify(n,null,2)+`
|
|
174
|
+
`,jn.artifacts,"Run artifacts",r)}async function ph(e,t,n,r={}){en(e,t),await Cn(e,t,n,jn.context,"Run context",r)}async function mh(e,t,n={}){en(e,t);let r=await Rn(e,t,jn.pendingAction,"Run pending action",n);return r===null?null:JSON.parse(r)}async function hh(e,t,n={}){en(e,t),await Bo(e,t,"Run pending action",n)}async function gh(e,t,n,r={}){en(e,t),await Cn(e,t,JSON.stringify(n,null,2)+`
|
|
175
|
+
`,jn.checkpoint,"Run checkpoint",r)}import tn from"node:path";async function Sl(e,t){let n=tn.resolve(e,t),r=tn.relative(tn.resolve(e),n);if(tn.isAbsolute(t)||tn.isAbsolute(r)||r===".."||r.startsWith(`..${tn.sep}`))throw new Error("Run path must stay inside the change directory");let i=await ye(e),o=await Ko(i,n,{readOnly:!0}),a=o?.root??e,u=o?.target??n,f=a===tn.parse(u).root?Le(i):a;return{root:f,ref:tn.relative(f,u).replaceAll("\\","/"),inspectionRoot:a,target:u}}async function ur(...e){return e[0]=await U(e[0]),lh(...e)}async function ps(...e){let t=await Sl(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,uh(...e)}async function wh(...e){let t=await Sl(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,dh(...e)}async function ms(...e){return e[0]=await U(e[0]),fh(...e)}async function hs(...e){return e[0]=await U(e[0]),ph(...e)}async function yh(...e){let t=await Sl(e[0],e[1]);return e[0]=t.root,e[1]=t.ref,mh(...e)}async function vh(...e){return e[0]=await U(e[0]),hh(...e)}async function kh(...e){return e[0]=await U(e[0]),gh(...e)}import{promises as Uh}from"fs";import Je from"path";import{fileURLToPath as Jh}from"url";Q();import nn from"path";Q();Ue();import yi from"path";function NS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function bh(e,t,n,r){let i=_e(n,"Classic handoff artifact pointer");if((await D(e,i,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let a=await Ne(e),u=`${we(e,a.changesDir)}/`,d=(a.artifactLayout==="docs"?[u,"openspec/changes/"]:[u]).find(v=>i.startsWith(v));if(!d)return null;let s=i.slice(d.length).split("/");if(s.length<4||s[1]!==".comet"||s.slice(2).some(v=>v.length===0))return null;let l=s[0];hl(l);let m=s.slice(2),c=yi.resolve(t);if(yi.dirname(c)!==yi.resolve(a.archiveDir))return null;let p=yi.basename(c),h=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(p);if(p!==l&&h?.[1]!==l)return null;await D(e,we(e,c),{label:"Classic archived change directory",expected:"directory"});let g=yi.join(c,".comet",...m),w=we(e,g);try{return await V(e,w,r,{label:"Historical Classic archived handoff artifact"}),w}catch(v){if(NS(v))return null;throw v}}import Dn from"node:path";async function El(e,t,n={}){if(!t||t==="null")return{status:"missing",recordedPath:null};let r=await Ne(e),i=Dn.resolve(e,t),o=Dn.relative(r.superpowersPlansDir,i);return Dn.isAbsolute(t)||!o||o.startsWith(`..${Dn.sep}`)||Dn.isAbsolute(o)||o.includes(Dn.sep)||Dn.extname(o).toLowerCase()!==".md"?{status:"broken",recordedPath:t}:await xe(e,t,{label:`Classic build plan ${t}`,expected:"file"})&&(!n.requireNonempty||(await ie(e,t,{label:`Classic build plan ${t}`})).trim().length>0)?{status:"ready",recordedPath:t}:{status:"broken",recordedPath:t}}var TS=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,jS=/\s*<!-- comet-task:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->\s*$/u;function vi(e){let t=[],n=new Set,r=null;for(let[i,o]of e.split(/\r?\n/u).entries()){let a=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(o);if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&!a[2].trim()&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let u=TS.exec(o);if(!u)continue;let f=jS.exec(u[4]),d=f?.[1]??null;if(u[4].includes("<!-- comet-task:")&&(!f||u[4].slice(0,f.index).includes("<!-- comet-task:")))throw new Error(`Malformed Classic task ID at line ${i+1}`);if(d&&n.has(d))throw new Error(`Duplicate Classic task ID: ${d}`);d&&n.add(d);let s=u[4].slice(0,f?.index).trim();if(!s)throw new Error(`Empty Classic task at line ${i+1}`);t.push({id:d,text:s,completed:u[2].toLowerCase()==="x",line:i+1})}return t}function gs(e,t){return nn.relative(e,t).split(nn.sep).join("/")}async function ki(e,t,n,r,i){if(!n)return{code:t,satisfied:!1};let o=n.replaceAll("\\","/");if(i)return{code:t,satisfied:!1,source:o,detail:`Classic layout is unsafe or unavailable: ${i instanceof Error?i.message:String(i)}`};try{if(r){let u=r.artifactLayout==="legacy"?"docs":"legacy",f=we(e,Mo(e,u).openSpecRoot);if((o===f||o.startsWith(`${f}/`))&&(await D(e,o,{label:`${t} artifact`,expected:"file"})).exists)return{code:t,satisfied:!1,source:o,detail:"standalone OpenSpec root is not a Comet artifact root"}}let a=await Ac(e,o,{label:`${t} artifact`});return{code:t,satisfied:a,source:o,...a?{resolvedSource:o}:{}}}catch(a){return{code:t,satisfied:!1,source:o,detail:`unsafe artifact pointer outside the project or through a special path: ${a instanceof Error?a.message:String(a)}`}}}async function DS(e,t,n,r){try{r??=await Ne(e)}catch(o){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${o instanceof Error?o.message:String(o)}`}}let i=await ki(e,"design.handoff",n,r);if(!n||i.satisfied||i.detail)return i;try{let o=await bh(e,t,n,Number.MAX_SAFE_INTEGER);return o?{...i,satisfied:!0,resolvedSource:o,detail:`resolved historical legacy pointer from archived change: ${o}`}:i}catch(o){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${o instanceof Error?o.message:String(o)}`}}}async function xl(e,t,n){return ki(e,t,gs(e,n))}async function LS(e,t){let n=nn.join(t,"specs"),r;try{r=await ar(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]?gs(e,r[0]):void 0,detail:`${r.length} delta spec${r.length===1?"":"s"}`}}async function qS(e,t){let n,r=gs(e,t);try{n=(await V(e,r,Number.MAX_SAFE_INTEGER,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(a){return a.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:r,detail:`unsafe tasks artifact: ${a instanceof Error?a.message:String(a)}`}}let i;try{i=vi(n)}catch(a){return{code:"build.tasks-complete",satisfied:!1,source:r,detail:`malformed tasks.md: ${a instanceof Error?a.message:String(a)}`}}let o=i.filter(a=>a.completed).length;return{code:"build.tasks-complete",satisfied:i.length>0&&o===i.length,source:r,detail:`${o} of ${i.length} tasks complete`}}function dr(e,t){return e.some(n=>n.code===t&&n.satisfied)}async function fr(e,t){let n=await ye(e),r=t.classic,i=nn.join(e,"proposal.md"),o=nn.join(e,"design.md"),a=nn.join(e,"tasks.md"),u=t.run?nn.resolve(e,t.run.checkpointRef):nn.join(e,".comet","checkpoint.json"),f,d;try{f=await Ne(n)}catch(l){d=l}let s=await Promise.all([xl(n,"openspec.proposal",i),xl(n,"openspec.design",o),xl(n,"openspec.tasks",a),LS(n,e),ki(n,"design.document",r?.designDoc??null,f,d),(async()=>{let l=await ki(n,"build.plan",r?.plan??null,f,d);if(!l.satisfied)return l;try{let m=await El(n,r?.plan??null,{requireNonempty:r?.buildMode==="autonomous"});return m.status==="ready"?l:{code:l.code,source:l.source,satisfied:!1,detail:`Implementation plan is ${m.status}`}}catch(m){return{code:l.code,source:l.source,satisfied:!1,detail:m instanceof Error?m.message:String(m)}}})(),qS(n,a),ki(n,"verification.report",r?.verificationReport??null,f,d),DS(n,e,r?.handoffContext??null,f),(async()=>{try{return{code:"run.checkpoint",source:gs(n,u),satisfied:await gi(n,u,"Classic Run checkpoint")}}catch(l){return{code:"run.checkpoint",satisfied:!1,detail:l instanceof Error?l.message:String(l)}}})()]);return s.push({code:"archive.confirmed",satisfied:r?.archiveConfirmation==="confirmed"}),s}import{createHash as fE,randomUUID as pE}from"crypto";import{promises as _l}from"fs";import Ot from"path";function $S(e){return e.classicProfile??e.workflow}function MS(e){return e.isolation!==null&&sh(e)}function WS(e){return(e.buildMode==="direct"||e.buildMode==="autonomous")&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function FS(e,t,n){if(e!=="full"&&t.verifyResult==="fail")return`${e}.build.execute`;if(e==="full"){if(dr(n,"build.plan")&&t.buildPause==="plan-ready")return"full.build.plan-ready";if(!MS(t))return"full.build.configure";if(!dr(n,"build.plan"))return"full.build.plan";if(t.verifyResult==="fail")return"full.build.fix"}else if(!WS(t))throw new Error(`${e} build configuration is incomplete`);return dr(n,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function BS(e,t,n){return t.verifyResult!=="pass"||!dr(n,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function HS(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 ws(e,t){let n=$S(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 dr(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return FS(n,e,t);case"verify":return BS(n,e,t);case"archive":return HS(n,e)}}function Rh(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 Lh,randomUUID as aE}from"crypto";import{promises as ve}from"fs";import pe from"path";var Eh=De(We(),1);import{promises as Al}from"fs";import rt from"path";var VS=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],US=["deterministic","adaptive"],JS=["function","mcp","script","agent"],KS=["none","read","write","external"],zS=["progress","step","completion"],GS=["artifact_exists","state_equals"];function Ln(e,t,n){return new Error(`${e}: ${t} ${n}`)}function He(e,t,n="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw Ln(t,n,"must be an object")}function rn(e,t,n){if(!Array.isArray(e))throw Ln(t,n,"must be an array")}function je(e,t,n){if(typeof e!="string")throw Ln(t,n,"must be a string")}function lt(e,t,n,r){t in e&&je(e[t],n,`${r}.${t}`)}function xh(e,t,n,r){if(t in e&&typeof e[t]!="boolean")throw Ln(n,`${r}.${t}`,"must be a boolean")}function on(e,t,n,r){if(typeof e!="string"||!t.includes(e))throw Ln(n,r,`must be one of ${t.join(", ")}`)}function ys(e,t,n){rn(e,t,n),e.forEach((r,i)=>{je(r,t,`${n}[${i}]`)})}function Ch(e,t,n){He(e,t,n),je(e.name,t,`${n}.name`),je(e.description,t,`${n}.description`),xh(e,"required",t,n)}function YS(e,t,n){He(e,t,n),je(e.id,t,`${n}.id`),lt(e,"source",t,n),lt(e,"version",t,n)}function XS(e,t,n){He(e,t,n),je(e.id,t,`${n}.id`),je(e.role,t,`${n}.role`),lt(e,"instructions",t,n)}function QS(e,t,n){He(e,t,n),je(e.id,t,`${n}.id`),on(e.kind,JS,t,`${n}.kind`),je(e.source,t,`${n}.source`),on(e.sideEffect,KS,t,`${n}.sideEffect`),xh(e,"requiresConfirmation",t,n)}function ZS(e,t,n){He(e,t,n),on(e.type,VS,t,`${n}.type`),lt(e,"ref",t,n),lt(e,"prompt",t,n),lt(e,"question",t,n),"options"in e&&ys(e.options,t,`${n}.options`)}function eE(e,t,n){He(e,t,n),je(e.id,t,`${n}.id`),ZS(e.action,t,`${n}.action`),lt(e,"next",t,n),"completionEvals"in e&&ys(e.completionEvals,t,`${n}.completionEvals`)}function tE(e,t){let n="goal";He(e,t,n),je(e.statement,t,`${n}.statement`),rn(e.inputs,t,`${n}.inputs`),e.inputs.forEach((r,i)=>{Ch(r,t,`${n}.inputs[${i}]`)}),rn(e.outputs,t,`${n}.outputs`),e.outputs.forEach((r,i)=>{Ch(r,t,`${n}.outputs[${i}]`)}),ys(e.success,t,`${n}.success`)}function nE(e,t){let n="orchestration";He(e,t,n),on(e.mode,US,t,`${n}.mode`),lt(e,"entry",t,n),"steps"in e&&(rn(e.steps,t,`${n}.steps`),e.steps.forEach((r,i)=>{eE(r,t,`${n}.steps[${i}]`)}))}function Ah(e,t){return He(e,t),on(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),on(e.kind,["Skill"],t,"kind"),He(e.metadata,t,"metadata"),je(e.metadata.name,t,"metadata.name"),je(e.metadata.version,t,"metadata.version"),je(e.metadata.description,t,"metadata.description"),tE(e.goal,t),nE(e.orchestration,t),rn(e.skills,t,"skills"),e.skills.forEach((n,r)=>{YS(n,t,`skills[${r}]`)}),rn(e.agents,t,"agents"),e.agents.forEach((n,r)=>{XS(n,t,`agents[${r}]`)}),rn(e.tools,t,"tools"),e.tools.forEach((n,r)=>{QS(n,t,`tools[${r}]`)}),e}function Ph(e,t){He(e,t);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in e&&ys(e[n],t,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in e&&(typeof e[n]!="number"||!Number.isFinite(e[n])))throw Ln(t,n,"must be a finite number");return e}function rE(e,t){return He(e,t),"runtime"in e&&Oh(e.runtime,t,"runtime"),e}function Oh(e,t,n){return rn(e,t,n),e.forEach((r,i)=>{let o=`${n}[${i}]`;He(r,t,o),je(r.id,t,`${o}.id`),on(r.scope,zS,t,`${o}.scope`),on(r.type,GS,t,`${o}.type`),lt(r,"artifact",t,o),lt(r,"field",t,o),lt(r,"equals",t,o)}),e}async function Pl(e){let t=await Al.readFile(e,"utf8");try{return(0,Eh.parse)(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw Ln(e,"document",r)}}async function iE(e){try{return await Pl(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Sh(e){try{return await Al.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function oE(e){let t=rt.join(e,"checks.yaml"),n=rt.join(e,"evals.yaml"),[r,i]=await Promise.all([Sh(t),Sh(n)]);if(i)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return r?{document:rE(await Pl(t),t)}:{document:null}}async function Ih(e){let t=rt.resolve(e.root),n=rt.resolve(e.controlRoot);e.requireSkillMarkdown&&await Al.access(rt.join(t,"SKILL.md"));let r=rt.join(n,"skill.yaml"),i=rt.join(n,"guardrails.yaml"),o=Ah(await Pl(r),r),a=await iE(i),u=a===null?null:Ph(a,i),f=await oE(n),d={allowedSkills:o.skills.map(s=>s.id),allowedAgents:o.agents.map(s=>s.id),allowedTools:o.tools.map(s=>s.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:o.tools.filter(s=>s.requiresConfirmation).map(s=>s.id)};return{root:t,packageKind:e.packageKind==="runtime"?"runtime":void 0,definition:o,guardrails:{...d,...u},evals:f.document?.runtime??[]}}async function _h(e){let t=rt.resolve(e);return Ih({root:t,controlRoot:rt.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Nh(e){let t=rt.resolve(e);return Ih({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function Th(e,t,n=rt.join(t,"package.json")){He(e,n);let r=e.packageKind==="runtime"?"runtime":void 0,i=Ah(e.definition,n),o=Ph(e.guardrails,n),a=Oh(e.evals,n,"evals"),u={allowedSkills:i.skills.map(f=>f.id),allowedAgents:i.agents.map(f=>f.id),allowedTools:i.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:i.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:rt.resolve(t),packageKind:r,definition:i,guardrails:{...u,...o},evals:a}}import jh from"path";function sE(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 Dh(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 o=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||o.length>0)&&t.push("adaptive orchestration must not define entry or steps");else{let a=new Set;for(let u of o)a.has(u.id)&&t.push(`duplicate step id: ${u.id}`),a.add(u.id),sE(u.action,e,t,u.id);(!n.orchestration.entry||!a.has(n.orchestration.entry))&&t.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let u of o){u.next&&!a.has(u.next)&&t.push(`step ${u.id} has unknown next step: ${u.next}`);for(let f of u.completionEvals??[])i.some(d=>d.id===f)||t.push(`step ${u.id} references unknown eval: ${f}`)}}for(let a of n.tools){if(a.kind!=="script")continue;let u=jh.posix.normalize(a.source.replaceAll("\\","/"));(jh.isAbsolute(a.source)||u===".."||u.startsWith("../"))&&t.push(`script tool ${a.id} must reference a relative path inside the Skill package`)}for(let a of r.allowedSkills)n.skills.some(u=>u.id===a)||t.push(`guardrails allow undeclared skill: ${a}`);for(let a of r.allowedAgents)n.agents.some(u=>u.id===a)||t.push(`guardrails allow undeclared agent: ${a}`);for(let a of r.allowedTools)n.tools.some(u=>u.id===a)||t.push(`guardrails allow undeclared tool: ${a}`);return t}function vs(e){return Array.isArray(e)?e.map(vs):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,vs(n)])):e}function cE(e){return vs({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function lE(e){return pe.posix.normalize(e.replaceAll("\\","/"))}function pr(e,t,n){let r=pe.relative(e,t);if(!(r===""||!pe.isAbsolute(r)&&!r.startsWith(`..${pe.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function qh(e,t,n){let r=lE(t);if(pe.posix.isAbsolute(r)||r===".."||r.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let i=pe.resolve(e,...r.split("/"));pr(e,i,n);let o;try{o=await ve.realpath(i)}catch(a){throw a.code==="ENOENT"?new Error(`${n} does not exist: ${t}`,{cause:a}):a}if(pr(e,o,n),!(await ve.stat(o)).isFile())throw new Error(`${n} is not a file: ${t}`);return{path:r,content:await ve.readFile(o)}}async function uE(e){let t=await ve.realpath(e.root),n=e.packageKind==="runtime"?[]:[await qh(t,"SKILL.md","SKILL.md")];for(let r of e.definition.tools)r.kind==="script"&&n.push(await qh(t,r.source,`Script tool ${r.id}`));return n.sort((r,i)=>r.path.localeCompare(i.path))}function dE(e,t){let n=t.map(r=>({path:r.path,sha256:Lh("sha256").update(r.content).digest("hex")}));return Lh("sha256").update(JSON.stringify(vs({package:e,files:n}))).digest("hex")}function Wh(e){return JSON.stringify(e,null,2)+`
|
|
176
|
+
`}async function Fh(e){let t=cE(e),n=await uE(e);return{document:t,files:n,hash:dE(t,n)}}async function ks(e){return(await Fh(e)).hash}async function $h(e){try{return await ve.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mh(e,t){try{if((await ve.readFile(pe.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await ve.readFile(pe.join(e,"package.json"),"utf8")!==Wh(t.document))throw new Error("package mismatch");for(let i of t.files)if(!(await ve.readFile(pe.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 Ol(e,t){let n=await Fh(e),r=pe.resolve(t,".comet","skill-snapshots"),i=pe.join(r,n.hash);if(await ve.mkdir(r,{recursive:!0}),await $h(i))return await Mh(i,n),{hash:n.hash,snapshotDir:i};let o=pe.join(r,`.tmp-${aE()}`);pr(r,o,"Temporary snapshot"),pr(r,i,"Published snapshot");try{await ve.mkdir(o);for(let a of n.files){let u=pe.join(o,...a.path.split("/"));pr(o,u,`Snapshot file ${a.path}`),await ve.mkdir(pe.dirname(u),{recursive:!0}),await ve.writeFile(u,a.content)}await ve.writeFile(pe.join(o,"package.json"),Wh(n.document)),await ve.writeFile(pe.join(o,"sha256"),n.hash+`
|
|
177
|
+
`),await ve.rename(o,i)}catch(a){if(await $h(i)){try{await Mh(i,n)}finally{await ve.rm(o,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:i}}throw await ve.rm(o,{recursive:!0,force:!0}),a}return{hash:n.hash,snapshotDir:i}}async function Il(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let n=pe.resolve(e,".comet","skill-snapshots"),r=pe.join(n,t);pr(n,r,"Skill snapshot");try{let i=(await ve.readFile(pe.join(r,"sha256"),"utf8")).trim();if(i!==t)throw new Error(`stored hash is ${i||"(empty)"}`);let o=pe.join(r,"package.json"),a=JSON.parse(await ve.readFile(o,"utf8")),u=Th(a,r,o),f=Dh(u);if(f.length>0)throw new Error(f.map(s=>` - ${s}`).join(`
|
|
178
|
+
`));let d=await ks(u);if(d!==t)throw new Error(`calculated hash is ${d}`);return u}catch(i){throw new Error(`Skill snapshot is invalid or missing: ${t}`,{cause:i})}}async function Bh(e){try{return await _l.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Hh(e){return fE("sha256").update(e).digest("hex")}function mE(e){return Hh(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function hE(e){return e.replaceAll(".","_").replaceAll("-","_")}async function gE(e,t){let n=await ye(e),r=Object.fromEntries(t.filter(a=>a.satisfied&&a.source).map(a=>[hE(a.code),a.source])),i=Ot.join(e,"subagent-progress.md");await Bh(i)&&(r.subagent_progress=Ot.relative(n,i).split(Ot.sep).join("/"));let o=t.find(a=>a.code==="design.handoff"&&a.satisfied);return o?.source&&(r.handoff_context=o.source),r}function wE(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:xn,profile:t,source:"pre-migration"}}]}async function yE(e){await Promise.all(e.map(t=>_l.rm(t,{recursive:!0,force:!0})))}async function Vh(e,t){return Et(e,()=>vE(e,t))}async function vE(e,t){let n=await ye(e),r=await ie(n,await ee(e),{label:"Classic migration state"});if(ht(r))throw new Error("Classic managed Run is owned by the SDK and cannot be migrated to compat");let i=await xt(e);if(!i.classic)throw new Error("Classic migration requires a legacy state projection");let o=i.classic,a=o.classicProfile??o.workflow;if(i.run){if(o.classicMigration!==xn)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 ks(t.skillPackage)!==i.run.skillHash)return await Il(await U(e),i.run.skillHash),{classic:o,run:i.run,evidence:await fr(e,i),migrated:!1,snapshotDir:Ot.join(await U(e),".comet","skill-snapshots",i.run.skillHash)};let p=await Ol(t.skillPackage,await U(e));return{classic:o,run:i.run,evidence:await fr(e,i),migrated:!1,snapshotDir:p.snapshotDir}}let u=await fr(e,i),f=ws(o,u);if(!t.skillPackage.definition.orchestration.steps?.some(c=>c.id===f))throw new Error(`Classic Skill package does not define resolved step: ${f}`);let d=await ks(t.skillPackage),s=Ot.join(await U(e),".comet","skill-snapshots",d),l=await Bh(s),m=[];try{let c=await Ol(t.skillPackage,await U(e)),p=Rh(t.skillPackage,t.runId?.()??pE(),c.hash);p.currentStep=f,f==="completed"&&(p.status="completed");let h={...o,classicProfile:a,classicMigration:xn},g=await gE(e,u),w=await ye(e),v=u.find(A=>A.code==="design.handoff"&&A.satisfied),k=null;v?.source&&(k=await ie(w,v.resolvedSource??v.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await hs(e,p.contextRef,k),m.push(Ot.resolve(await U(e),p.contextRef))),await ms(e,p.artifactsRef,g),m.push(Ot.resolve(await U(e),p.artifactsRef));let S=(t.now?.()??new Date).toISOString(),E={runId:p.runId,stateVersion:1,trajectoryOffset:2,contextHash:k===null?null:Hh(k),artifactsHash:mE(g),createdAt:S};await kh(e,p.checkpointRef,E),m.push(Ot.resolve(await U(e),p.checkpointRef)),m.push(Ot.resolve(await U(e),p.trajectoryRef));for(let A of wE(p,a,S))await ur(e,p.trajectoryRef,A);return await Qn(e,{classic:h,run:p,unknownKeys:i.unknownKeys}),{classic:h,run:p,evidence:u,migrated:!0,snapshotDir:c.snapshotDir}}catch(c){throw await yE(m),l||await _l.rm(s,{recursive:!0,force:!0}),c}}async function kE(e){try{return(await Uh.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bs(e){try{return(await Uh.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bE(e){return await kE(e)?await bs(Je.join(e,"skill.yaml"))?!0:await bs(Je.join(e,"SKILL.md"))&&await bs(Je.join(e,"comet","skill.yaml")):!1}function RE(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 CE(){let e=Je.dirname(Jh(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Je.resolve(e,"..","runtime","classic"),Je.resolve(e,"..","..","comet","runtime","classic"),Je.resolve(e,"..","..","assets","skills","comet","runtime","classic"),Je.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Je.resolve(e,"..","..","comet-classic"),Je.resolve(e,"..","..","assets","skills","comet-classic"),Je.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of t)if(await bE(n))return n;return null}async function SE(e){return await bs(Je.join(e,"skill.yaml"))?Nh(e):_h(e)}async function Kh(e){let t=await CE();return Vh(e,{skillPackage:t?await SE(t):RE(Je.dirname(Jh(import.meta.url)))})}async function zh(e,t,n,r){return Et(e,()=>EE(e,t,n,r))}async function EE(e,t,n,r){let i=await xt(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 o=await fr(e,{classic:t,run:n,unknownKeys:i.unknownKeys}),a=ws(t,o),u={...n,currentStep:a,iteration:n.iteration+1,status:a==="completed"?"completed":"running"};await Qn(e,{classic:t,run:u,unknownKeys:i.unknownKeys});let f=await ps(e,u.trajectoryRef);return await ur(e,u.trajectoryRef,{sequence:f.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:u.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:a,...r}}),u}function AE(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(`
|
|
179
|
+
`)}async function PE(e){let{projectRoot:t,changeDir:n,change:r}=e,i=we(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 o=i+"/proposal.md";if(!(await ie(t,o,{label:"Classic Design source"})).trim())throw new Error("Classic Design source is empty");return{handoffContext:o,handoffHash:e.run?.actions.at(-1)?.inputHash??null}}async function OE(e){let{projectRoot:t,changeDir:n,change:r}=e,i=[],o=[...["proposal.md","design.md","tasks.md"].map(u=>n+"/"+u),...await ar(t,n+"/specs")];for(let u of o)await xe(t,u,{label:"Classic handoff source",expected:"file"})&&i.push({reference:we(t,u),content:await ie(t,u,{label:"Classic handoff source"})});await ls(t,n+"/.comet/handoff","Classic handoff view directory");let a=n+"/.comet/handoff/design-context.md";return await sr(t,a,AE(r,"full","",i),{label:"Classic handoff view"}),we(t,a)}var cq=rs(async e=>{let[t,n,r,i]=e;if(n==="--hash-only")return{exitCode:64,stderr:`handoff --hash-only 已移除。由 Agent 读取实际文档并判断上下文是否需要更新。
|
|
180
|
+
`};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]
|
|
181
|
+
`};let o=cr(t);if(o)return{exitCode:1,stderr:o};let a=ns(),u=await ti(a),f=await us(t,u.projectRoot);return!f.exists||!f.stateExists?{exitCode:1,stderr:"Classic change directory or state is missing"}:Et(f.directory,async()=>{let d=await xt(f.directory);if(!d.classic||!["design","build"].includes(d.classic.phase))throw new Error("Design handoff requires phase: design or build");let s=await Rl(a,f.directory);if(s.problems.length)throw new Error(s.problems.join(`
|
|
182
|
+
`));let l=await Kh(f.directory),m=await yh(f.directory,l.run.pendingRef);if(l.run.pending&&m?.type!=="handoff")throw new Error("Another Classic action is pending");if(m&&l.run.pending!==m.id)throw new Error("Classic handoff pending identity does not match the original Run");let c=await PE({projectRoot:a,changeDir:f.directory,change:t,contextCompression:l.classic.contextCompression}),p=c.handoffContext.replace(/\.json$/u,".md"),h=await ie(a,p,{label:"Classic handoff"}),g=i==="--full"?await OE({projectRoot:a,changeDir:f.directory,change:t}):null;await hs(f.directory,l.run.contextRef,h),await ms(f.directory,l.run.artifactsRef,{...await wh(f.directory,l.run.artifactsRef),handoff_context:c.handoffContext,handoff_markdown:p});let w={...l.classic,...c},v={...l.run,pending:null};if(v.currentStep==="full.design.handoff"&&(v=await zh(f.directory,w,v,{actionId:m?.id??xE(),kind:"classic-handoff"})),await Qn(f.directory,{...d,classic:w,run:v}),m){let S=await ps(f.directory,v.trajectoryRef);S.some(E=>E.type==="recovery_reconciled"&&E.data?.actionId===m.id)||await ur(f.directory,v.trajectoryRef,{sequence:S.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:v.runId,data:{kind:"classic-handoff",actionId:m.id}}),await vh(f.directory,l.run.pendingRef)}let k=ch({name:t,locale:ah(w.language)});return{exitCode:0,envelope:k,stderr:k.summary+`
|
|
183
|
+
[HANDOFF] source `+c.handoffContext+(g?`
|
|
184
|
+
[HANDOFF] view `+g:"")+`
|
|
185
|
+
`}})});Ue();Q();Ue();Q();var Yh=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"];Ue();vn();Q();async function Qh(e,t){if(!ht(t))return null;let n=(0,Xh.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Classic state: ${n.errors[0].message}`);let r=Ze(n.toJS()).classic,i=await jE.readdir(e),o=[];for(let a of i)a===".comet-state.lock"&&await Yl(DE.join(e,a))||o.push(a);return r?.phase==="open"&&r.designDoc===null&&r.plan===null&&r.verifyResult==="pending"&&r.verifyFailures===0&&!r.archived&&o.every(a=>Oi(a)||a===".openspec.yaml")?r:null}import{createHash as Es,randomUUID as m1}from"node:crypto";var rg=De(We(),1);import it from"node:path";var LE=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_PREFIX","GIT_IMPLICIT_WORK_TREE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"]);function qE(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>{let n=t.toUpperCase();return!LE.has(n)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(n)}))}function Zh(e){return{...qE(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"}}Ke();Q();function qn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Classic progress requires a JSON object");return e}function jl(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 vt(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}async function $E(e,t,n){let r=it.join(t,".comet",n);if(await xe(e,r,{label:"Classic progress",expected:"file"}))return JSON.parse(await ie(e,r,{label:"Classic progress"}))}function ME(e,t){let n=Es("sha256").update(t).digest("hex");return it.join(Le(e),"classic-delivery",`${n}.json`)}async function WE(e,t){let n=ME(e,t);if(!await xe(e,n,{label:"Classic delivery reauthorization",expected:"file"}))return null;let r=qn(JSON.parse(await ie(e,n,{label:"Classic delivery reauthorization"})));if(jl(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=Dl({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:vt(r.previousAuthorizationId,"previousAuthorizationId"),authorizationId:vt(r.authorizationId,"authorizationId"),...i,targetBranch:i.targetBranch,...r.authorizedRemoteUrl===void 0?{}:{authorizedRemoteUrl:vt(r.authorizedRemoteUrl,"authorizedRemoteUrl")}}}function Dl(e,t=!1){let n=qn(e);if(jl(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=vt(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 o=vt(n.remote,"remote");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/u.test(o))throw new Error("Classic delivery remote must be a name, not a URL");i.remote=o}if(n.commit!==void 0){let o=vt(n.commit,"commit");if(!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/u.test(o))throw new Error("Classic delivery commit must be a full object ID");i.commit=o.toLowerCase()}if(n.prUrl!==void 0){let o=vt(n.prUrl,"prUrl"),a=new URL(o);if(a.protocol!=="https:"||a.username||a.password)throw new Error("Invalid Classic delivery prUrl");i.prUrl=o}return i}function ig(e){let t=(0,rg.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length)throw new Error("Invalid Classic delivery change state");return qn(t.toJS())}function FE(e,t,n){return typeof e.run_id=="string"&&e.run_id?`run:${e.run_id}`:og(e,t,n)}function og(e,t,n){let r=e.archived===!0||it.basename(it.dirname(t))==="archive"?it.basename(t).replace(/^\d{4}-\d{2}-\d{2}-/u,""):it.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:${Es("sha256").update(JSON.stringify([r,e.created_at,e.base_ref??it.resolve(n)])).digest("hex")}`}function sg(e,t,n,r){let i=FE(t,n,r);if(e===i)return i;if(typeof e=="string"&&e.startsWith("legacy:")&&e===og(t,n,r))return e;throw new Error("Classic delivery change identity mismatch")}var BE=Re("classicCurrentState",async(e,t)=>HE(e,t));async function HE(e,t){return ig(await ie(e,await ee(t),{label:"Classic delivery state"}))}async function VE(e,t){return BE(e,t)}var Ss=class extends Error{constructor(t,n){super(`Classic delivery git command timed out: ${[t,...n].join(" ")}`)}};function Tl(e,t,n,r){return Qm(t,n,{cwd:e,timeoutMs:5e3,env:Zh({authentication:r})}).trim()}function Ri(e,t,n,r=!1){try{return Tl(e,t,n,r)}catch{return null}}function UE(e,t,n,r=!1){try{return Tl(e,t,n,r)}catch(i){if(!(i instanceof Tn)||!i.timedOut)return null;try{return Tl(e,t,n,r)}catch(o){if(o instanceof Tn&&o.timedOut)throw new Ss(t,n);return null}}}function bi(e,t){return Ri(e,"git",["-C",e,...t])}function Rs(e,t){return UE(e,"git",["-C",e,...t])}function eg(e,t,n=!1){return Ri(e,"git",["-C",e,"remote","get-url",...n?["--push"]:[],t],!0)}function JE(e,t){let n=it.relative(e,t).replaceAll("\\","/");return[`:(literal)${n}`,...[".comet-state.lock",".comet-state-transaction.json",...[...Jc].map(r=>`.comet/${r}`)].map(r=>`:(exclude,literal)${n}/${r}`)]}function tg(e,t,n,r){let i=it.relative(e,t).replaceAll("\\","/"),o=JE(e,t),a=$n.map(f=>Rs(e,["show",`${n}:${i}/${f}`])).filter(f=>f!==null);if(a.length!==1)return!1;let u=a[0];try{let f=ig(u);return f.archived===!0&&sg(r,f,t,e)===r&&Rs(e,["merge-base","--is-ancestor",n,"HEAD"])!==null&&Rs(e,["diff","--quiet","--no-ext-diff","--no-textconv",n,"--",...o])!==null&&Rs(e,["ls-files","--others","--exclude-standard","--",...o])===""}catch(f){if(f instanceof Ss)throw f;return!1}}function KE(e){return Es("sha256").update(e).digest("hex")+".json"}async function zE(e,t){let n=KE(t);return[{root:it.dirname(Le(e)),file:it.join(Le(e),"classic-delivery-receipts",n)}]}function GE(e,t){let n=qn(e);if(jl(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=Dl({action:"local",targetBranch:"main",...n.commit!==void 0?{commit:n.commit}:{},...n.prUrl!==void 0?{prUrl:n.prUrl}:{}});return{schemaVersion:1,changeIdentity:t,authorizationId:vt(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:XE(n.archiveFiles)}}}async function YE(e,t){let n=null;for(let r of await zE(e,t)){if(!await xe(r.root,r.file,{label:"Classic delivery receipt",expected:"file"}))continue;let i=GE(JSON.parse(await ie(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 XE(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 QE(e){return e.authorizationId===void 0?`legacy:${Es("sha256").update(JSON.stringify(e)).digest("hex")}`:vt(e.authorizationId,"authorizationId")}function ng(e,t,n){return t===n||bi(e,["merge-base","--is-ancestor",t,n])!==null}function ZE(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 Cs(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 ag(e,t,n={}){let r=n.evidence!==!1,i=await $E(e,t,"delivery.json");if(i===void 0)return{delivery:null,verification:{status:"needsAuthorization"}};let o=qn(i);if(o.schemaVersion!==1)throw new Error("Unsupported Classic delivery schemaVersion");let a=Dl(o,!0),u=await VE(e,t),f=sg(o.changeIdentity,u,t,e),d=QE(o),s=await WE(e,f);if(s&&s.previousAuthorizationId!==d)throw new Error("Classic delivery reauthorization is stale for the sealed authorization");let l=s?{action:s.action,targetBranch:s.targetBranch,...s.remote===void 0?{}:{remote:s.remote}}:a,m=s?.authorizationId??d,c=await YE(e,f),p=c?.authorizationId===m?c:null;if(p?.invalidated)return{delivery:null,verification:{status:"needsAuthorization",invalidated:!0}};for(let X of["commit","prUrl"]){if(X==="commit"&&p?.[X]&&l[X]&&p[X]!==l[X])throw new Error("Classic delivery receipt conflicts with authorization evidence");p?.[X]&&(l[X]=p[X])}let h=o.authorizedRemoteUrl===void 0?void 0:vt(o.authorizedRemoteUrl,"authorizedRemoteUrl"),g=s?.authorizedRemoteUrl??h,w={...l,schemaVersion:1,changeIdentity:f,authorizationId:m,...g?{authorizedRemoteUrl:g}:{}};if(l.action==="archive-only"){let X=u.archived===!0&&!!(p?.archiveCompleted||p?.archiveFiles);return{delivery:w,verification:{status:X?"complete":"needsVerification",archiveVerified:X}}}if(!r)return{delivery:w,verification:{status:p?.commit||p?.prUrl?"complete":"needsVerification",currentBranch:null,commitExists:!1,archiveCommitted:!1,observedCommit:null,observedPrUrl:null,remoteVerified:!1,prVerified:!1,remoteStatus:"notChecked",prStatus:"notChecked"}};let v=bi(e,["symbolic-ref","--quiet","--short","HEAD"]),k=it.relative(e,t).replaceAll("\\","/"),S=null;!l.commit&&u.archived===!0&&(S=bi(e,["log","-20","--format=%H","HEAD","--",...$n.map(te=>`:(literal)${k}/${te}`)])?.split(/\r?\n/u).find(te=>/^[a-f0-9]{40,64}$/u.test(te)&&tg(e,t,te,f))??null);let E=l.commit??S,A=!!E&&bi(e,["cat-file","-t",E])==="commit",M=u.archived===!0&&A&&tg(e,t,E,f),O=v===l.targetBranch&&(!u.bound_branch||s!==null||u.bound_branch===v)&&M,L=!1,$=!1,J=null,F=n.verifyRemote&&l.action!=="local"?"unavailable":"notChecked",re="notChecked";if(n.verifyRemote&&O&&l.action!=="local"&&l.remote&&g&&eg(e,l.remote)===g&&eg(e,l.remote,!0)===g){let X=`refs/heads/${l.targetBranch}`,te=Ri(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",l.remote,X],!0),Ve=te?.split(/\r?\n/u)??[],R=Ve.length===1?/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(Ve[0]):null,N=R?.[2]===X?R[1]:null;L=!!E&&!!N&&ng(e,E,N),F=L?"verified":te===""?"missing":te===null||!N||bi(e,["cat-file","-t",N])!=="commit"?"unavailable":"missing";let q=ZE(g),me=q&&l.prUrl?Cs(l.prUrl,q):null,y=L||te==="",x=C=>C.headRefName===l.targetBranch&&typeof C.headRefOid=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(C.headRefOid)&&(L?C.headRefOid===N&&["OPEN","MERGED"].includes(C.state):te===""&&C.state==="MERGED"&&!!E&&ng(e,E,C.headRefOid));if(y&&l.action==="pr"&&(re="unavailable"),y&&l.action==="pr"&&me&&q){let C=Ri(e,"gh",["pr","view",me,"--repo",q,"--json","url,headRefName,headRefOid,state"],!0);try{let P=C?qn(JSON.parse(C)):null;$=!!P&&typeof P.url=="string"&&Cs(P.url,q)===me&&x(P),re=$?"verified":P?"missing":"unavailable"}catch{$=!1,re="unavailable"}}else if(y&&l.action==="pr"&&!l.prUrl&&q){let C=Ri(e,"gh",["pr","list","--repo",q,"--head",l.targetBranch,"--state","all","--json","url,headRefName,headRefOid,state","--limit","100"],!0);try{let P=C===null?null:JSON.parse(C);if(!Array.isArray(P)||P.length>=100)throw new Error("Incomplete PR discovery");let I=P.map(qn).filter(W=>typeof W.url=="string"&&Cs(W.url,q)&&x(W));I.length===1?(J=Cs(I[0].url,q),$=!0,re="verified"):re=I.length===0?"missing":"unavailable"}catch{re="unavailable"}}}return{delivery:w,verification:{status:O&&(l.action==="local"||(l.action==="push"?L:$))?"complete":"needsVerification",currentBranch:v,commitExists:A,archiveCommitted:M,observedCommit:S,observedPrUrl:J,remoteVerified:L,prVerified:$,remoteStatus:F,prStatus:re}}}var mr="comet.resume_probe.v1";function cg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tx(e){if(!cg(e))throw new Error("Invalid CometResumeProbeInput: input must be an object");if(e.schema_version!==mr)throw new Error(`Invalid CometResumeProbeInput: schema_version must be ${mr}`);if(typeof e.utterance!="string")throw new Error("Invalid CometResumeProbeInput: utterance must be a string");let t=cg(e.agent_context)?e.agent_context:{};return{schema_version:mr,utterance:e.utterance,locale:typeof e.locale=="string"?e.locale:"unknown",agent_context:{non_trivial_work:t.non_trivial_work===!0,already_in_comet_flow:t.already_in_comet_flow===!0}}}function Pe(e,t,n,r,i=[]){return{schema_version:mr,action:e,changeName:t?.name??null,phase:t?.phase??null,nextCommand:e==="auto_resume"||e==="ask_user"?t?.nextCommand??null:null,confidence:n,reason:r,evidence:i}}async function nx(e,t,n){return await xe(e,t,{label:n,expected:"file"})?ie(e,t,{label:n}):""}async function $l(e,t,n){let r=["proposal.md","design.md","tasks.md"],i=[n.name,n.workflow,n.phase];for(let o of r)i.push(await nx(e,`${t}/${o}`,`Classic change ${n.name} ${o}`));return i.join(`
|
|
186
|
+
`).toLowerCase()}function rx(e,t){switch(e){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return t==="hotfix"||t==="tweak"?`/comet-${t}`:"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}function fg(e,t,n){let r=n.classic,i=n.unknownKeys.filter(o=>o!=="run_id");return r?i.length>0?{name:t,valid:!1,workflow:r.workflow,phase:r.phase,currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`unknown field(s): ${i.join(", ")}`}:{name:t,valid:!0,workflow:r.workflow,phase:r.phase,currentStep:null,nextCommand:rx(r.phase,r.workflow),runtimeMode:"engine-projection",runtimeEval:null,evidence:[]}:{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`${e} does not contain valid Comet state`}}async function ix(e,t){return await xe(e,`${t}/proposal.md`,{label:"Classic proposal",expected:"file"})||await xe(e,`${t}/design.md`,{label:"Classic design",expected:"file"})||await xe(e,`${t}/tasks.md`,{label:"Classic tasks",expected:"file"})}async function pg(e,t,n){let r=await ie(e,n,{label:"Classic change state"}),i=await ml(e,"classic",t);if(!ht(r)&&!i)return{state:null,lostRun:!1};let o=(u,f)=>({state:f,lostRun:!1,...u.status==="cancelled"?{cancellation:cl(u)?"complete":"pending"}:{}}),a=()=>{let u=(0,dg.parseDocument)(r,{uniqueKeys:!0});if(u.errors.length>0)return null;let f=u.toJS(),d=_n(f[nr],t);if(!d)return null;let s=Ze(f).classic;return s&&d.input&&typeof d.input=="object"&&!Array.isArray(d.input)&&d.input.change===t&&d.state.phase===s.phase?o(d,s):null};if(!i){let u=a();if(u)return u;let f=await Qh(ql.dirname(n),r);return f?{state:f,lostRun:!1}:{state:null,lostRun:!0}}try{let f=await Qt({rootDir:ql.join(await Dt(e),"sdk-runs","classic")}).read(i.runId);if(!f)return a()??{state:null,lostRun:!0};if(f.workflow.id!==`comet-${i.application}`||!f.input||typeof f.input!="object"||Array.isArray(f.input)||f.input.change!==t)return{state:null,lostRun:!0};let d=Ze(ai(f.state)).classic;return d?o(f,d):{state:null,lostRun:!0}}catch{return{state:null,lostRun:!0}}}async function ox(e){let t=(await Ne(e)).changesDir;if(!(await ct(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return[];let r=await Bs(t),i=[];for(let o of r){if(o==="archive"||cr(o))continue;let a=await us(o,e);if(!a.exists)continue;let u=a.directory;if(!a.stateExists){if(!await ix(e,u))continue;let v={name:o,workflow:"unknown",phase:"invalid",nextCommand:null,diagnostic:{name:o,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:"missing Comet state"},buildPause:null,hasClassicProjection:!1,verifyResult:null,archived:!1,text:"",missingCometState:!0};v.text=await $l(e,u,v),i.push(v);continue}let d=await pg(e,o,await ee(u));if(d.cancellation==="complete")continue;let s=await xt(u,{migrate:!1});d.state&&(s.classic=d.state);let l=s.classic,m=fg(u,o,s),c=d.lostRun?{...m,valid:!1,nextCommand:null,error:`Classic change ${o} has a state file but lost its local Run history`}:m,p=!!l,h=l?.phase??c.phase,g=l?.workflow??c.workflow;if((h==="archive"||l?.archived)&&d.cancellation!=="pending")continue;let w={name:o,workflow:g,phase:h,nextCommand:d.cancellation==="pending"?null:c.nextCommand,diagnostic:c,buildPause:l?.buildPause??null,hasClassicProjection:p,verifyResult:l?.verifyResult??null,archived:l?.archived??!1,text:"",missingCometState:!1,...d.cancellation==="pending"?{cancellationPending:!0}:{}};w.text=await $l(e,u,w),i.push(w)}return i}function sx(e){let t=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(e)?.[1]??e;return cr(t)===null?t:null}async function ax(e){let t=await Ne(e);if(!(await ct(e,t.archiveDir,{label:"Classic archive directory",expected:"directory"})).exists)return[];let r=(await Bs(t.archiveDir)).map(a=>({entry:a,name:sx(a)})).filter(a=>a.name!==null),i=[],o=8;for(let a=0;a<r.length;a+=o){let u=await Promise.all(r.slice(a,a+o).map(async({entry:f,name:d})=>{let s=ql.join(t.archiveDir,f),l=await ct(e,s,{label:`Classic archived change ${f}`,expected:"directory"});if(!l.exists)return null;let m=await xt(l.target,{migrate:!1}),c=await pg(e,d,await ee(l.target));if(c.cancellation==="complete")return null;c.state&&(m.classic=c.state);let p=m.classic;if(!p?.archived||p.phase!=="archive")return null;let h=await ag(e,l.target,{evidence:!1});if(["complete","local-verified"].includes(h.verification.status))return null;let g=fg(l.target,d,m),w=c.lostRun?{...g,valid:!1,nextCommand:null,error:`Classic change ${d} has a state file but lost its local Run history`}:g,v={name:d,workflow:p.workflow,phase:"archive",nextCommand:c.cancellation==="pending"?null:w.nextCommand,diagnostic:w,buildPause:null,hasClassicProjection:!0,verifyResult:p.verifyResult,archived:!0,text:"",missingCometState:!1,...c.cancellation==="pending"?{cancellationPending:!0}:{}};return v.text=await $l(e,l.target,v),v}));for(let f of u)f&&i.push(f)}return i}var cx=["continue","resume","carry on","finish","run it","commit","verify","archive","继续","接着","恢复","跑完","提交","验证","归档","修刚才"],lx=["what","why","how","explain","summarize","reliable","靠谱吗","是什么","为什么","解释","总结","取名","命名"],ux=new Set(["add","build","cache","change","code","design","docs","file","fix","implement","plan","readme","task","test","update","修改","更新","修复","添加","文档","任务","计划","实现"]),dx=["do not resume","don't resume","without comet","skip comet","不要恢复","不走 comet","不要走 comet","直接解释","只回答"];function Ll(e,t){return t.some(n=>e.includes(n))}function lg(e){return e.missingCometState||!e.hasClassicProjection||!e.diagnostic.valid||e.phase==="archive"||e.verifyResult==="fail"||e.diagnostic.runtimeEval&&!e.diagnostic.runtimeEval.passed?!0:e.phase!=="build"?!1:e.buildPause==="plan-ready"}function ug(e){return Pe("ask_user",e,"low","Classic Run is cancelled but an original Archive or child Run still has an unresolved business result. Preserve the records and complete its business recovery; ordinary task cleanup belongs to the Agent platform and needs no process-stop receipt.",[{source:"state",quote:"Run cancelled; original Archive or child Run business result is unresolved"}])}function fx(e,t){let n=e.toLowerCase(),r=[];n.includes(t.name.toLowerCase())&&r.push({source:"user",quote:t.name});let i=t.text.split(/[^a-zA-Z0-9_\-\u4e00-\u9fff/]+/u).map(a=>a.trim().toLowerCase()).filter(a=>a.length>=4&&!ux.has(a)),o=[...new Set(i.filter(a=>n.includes(a)))].slice(0,3);for(let a of o)r.push({source:"repo",quote:a});return r}async function px(e){return Fs(()=>new Promise(t=>{ex("git",["status","--short","--untracked-files=all"],{cwd:e,timeout:3e3,maxBuffer:2*1024*1024,windowsHide:!0},(n,r)=>{if(n||typeof r!="string"){t([]);return}t(r.split(/\r?\n/u).map(i=>i.trim()).filter(Boolean))})}))}async function mg(e,t){let n=tx(t),r=n.utterance.trim(),i=r.toLowerCase();if(n.agent_context.already_in_comet_flow)return Pe("out_of_scope",null,"low","already in Comet flow");if(Ll(i,dx))return Pe("out_of_scope",null,"low","user opted out of Comet resume",[{source:"user",quote:r}]);let o=await ox(e),a=new Set(o.map(({name:p})=>p)),u=(await ax(e)).filter(({name:p})=>!a.has(p)),f=[...o,...u];if(f.length===0)return Pe("none",null,"none","no active Comet changes");let d=await px(e);if(f.length>1){let p=f.find(h=>i.includes(h.name.toLowerCase()));return p?p.cancellationPending?ug(p):d.length>0?Pe("ask_user",p,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${d.length} dirty file(s)`}]):lg(p)?Pe("ask_user",p,"low","active change is at a decision point"):Pe("auto_resume",p,"high","request names an active change",[{source:"user",quote:p.name}]):Pe("ask_user",null,"low","multiple active changes require a change name")}let[s]=f;if(s.cancellationPending)return ug(s);if(d.length>0)return Pe("ask_user",s,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${d.length} dirty file(s)`}]);if(lg(s))return s.archived?Pe("ask_user",s,"low",s.diagnostic.valid?"archived change has pending delivery":"archived change execution history is unavailable",[{source:"state",quote:"archived: true"},{source:"state",quote:"delivery is not complete"}]):s.missingCometState?Pe("ask_user",s,"low","active OpenSpec change is missing Comet state"):Pe("ask_user",s,"low","active change is at a decision point",[{source:"state",quote:`phase: ${s.phase}`}]);let l=Ll(i,cx);if(!n.agent_context.non_trivial_work&&Ll(i,lx)&&!l)return Pe("out_of_scope",s,"low","user asked a question without workflow work");let c=fx(r,s);return l||c.length>0?Pe("auto_resume",s,"high","single active change and request is related",[{source:"state",quote:`phase: ${s.phase}`},...c]):n.agent_context.non_trivial_work?Pe("ask_user",s,"low","single active change exists but request looks unrelated"):Pe("out_of_scope",s,"low","request is not workflow work")}Ke();function xs(e,t,n){return{exitCode:e,...t===void 0?{}:{stdout:t},...n===void 0?{}:{stderr:n}}}function hg(){return xs(64,void 0,`Usage: comet-resume-probe.mjs probe <input-json>
|
|
187
|
+
Usage: comet-resume-probe.mjs probe --stdin`)}async function mx(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Is(Buffer.concat(e).toString("utf8"))}function hx(e){return{schema_version:mr,utterance:e,locale:"unknown",agent_context:{non_trivial_work:!0,already_in_comet_flow:!1}}}function gx(e){try{return JSON.parse(e)}catch{return hx(e)}}var gg=rs(async e=>{let[t,n]=e;if(t!=="probe")return hg();let r=n==="--stdin",i=r?await mx():n;if(!i)return hg();try{let o=r?gx(i):JSON.parse(i),a=await Ai(()=>mg(ns(),o));return xs(0,`${JSON.stringify(a,null,2)}
|
|
188
|
+
`)}catch(o){return o instanceof SyntaxError?xs(1,void 0,`Invalid JSON: ${o.message}`):xs(1,void 0,o instanceof Error?o.message:String(o))}});var wx=new Set([...si,"archive_confirmation","verify_failures","check_epoch","classic_profile","classic_migration","bound_branch"]),wg=new Set(zt.filter(e=>!wx.has(e))),Ml={workflow:["full","hotfix","tweak"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct","autonomous"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]};var yx=`
|
|
189
|
+
Options: --json (machine-readable output), --compact (requires --json), --help
|
|
190
|
+
精简视图用 outputView.references 的 JSON Pointer 定位重复字段;Request 模板保留完整;没有字节收益时返回原完整协议。去掉 --compact 获取完整协议。
|
|
191
|
+
JSON: one object with command and exitCode; data, stdout, stderr, summary and next are optional.
|
|
192
|
+
Use exitCode for success; do not parse human-readable stdout. Help text is in stdout in JSON mode.
|
|
193
|
+
`;function yg(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>"]},o={current:["comet state current","Reports the selected Classic change. Does not advance the phase."],next:["comet state next <change-name> [--details] [--continue]","Reports the next workflow action. --continue executes only recorded SDK commands and authorized internal steps, stopping for Agent work, user decisions, failures or unresolved executions.","SDK JSON includes recovery paths, configuration, compact task state and current Run handles. --details expands tasks, checkpoint content and full Run history."],select:["comet state select <change-name> [--details]","Writes the current change selection used by workflow routing.","SDK JSON includes recovery paths, configuration, compact task state and current Run handles. --details expands tasks, checkpoint content and full Run history."],rebind:["comet state rebind <change-name>","Updates the change branch binding to the current Git branch after validation."],"clear-selection":["comet state clear-selection","Clears the current change selection; does not delete change artifacts."],init:["comet state init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>]","Creates Classic workflow state. Follow the Open workflow for required user decisions."],scale:["comet state scale <change-name>","Reports a verification recommendation without changing verify_mode.","JSON: data.recommendation, data.selected and data.metrics. Scale is not a risk assessment.","Preserve an existing selection; record a new decision explicitly with state set when needed."],artifacts:["comet state artifacts <change-name>","Inspects the OpenSpec apply dependency closure, including dependencies of already-complete artifacts.","JSON: data.source, required, skipped, designRequired, files and problems. This does not execute implementation or verification.","Optional design is omitted only when the active schema excludes it from the required closure.","Skipped specs require explicit skip_specs: true, upstream support and no conflicting spec files.","Compat changes without .openspec.yaml retain the existing Classic artifact requirements."],"task-checkoff":["comet state task-checkoff <file> <task-text>","Checks that exactly one matching task is already checked. Does not write the task file or execute the task."],tasks:["comet state tasks <change-name> [--assign-ids]","Reads tasks.md as the task completion authority. Fenced examples are excluded.","--assign-ids persists IDs for legacy/new tasks in Open, Design or Build; existing IDs remain unchanged.","Assign IDs before generating the design handoff and plan. ID assignment changes task requirements.","JSON: data.authority, data.revision, data.needsIds, data.tasks and data.progress.","Each task has id, text, completed and line. Never use line/order as task identity.","Example: comet state tasks demo --assign-ids --json"],"task-complete":["comet state task-complete <change-name> <task-id> --expect <revision>","Records accepted task completion during Build; does not execute or independently verify work.","Use the revision returned by state tasks. Changed requirements reject the write; refresh and reassess the task.","Writes tasks.md under the state lock and synchronizes explicitly ID-mapped legacy plan checkboxes. Retries repair interrupted projection writes.","Reconcile code, checks and review evidence before recording completion; unchecked does not mean unimplemented.","Unmapped legacy items are preserved and reported as mapping-required; never match tasks by position or wording."],"sync-plan":["comet state sync-plan <change-name>","Synchronizes legacy plan checkboxes from tasks.md by explicit comet-task IDs; does not execute or accept work.","Rejects missing or unknown plan IDs. Reconcile extra requirements into tasks.md before mapping.","New plans should reference task IDs without a second completion checklist."],checkpoint:["comet state checkpoint <change-name> [--file <json>]","Reads a structured coordination checkpoint, or records an explicitly bounded work package during Build.","Input: taskIds, revision, stage, sessionId, evidence, unresolved, reviewRounds.","Include schemaVersion: 1. JSON state is .comet/coordination.json, separate from the Engine checkpoint.","Stages: implementing|task-review|checkoff|done|blocked. Evidence is a coordination record, not automatic acceptance.","Runtime checks task IDs and revision and renders subagent-progress.md. Do not maintain its projection manually."],delivery:["comet state delivery <change-name> [--file <json> | --verify]","Reads delivery authorization and observed progress, or records the user-authorized local|push|pr action.","Input: action, targetBranch, optional remote, commit and prUrl. Recording never performs remote writes.","First authorization requires Archive with passing verification before archival. Missing legacy authorization is never inferred.","Resume only authorized unfinished steps; supplied commit or PR text alone does not prove delivery.","compat 的 --verify 只做有界远端/PR 读取。SDK 的 --verify 使用当前 HEAD 转交 complete-delivery 校验并结束已批准的交付;已完成 Run 只核对历史回执和原提交对象,不将后续 HEAD、工作区或远端变化视为旧交付失败;普通读取不访问网络。","SDK 的 --file 仅接受与已批准 action、targetBranch、remote 一致的实际 commit 和可选 prUrl,不创建或覆盖授权。PR 首次交付使用 complete-delivery --commit <sha> --pr-url <url>,或 --file 提交完整记录。"],get:["comet state get <change-name> <field> [<field> ...]","Reads the requested fields from one state snapshot. JSON: data.change and data.fields (string values).","One field preserves the bare stdout value; multiple fields print field=value lines in request order.",`Fields: ${[...zt,...si].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):",...[...wg].map(f=>` ${f}${Ml[f]?`: ${Ml[f].join("|")}`:f==="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: ${Yh.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."]},a=r.find(f=>!f.startsWith("-")),u=e==="state"&&a&&o[a]||i[e];return u?`Usage: ${u.join(`
|
|
194
|
+
`)}
|
|
195
|
+
${yx}Command placeholders must be replaced with actual values.
|
|
196
|
+
`:void 0}function vg(e,t){let n=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)?h:{},r=n(e),i=n(r.entry),o=n(r.run??i.run??(typeof r.runId=="string"?r:void 0)),a=n(r.state??i.state??r),u=n(r.preparation??r.workspace??i.workspace),f=n(r.continuation??i.continuation??r.nextAction??i.nextAction),d=typeof u.projectRoot=="string"&&u.projectRoot!=="."?u.projectRoot:typeof f.cwd=="string"?f.cwd:typeof r.projectRoot=="string"?r.projectRoot:typeof i.projectRoot=="string"?i.projectRoot:t??null,s=a.stateVersion??a.state_version,l=a.status??o.status,{current:m,...c}=f,p=m===void 0?f:{...c,currentRef:r.continuation!==void 0?"data.continuation.current":"data.entry.continuation.current"};return{phase:typeof a.phase=="string"?a.phase:null,status:typeof l=="string"?l:null,stateVersion:typeof s=="number"?s:null,workspace:{cwd:d},continuation:Object.keys(f).length?{...p,cwd:d}:null,...Object.keys(o).length?{run:{id:typeof o.id=="string"?o.id:typeof o.runId=="string"?o.runId:null,revision:typeof o.revision=="number"?o.revision:null,status:typeof o.status=="string"?o.status:null}}:{}}}import{stripVTControlCharacters as vx}from"node:util";function kg(e,t={}){return{code:"CLASSIC_COMMAND_FAILED",message:vx(e instanceof Error?e.message:String(e)),...t}}import{randomUUID as kx}from"node:crypto";import{performance as bg}from"node:perf_hooks";var bx=7*864e5,Rx=1e4;async function Cx(e,t){let n=tr(await os(e,!0));try{n.exec(`PRAGMA busy_timeout=25; PRAGMA journal_mode=WAL;
|
|
197
|
+
CREATE TABLE IF NOT EXISTS samples (
|
|
198
|
+
id TEXT PRIMARY KEY, workflow TEXT NOT NULL, kind TEXT NOT NULL, command TEXT NOT NULL,
|
|
199
|
+
occurredAt TEXT NOT NULL, durationMs REAL NOT NULL, exitCode INTEGER NOT NULL,
|
|
200
|
+
gitCommands INTEGER NOT NULL, gitDurationMs REAL NOT NULL);
|
|
201
|
+
CREATE INDEX IF NOT EXISTS samples_time ON samples(occurredAt);
|
|
202
|
+
BEGIN IMMEDIATE;`),n.prepare("DELETE FROM samples WHERE occurredAt < ?").run(new Date(Date.now()-bx).toISOString()),n.prepare("INSERT INTO samples VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(kx(),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(Rx),n.exec("COMMIT")}finally{n.close()}}async function Rg(e,t){let n=bg.now(),r,i,o=!1,a=1,u=!0,{metrics:f}=await jm({projectRoot:e.projectRoot,workflow:e.workflow,kind:e.kind??"command",name:e.traceName??e.command,status:()=>{try{a=r?e.exitCode?.(r)??r.exitCode??1:e.errorExitCode?.(i)??1}catch{return u=!1,"unknown"}return a===0?"succeeded":"failed"}},()=>tu(async()=>{try{r=await t()}catch(s){o=!0,i=s}})),d=Math.max(0,bg.now()-n);try{if(!u)throw new Error("Runtime result classification unavailable");await Cx(await e.projectRoot(),{workflow:e.workflow,kind:e.kind??"command",command:e.command,occurredAt:new Date().toISOString(),durationMs:d,exitCode:a,...f})}catch{}if(o)throw i;return r}function Sx(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e,exitCode:t.exitCode,agent:vg(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}})+`
|
|
203
|
+
`,...t.envelope===void 0?{}:{envelope:t.envelope}}}async function Ex(e,t,n,r={}){let i=n.indexOf("--"),o=d=>i<0||d<i,a=n.some((d,s)=>o(s)&&d==="--json"),u=n.filter((d,s)=>!o(s)||d!=="--json"),f;try{let d=yg(e,u),s=()=>t(u,{json:a,invocationCwd:r.invocationCwd??process.cwd(),...r.projectRoot?{projectRoot:r.projectRoot}:{}});f=d?{exitCode:0,stdout:d}:e==="hook-guard"?await s():await Zl(()=>Rg({projectRoot:()=>r.projectRoot??ye(r.invocationCwd??process.cwd()),workflow:"classic",command:e,errorExitCode:l=>l instanceof bn?1:70},s))}catch(d){f={exitCode:d instanceof bn?1:70,stderr:d instanceof Error?d.message:String(d),data:{issues:[kg(d)]}}}return a?Sx(e,f):f}async function Cg(e,t,n=process.argv.slice(2)){let r=await Ex(e,t,n);return r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr+(r.stderr.endsWith(`
|
|
204
|
+
`)?"":`
|
|
205
|
+
`)),r.exitCode}process.exitCode=await Cg("resume-probe",gg);
|